diff --git a/contracts/asset-proxy/src/erc1155_proxy_wrapper.ts b/contracts/asset-proxy/src/erc1155_proxy_wrapper.ts index fe68af2cfb..8f69fdb7c9 100644 --- a/contracts/asset-proxy/src/erc1155_proxy_wrapper.ts +++ b/contracts/asset-proxy/src/erc1155_proxy_wrapper.ts @@ -76,7 +76,7 @@ export class ERC1155ProxyWrapper { txDefaults, artifacts, ); - this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync(); + this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync(); return this._proxyContract; } /** @@ -113,19 +113,13 @@ export class ERC1155ProxyWrapper { this._validateProxyContractExistsOrThrow(); const assetData = assetData_ === undefined - ? await this._devUtils.encodeERC1155AssetData.callAsync( - contractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ) + ? await this._devUtils + .encodeERC1155AssetData(contractAddress, tokensToTransfer, valuesToTransfer, receiverCallbackData) + .callAsync() : assetData_; - const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - from, - to, - valueMultiplier, - ); + const data = this._assetProxyInterface + .transferFrom(assetData, from, to, valueMultiplier) + .getABIEncodedTransactionData(); return data; } /** @@ -173,19 +167,13 @@ export class ERC1155ProxyWrapper { this._validateProxyContractExistsOrThrow(); const assetData = assetData_ === undefined - ? await this._devUtils.encodeERC1155AssetData.callAsync( - contractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ) + ? await this._devUtils + .encodeERC1155AssetData(contractAddress, tokensToTransfer, valuesToTransfer, receiverCallbackData) + .callAsync() : assetData_; - const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - from, - to, - valueMultiplier, - ); + const data = this._assetProxyInterface + .transferFrom(assetData, from, to, valueMultiplier) + .getABIEncodedTransactionData(); const txHash = await this._web3Wrapper.sendTransactionAsync({ to: (this._proxyContract as ERC1155ProxyContract).address, data, @@ -366,7 +354,7 @@ export class ERC1155ProxyWrapper { this._validateProxyContractExistsOrThrow(); const tokenContract = this._getContractFromAddress(contractAddress); const operator = (this._proxyContract as ERC1155ProxyContract).address; - const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator); + const didApproveAll = await tokenContract.isApprovedForAll(userAddress, operator).callAsync(); return didApproveAll; } public getFungibleTokenIds(): BigNumber[] { diff --git a/contracts/asset-proxy/src/erc20_wrapper.ts b/contracts/asset-proxy/src/erc20_wrapper.ts index c928375a92..fa1c5661fd 100644 --- a/contracts/asset-proxy/src/erc20_wrapper.ts +++ b/contracts/asset-proxy/src/erc20_wrapper.ts @@ -58,7 +58,7 @@ export class ERC20Wrapper { txDefaults, artifacts, ); - this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync(); + this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync(); return this._proxyContract; } public getProxyId(): string { @@ -70,43 +70,39 @@ export class ERC20Wrapper { this._validateProxyContractExistsOrThrow(); for (const dummyTokenContract of this._dummyTokenContracts) { for (const tokenOwnerAddress of this._tokenOwnerAddresses) { - await dummyTokenContract.setBalance.awaitTransactionSuccessAsync( - tokenOwnerAddress, - constants.INITIAL_ERC20_BALANCE, - { from: this._contractOwnerAddress }, - ); - await dummyTokenContract.approve.awaitTransactionSuccessAsync( - (this._proxyContract as ERC20ProxyContract).address, - constants.INITIAL_ERC20_ALLOWANCE, - { from: tokenOwnerAddress }, - ); + await dummyTokenContract + .setBalance(tokenOwnerAddress, constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync({ from: this._contractOwnerAddress }); + await dummyTokenContract + .approve((this._proxyContract as ERC20ProxyContract).address, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync({ from: tokenOwnerAddress }); } } } public async getBalanceAsync(userAddress: string, assetData: string): Promise { const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData); - const balance = new BigNumber(await tokenContract.balanceOf.callAsync(userAddress)); + const balance = new BigNumber(await tokenContract.balanceOf(userAddress).callAsync()); return balance; } public async setBalanceAsync(userAddress: string, assetData: string, amount: BigNumber): Promise { const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData); - await tokenContract.setBalance.awaitTransactionSuccessAsync( - userAddress, - amount, - { from: this._contractOwnerAddress }, - { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }, - ); + await tokenContract + .setBalance(userAddress, amount) + .awaitTransactionSuccessAsync( + { from: this._contractOwnerAddress }, + { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }, + ); } public async getProxyAllowanceAsync(userAddress: string, assetData: string): Promise { const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData); const proxyAddress = (this._proxyContract as ERC20ProxyContract).address; - const allowance = new BigNumber(await tokenContract.allowance.callAsync(userAddress, proxyAddress)); + const allowance = new BigNumber(await tokenContract.allowance(userAddress, proxyAddress).callAsync()); return allowance; } public async setAllowanceAsync(userAddress: string, assetData: string, amount: BigNumber): Promise { const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData); const proxyAddress = (this._proxyContract as ERC20ProxyContract).address; - await tokenContract.approve.awaitTransactionSuccessAsync(proxyAddress, amount, { from: userAddress }); + await tokenContract.approve(proxyAddress, amount).awaitTransactionSuccessAsync({ from: userAddress }); } public async getBalancesAsync(): Promise { this._validateDummyTokenContractsExistOrThrow(); @@ -115,7 +111,7 @@ export class ERC20Wrapper { const balanceInfo: Array<{ tokenOwnerAddress: string; tokenAddress: string }> = []; for (const dummyTokenContract of this._dummyTokenContracts) { for (const tokenOwnerAddress of this._tokenOwnerAddresses) { - balances.push(await dummyTokenContract.balanceOf.callAsync(tokenOwnerAddress)); + balances.push(await dummyTokenContract.balanceOf(tokenOwnerAddress).callAsync()); balanceInfo.push({ tokenOwnerAddress, tokenAddress: dummyTokenContract.address, @@ -149,7 +145,7 @@ export class ERC20Wrapper { return tokenAddresses; } private async _getTokenContractFromAssetDataAsync(assetData: string): Promise { - const [proxyId, tokenAddress] = await this._devUtils.decodeERC20AssetData.callAsync(assetData); // tslint:disable-line:no-unused-variable + const [proxyId, tokenAddress] = await this._devUtils.decodeERC20AssetData(assetData).callAsync(); // tslint:disable-line:no-unused-variable const tokenContractIfExists = _.find(this._dummyTokenContracts, c => c.address === tokenAddress); if (tokenContractIfExists === undefined) { throw new Error(`Token: ${tokenAddress} was not deployed through ERC20Wrapper`); diff --git a/contracts/asset-proxy/src/erc721_wrapper.ts b/contracts/asset-proxy/src/erc721_wrapper.ts index cbee407178..da6fa4aa22 100644 --- a/contracts/asset-proxy/src/erc721_wrapper.ts +++ b/contracts/asset-proxy/src/erc721_wrapper.ts @@ -46,7 +46,7 @@ export class ERC721Wrapper { txDefaults, artifacts, ); - this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync(); + this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync(); return this._proxyContract; } public getProxyId(): string { @@ -80,7 +80,7 @@ export class ERC721Wrapper { } public async doesTokenExistAsync(tokenAddress: string, tokenId: BigNumber): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - const owner = await tokenContract.ownerOf.callAsync(tokenId); + const owner = await tokenContract.ownerOf(tokenId).callAsync(); const doesExist = owner !== constants.NULL_ADDRESS; return doesExist; } @@ -95,14 +95,14 @@ export class ERC721Wrapper { ): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); const proxyAddress = (this._proxyContract as ERC721ProxyContract).address; - await tokenContract.setApprovalForAll.awaitTransactionSuccessAsync(proxyAddress, isApproved, { + await tokenContract.setApprovalForAll(proxyAddress, isApproved).awaitTransactionSuccessAsync({ from: ownerAddress, }); } public async approveAsync(to: string, tokenAddress: string, tokenId: BigNumber): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); const tokenOwner = await this.ownerOfAsync(tokenAddress, tokenId); - await tokenContract.approve.awaitTransactionSuccessAsync(to, tokenId, { from: tokenOwner }); + await tokenContract.approve(to, tokenId).awaitTransactionSuccessAsync({ from: tokenOwner }); } public async transferFromAsync( tokenAddress: string, @@ -111,28 +111,28 @@ export class ERC721Wrapper { userAddress: string, ): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - await tokenContract.transferFrom.awaitTransactionSuccessAsync(currentOwner, userAddress, tokenId, { + await tokenContract.transferFrom(currentOwner, userAddress, tokenId).awaitTransactionSuccessAsync({ from: currentOwner, }); } public async mintAsync(tokenAddress: string, tokenId: BigNumber, userAddress: string): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - await tokenContract.mint.awaitTransactionSuccessAsync(userAddress, tokenId, { + await tokenContract.mint(userAddress, tokenId).awaitTransactionSuccessAsync({ from: this._contractOwnerAddress, }); } public async burnAsync(tokenAddress: string, tokenId: BigNumber, owner: string): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - await tokenContract.burn.awaitTransactionSuccessAsync(owner, tokenId, { from: this._contractOwnerAddress }); + await tokenContract.burn(owner, tokenId).awaitTransactionSuccessAsync({ from: this._contractOwnerAddress }); } public async ownerOfAsync(tokenAddress: string, tokenId: BigNumber): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - const owner = await tokenContract.ownerOf.callAsync(tokenId); + const owner = await tokenContract.ownerOf(tokenId).callAsync(); return owner; } public async isOwnerAsync(userAddress: string, tokenAddress: string, tokenId: BigNumber): Promise { const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - const tokenOwner = await tokenContract.ownerOf.callAsync(tokenId); + const tokenOwner = await tokenContract.ownerOf(tokenId).callAsync(); const isOwner = tokenOwner === userAddress; return isOwner; } @@ -140,13 +140,13 @@ export class ERC721Wrapper { this._validateProxyContractExistsOrThrow(); const tokenContract = this._getTokenContractFromAssetData(tokenAddress); const operator = (this._proxyContract as ERC721ProxyContract).address; - const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator); + const didApproveAll = await tokenContract.isApprovedForAll(userAddress, operator).callAsync(); return didApproveAll; } public async isProxyApprovedAsync(tokenAddress: string, tokenId: BigNumber): Promise { this._validateProxyContractExistsOrThrow(); const tokenContract = this._getTokenContractFromAssetData(tokenAddress); - const approvedAddress = await tokenContract.getApproved.callAsync(tokenId); + const approvedAddress = await tokenContract.getApproved(tokenId).callAsync(); const proxyAddress = (this._proxyContract as ERC721ProxyContract).address; const isProxyAnApprovedOperator = approvedAddress === proxyAddress; return isProxyAnApprovedOperator; @@ -163,7 +163,7 @@ export class ERC721Wrapper { dummyTokenContract.address ]; for (const tokenId of initialTokenOwnerIds) { - tokenOwnerAddresses.push(await dummyTokenContract.ownerOf.callAsync(tokenId)); + tokenOwnerAddresses.push(await dummyTokenContract.ownerOf(tokenId).callAsync()); tokenInfo.push({ tokenId, tokenAddress: dummyTokenContract.address, diff --git a/contracts/asset-proxy/test/authorizable.ts b/contracts/asset-proxy/test/authorizable.ts index 1685c609f9..d4b5b58a84 100644 --- a/contracts/asset-proxy/test/authorizable.ts +++ b/contracts/asset-proxy/test/authorizable.ts @@ -49,21 +49,21 @@ describe('Authorizable', () => { describe('addAuthorizedAddress', () => { it('should revert if not called by owner', async () => { await expectTransactionFailedAsync( - authorizable.addAuthorizedAddress.sendTransactionAsync(notOwner, { from: notOwner }), + authorizable.addAuthorizedAddress(notOwner).sendTransactionAsync({ from: notOwner }), RevertReason.OnlyContractOwner, ); }); it('should allow owner to add an authorized address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const isAuthorized = await authorizable.authorized.callAsync(address); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const isAuthorized = await authorizable.authorized(address).callAsync(); expect(isAuthorized).to.be.true(); }); it('should revert if owner attempts to authorize a duplicate address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); return expectTransactionFailedAsync( - authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }), + authorizable.addAuthorizedAddress(address).sendTransactionAsync({ from: owner }), RevertReason.TargetAlreadyAuthorized, ); }); @@ -71,23 +71,23 @@ describe('Authorizable', () => { describe('removeAuthorizedAddress', () => { it('should revert if not called by owner', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); await expectTransactionFailedAsync( - authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: notOwner }), + authorizable.removeAuthorizedAddress(address).sendTransactionAsync({ from: notOwner }), RevertReason.OnlyContractOwner, ); }); it('should allow owner to remove an authorized address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const isAuthorized = await authorizable.authorized.callAsync(address); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const isAuthorized = await authorizable.authorized(address).callAsync(); expect(isAuthorized).to.be.false(); }); it('should revert if owner attempts to remove an address that is not authorized', async () => { return expectTransactionFailedAsync( - authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { + authorizable.removeAuthorizedAddress(address).sendTransactionAsync({ from: owner, }), RevertReason.TargetNotAuthorized, @@ -97,10 +97,10 @@ describe('Authorizable', () => { describe('removeAuthorizedAddressAtIndex', () => { it('should revert if not called by owner', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const index = new BigNumber(0); await expectTransactionFailedAsync( - authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { + authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({ from: notOwner, }), RevertReason.OnlyContractOwner, @@ -108,10 +108,10 @@ describe('Authorizable', () => { }); it('should revert if index is >= authorities.length', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const index = new BigNumber(1); return expectTransactionFailedAsync( - authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { + authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({ from: owner, }), RevertReason.IndexOutOfBounds, @@ -121,7 +121,7 @@ describe('Authorizable', () => { it('should revert if owner attempts to remove an address that is not authorized', async () => { const index = new BigNumber(0); return expectTransactionFailedAsync( - authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { + authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({ from: owner, }), RevertReason.TargetNotAuthorized, @@ -131,11 +131,11 @@ describe('Authorizable', () => { it('should revert if address at index does not match target', async () => { const address1 = address; const address2 = notOwner; - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address1, { from: owner }); - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address2, { from: owner }); + await authorizable.addAuthorizedAddress(address1).awaitTransactionSuccessAsync({ from: owner }); + await authorizable.addAuthorizedAddress(address2).awaitTransactionSuccessAsync({ from: owner }); const address1Index = new BigNumber(0); return expectTransactionFailedAsync( - authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address2, address1Index, { + authorizable.removeAuthorizedAddressAtIndex(address2, address1Index).sendTransactionAsync({ from: owner, }), RevertReason.AuthorizedAddressMismatch, @@ -143,26 +143,26 @@ describe('Authorizable', () => { }); it('should allow owner to remove an authorized address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const index = new BigNumber(0); - await authorizable.removeAuthorizedAddressAtIndex.awaitTransactionSuccessAsync(address, index, { + await authorizable.removeAuthorizedAddressAtIndex(address, index).awaitTransactionSuccessAsync({ from: owner, }); - const isAuthorized = await authorizable.authorized.callAsync(address); + const isAuthorized = await authorizable.authorized(address).callAsync(); expect(isAuthorized).to.be.false(); }); }); describe('getAuthorizedAddresses', () => { it('should return all authorized addresses', async () => { - const initial = await authorizable.getAuthorizedAddresses.callAsync(); + const initial = await authorizable.getAuthorizedAddresses().callAsync(); expect(initial).to.have.length(0); - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const afterAdd = await authorizable.getAuthorizedAddresses.callAsync(); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const afterAdd = await authorizable.getAuthorizedAddresses().callAsync(); expect(afterAdd).to.have.length(1); expect(afterAdd).to.include(address); - await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const afterRemove = await authorizable.getAuthorizedAddresses.callAsync(); + await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const afterRemove = await authorizable.getAuthorizedAddresses().callAsync(); expect(afterRemove).to.have.length(0); }); }); diff --git a/contracts/asset-proxy/test/erc1155_proxy.ts b/contracts/asset-proxy/test/erc1155_proxy.ts index 4f26770972..8a7f852065 100644 --- a/contracts/asset-proxy/test/erc1155_proxy.ts +++ b/contracts/asset-proxy/test/erc1155_proxy.ts @@ -77,8 +77,8 @@ describe('ERC1155Proxy', () => { const usedAddresses = ([owner, notAuthorized, authorized, spender, receiver] = _.slice(accounts, 0, 5)); erc1155ProxyWrapper = new ERC1155ProxyWrapper(provider, usedAddresses, owner); erc1155Proxy = await erc1155ProxyWrapper.deployProxyAsync(); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(erc1155Proxy.address, { from: owner }); + await erc1155Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + await erc1155Proxy.addAuthorizedAddress(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: owner }); // deploy & configure ERC1155 tokens and receiver [erc1155Wrapper] = await erc1155ProxyWrapper.deployDummyContractsAsync(); erc1155Contract = erc1155Wrapper.getContract(); @@ -122,7 +122,7 @@ describe('ERC1155Proxy', () => { ); }); it('should have an id of 0xa7cb5fb7', async () => { - const proxyId = await erc1155Proxy.getProxyId.callAsync(); + const proxyId = await erc1155Proxy.getProxyId().callAsync(); const expectedProxyId = AssetProxyId.ERC1155; expect(proxyId).to.equal(expectedProxyId); }); @@ -637,12 +637,14 @@ describe('ERC1155Proxy', () => { return value.times(valueMultiplier); }); const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); const extraData = '0102030405060708091001020304050607080910010203040506070809100102'; const assetDataWithExtraData = `${assetData}${extraData}`; // check balances before transfer @@ -697,14 +699,16 @@ describe('ERC1155Proxy', () => { // create token await erc1155Wrapper .getContract() - .createWithType.awaitTransactionSuccessAsync(tokenToCreate, tokenUri, { + .createWithType(tokenToCreate, tokenUri) + .awaitTransactionSuccessAsync({ from: owner, }); // mint balance for spender await erc1155Wrapper .getContract() - .mintFungible.awaitTransactionSuccessAsync(tokenToCreate, [spender], [spenderInitialBalance], { + .mintFungible(tokenToCreate, [spender], [spenderInitialBalance]) + .awaitTransactionSuccessAsync({ from: owner, }); } @@ -742,7 +746,7 @@ describe('ERC1155Proxy', () => { // hand encode optimized assetData because our tooling (based on LibAssetData.sol/encodeERC1155AssetData) does not use optimized encoding const assetDataContract = new IAssetDataContract(constants.NULL_ADDRESS, provider); - const selector = assetDataContract.ERC1155Assets.getSelector(); + const selector = assetDataContract.getSelector('ERC1155Assets'); const assetDataWithoutContractAddress = '0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000040102030400000000000000000000000000000000000000000000000000000000'; const assetData = `${selector}000000000000000000000000${erc1155ContractAddress.substr( @@ -797,14 +801,16 @@ describe('ERC1155Proxy', () => { // create token await erc1155Wrapper .getContract() - .createWithType.awaitTransactionSuccessAsync(tokenToCreate, tokenUri, { + .createWithType(tokenToCreate, tokenUri) + .awaitTransactionSuccessAsync({ from: owner, }); // mint balance for spender await erc1155Wrapper .getContract() - .mintFungible.awaitTransactionSuccessAsync(tokenToCreate, [spender], [spenderInitialBalance], { + .mintFungible(tokenToCreate, [spender], [spenderInitialBalance]) + .awaitTransactionSuccessAsync({ from: owner, }); } @@ -850,12 +856,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [new BigNumber(2), new BigNumber(2)]; const valueMultiplier = new BigNumber(2); // create callback data that is the encoded version of `valuesToTransfer` - const generatedAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const generatedAssetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // remove the function selector and contract address from check, as these change on each test const offsetToTokenIds = 74; const assetDataSelectorAndContractAddress = generatedAssetData.substr(0, offsetToTokenIds); @@ -922,14 +930,16 @@ describe('ERC1155Proxy', () => { // create token await erc1155Wrapper .getContract() - .createWithType.awaitTransactionSuccessAsync(tokenToCreate, tokenUri, { + .createWithType(tokenToCreate, tokenUri) + .awaitTransactionSuccessAsync({ from: owner, }); // mint balance for spender await erc1155Wrapper .getContract() - .mintFungible.awaitTransactionSuccessAsync(tokenToCreate, [spender], [spenderInitialBalance], { + .mintFungible(tokenToCreate, [spender], [spenderInitialBalance]) + .awaitTransactionSuccessAsync({ from: owner, }); } @@ -972,12 +982,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [new BigNumber(1), new BigNumber(2)]; const valueMultiplier = new BigNumber(2); // create callback data that is the encoded version of `valuesToTransfer` - const generatedAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const generatedAssetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // remove the function selector and contract address from check, as these change on each test const offsetToTokenIds = 74; const assetDataSelectorAndContractAddress = generatedAssetData.substr(0, offsetToTokenIds); @@ -1035,12 +1047,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1082,12 +1096,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1133,12 +1149,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1184,12 +1202,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1235,12 +1255,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1287,12 +1309,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1334,12 +1358,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1385,12 +1411,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1432,12 +1460,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // The asset data we just generated will look like this: // a7cb5fb7 // 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082 @@ -1483,12 +1513,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); const txData = await erc1155ProxyWrapper.getTransferFromAbiEncodedTxDataAsync( spender, receiverContract, @@ -1514,12 +1546,14 @@ describe('ERC1155Proxy', () => { const valuesToTransfer = [fungibleValueToTransferLarge]; const valueMultiplier = valueMultiplierSmall; const erc1155ContractAddress = erc1155Wrapper.getContract().address; - const assetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155ContractAddress, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const assetData = await devUtils + .encodeERC1155AssetData( + erc1155ContractAddress, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); const txData = await erc1155ProxyWrapper.getTransferFromAbiEncodedTxDataAsync( spender, receiverContract, @@ -1643,7 +1677,7 @@ describe('ERC1155Proxy', () => { it('should propagate revert reason from erc1155 contract failure', async () => { // disable transfers const shouldRejectTransfer = true; - await erc1155Receiver.setRejectTransferFlag.awaitTransactionSuccessAsync(shouldRejectTransfer, { + await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).awaitTransactionSuccessAsync({ from: owner, }); // setup test parameters diff --git a/contracts/asset-proxy/test/erc20bridge_proxy.ts b/contracts/asset-proxy/test/erc20bridge_proxy.ts index b10b74cb4f..5df7181165 100644 --- a/contracts/asset-proxy/test/erc20bridge_proxy.ts +++ b/contracts/asset-proxy/test/erc20bridge_proxy.ts @@ -41,8 +41,8 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => { env.txDefaults, artifacts, ); - testTokenAddress = await bridgeContract.testToken.callAsync(); - await assetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner); + testTokenAddress = await bridgeContract.testToken().callAsync(); + await assetProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync(); }); interface AssetDataOpts { @@ -99,7 +99,7 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => { } async function setTestTokenBalanceAsync(_owner: string, balance: Numberish): Promise { - await bridgeContract.setTestTokenBalance.awaitTransactionSuccessAsync(_owner, new BigNumber(balance)); + await bridgeContract.setTestTokenBalance(_owner, new BigNumber(balance)).awaitTransactionSuccessAsync(); } describe('transferFrom()', () => { @@ -129,13 +129,9 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => { async function transferFromAsync(opts?: Partial, caller?: string): Promise { const _opts = createTransferFromOpts(opts); - const { logs } = await assetProxy.transferFrom.awaitTransactionSuccessAsync( - encodeAssetData(_opts.assetData), - _opts.from, - _opts.to, - new BigNumber(_opts.amount), - { from: caller }, - ); + const { logs } = await assetProxy + .transferFrom(encodeAssetData(_opts.assetData), _opts.from, _opts.to, new BigNumber(_opts.amount)) + .awaitTransactionSuccessAsync({ from: caller }); return (logs as any) as DecodedLogs; } @@ -177,12 +173,9 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => { it('fails if asset data is truncated', async () => { const opts = createTransferFromOpts(); const truncatedAssetData = hexSlice(encodeAssetData(opts.assetData), 0, -1); - const tx = assetProxy.transferFrom.awaitTransactionSuccessAsync( - truncatedAssetData, - opts.from, - opts.to, - new BigNumber(opts.amount), - ); + const tx = assetProxy + .transferFrom(truncatedAssetData, opts.from, opts.to, new BigNumber(opts.amount)) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.rejected(); }); @@ -278,18 +271,18 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => { it('retrieves the balance of the encoded token', async () => { const _owner = randomAddress(); const balance = getRandomInteger(1, 100e18); - await bridgeContract.setTestTokenBalance.awaitTransactionSuccessAsync(_owner, balance); + await bridgeContract.setTestTokenBalance(_owner, balance).awaitTransactionSuccessAsync(); const assetData = createAssetData({ tokenAddress: testTokenAddress, }); - const actualBalance = await assetProxy.balanceOf.callAsync(encodeAssetData(assetData), _owner); + const actualBalance = await assetProxy.balanceOf(encodeAssetData(assetData), _owner).callAsync(); expect(actualBalance).to.bignumber.eq(balance); }); }); describe('getProxyId()', () => { it('returns the correct proxy ID', async () => { - const proxyId = await assetProxy.getProxyId.callAsync(); + const proxyId = await assetProxy.getProxyId().callAsync(); expect(proxyId).to.eq(PROXY_ID); }); }); diff --git a/contracts/asset-proxy/test/eth2dai_bridge.ts b/contracts/asset-proxy/test/eth2dai_bridge.ts index b368c8d4ad..445765e1cb 100644 --- a/contracts/asset-proxy/test/eth2dai_bridge.ts +++ b/contracts/asset-proxy/test/eth2dai_bridge.ts @@ -8,7 +8,6 @@ import { hexRandom, Numberish, randomAddress, - TransactionHelper, } from '@0x/contracts-test-utils'; import { AssetProxyId } from '@0x/types'; import { BigNumber, RawRevertError } from '@0x/utils'; @@ -26,7 +25,6 @@ import { } from './wrappers'; blockchainTests.resets('Eth2DaiBridge unit tests', env => { - const txHelper = new TransactionHelper(env.web3Wrapper, artifacts); let testContract: TestEth2DaiBridgeContract; before(async () => { @@ -41,7 +39,7 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => { describe('isValidSignature()', () => { it('returns success bytes', async () => { const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381'; - const result = await testContract.isValidSignature.callAsync(hexRandom(), hexRandom(_.random(0, 32))); + const result = await testContract.isValidSignature(hexRandom(), hexRandom(_.random(0, 32))).callAsync(); expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE); }); }); @@ -81,32 +79,30 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => { async function withdrawToAsync(opts?: Partial): Promise { const _opts = createWithdrawToOpts(opts); // Set the fill behavior. - await testContract.setFillBehavior.awaitTransactionSuccessAsync( - _opts.revertReason, - new BigNumber(_opts.fillAmount), - ); + await testContract + .setFillBehavior(_opts.revertReason, new BigNumber(_opts.fillAmount)) + .awaitTransactionSuccessAsync(); // Create tokens and balances. if (_opts.fromTokenAddress === undefined) { - [_opts.fromTokenAddress] = await txHelper.getResultAndReceiptAsync( - testContract.createToken, - new BigNumber(_opts.fromTokenBalance), - ); + const createTokenFn = testContract.createToken(new BigNumber(_opts.fromTokenBalance)); + _opts.fromTokenAddress = await createTokenFn.callAsync(); + await createTokenFn.awaitTransactionSuccessAsync(); } if (_opts.toTokenAddress === undefined) { - [_opts.toTokenAddress] = await txHelper.getResultAndReceiptAsync( - testContract.createToken, - constants.ZERO_AMOUNT, - ); + const createTokenFn = testContract.createToken(constants.ZERO_AMOUNT); + _opts.toTokenAddress = await createTokenFn.callAsync(); + await createTokenFn.awaitTransactionSuccessAsync(); } // Set the transfer behavior of `toTokenAddress`. - await testContract.setTransferBehavior.awaitTransactionSuccessAsync( - _opts.toTokenAddress, - _opts.toTokentransferRevertReason, - _opts.toTokenTransferReturnData, - ); + await testContract + .setTransferBehavior( + _opts.toTokenAddress, + _opts.toTokentransferRevertReason, + _opts.toTokenTransferReturnData, + ) + .awaitTransactionSuccessAsync(); // Call bridgeTransferFrom(). - const [result, { logs }] = await txHelper.getResultAndReceiptAsync( - testContract.bridgeTransferFrom, + const bridgeTransferFromFn = testContract.bridgeTransferFrom( // "to" token address _opts.toTokenAddress, // Random from address. @@ -117,6 +113,8 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => { // ABI-encode the "from" token address as the bridge data. hexLeftPad(_opts.fromTokenAddress as string), ); + const result = await bridgeTransferFromFn.callAsync(); + const { logs } = await bridgeTransferFromFn.awaitTransactionSuccessAsync(); return { opts: _opts, result, diff --git a/contracts/asset-proxy/test/proxies.ts b/contracts/asset-proxy/test/proxies.ts index 5f48bda4dd..6e908701a1 100644 --- a/contracts/asset-proxy/test/proxies.ts +++ b/contracts/asset-proxy/test/proxies.ts @@ -102,24 +102,24 @@ describe('Asset Transfer Proxies', () => { ); // Configure ERC20Proxy - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner }); + await erc20Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure ERC721Proxy - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner }); + await erc721Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure ERC115Proxy erc1155ProxyWrapper = new ERC1155ProxyWrapper(provider, usedAddresses, owner); erc1155Proxy = await erc1155ProxyWrapper.deployProxyAsync(); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner }); + await erc1155Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure MultiAssetProxy - await multiAssetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { from: owner }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { from: owner }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, { from: owner }); + await multiAssetProxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxy.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: owner }); // Deploy and configure ERC20 tokens const numDummyErc20ToDeploy = 2; @@ -149,26 +149,20 @@ describe('Asset Transfer Proxies', () => { ); await erc20Wrapper.setBalancesAndAllowancesAsync(); - await noReturnErc20Token.setBalance.awaitTransactionSuccessAsync(fromAddress, constants.INITIAL_ERC20_BALANCE, { + await noReturnErc20Token.setBalance(fromAddress, constants.INITIAL_ERC20_BALANCE).awaitTransactionSuccessAsync({ from: owner, }); - await noReturnErc20Token.approve.awaitTransactionSuccessAsync( - erc20Proxy.address, - constants.INITIAL_ERC20_ALLOWANCE, - { from: fromAddress }, - ); - await multipleReturnErc20Token.setBalance.awaitTransactionSuccessAsync( - fromAddress, - constants.INITIAL_ERC20_BALANCE, - { + await noReturnErc20Token + .approve(erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync({ from: fromAddress }); + await multipleReturnErc20Token + .setBalance(fromAddress, constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync({ from: owner, - }, - ); - await multipleReturnErc20Token.approve.awaitTransactionSuccessAsync( - erc20Proxy.address, - constants.INITIAL_ERC20_ALLOWANCE, - { from: fromAddress }, - ); + }); + await multipleReturnErc20Token + .approve(erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync({ from: fromAddress }); // Deploy and configure ERC721 tokens and receiver [erc721TokenA, erc721TokenB] = await erc721Wrapper.deployDummyTokensAsync(); @@ -220,23 +214,20 @@ describe('Asset Transfer Proxies', () => { ); }); it('should have an id of 0xf47261b0', async () => { - const proxyId = await erc20Proxy.getProxyId.callAsync(); + const proxyId = await erc20Proxy.getProxyId().callAsync(); const expectedProxyId = '0xf47261b0'; expect(proxyId).to.equal(expectedProxyId); }); describe('transferFrom', () => { it('should successfully transfer tokens', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Perform a transfer from fromAddress to toAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, @@ -257,17 +248,14 @@ describe('Asset Transfer Proxies', () => { it('should successfully transfer tokens that do not return a value', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(); // Perform a transfer from fromAddress to toAddress - const initialFromBalance = await noReturnErc20Token.balanceOf.callAsync(fromAddress); - const initialToBalance = await noReturnErc20Token.balanceOf.callAsync(toAddress); + const initialFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); + const initialToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, @@ -277,8 +265,8 @@ describe('Asset Transfer Proxies', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful - const newFromBalance = await noReturnErc20Token.balanceOf.callAsync(fromAddress); - const newToBalance = await noReturnErc20Token.balanceOf.callAsync(toAddress); + const newFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); + const newToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); expect(newFromBalance).to.be.bignumber.equal(initialFromBalance.minus(amount)); expect(newToBalance).to.be.bignumber.equal(initialToBalance.plus(amount)); }); @@ -286,18 +274,15 @@ describe('Asset Transfer Proxies', () => { it('should successfully transfer tokens and ignore extra assetData', async () => { // Construct ERC20 asset data const extraData = '0102030405060708'; - const encodedAssetData = `${await devUtils.encodeERC20AssetData.callAsync( - erc20TokenA.address, - )}${extraData}`; + const encodedAssetData = `${await devUtils + .encodeERC20AssetData(erc20TokenA.address) + .callAsync()}${extraData}`; // Perform a transfer from fromAddress to toAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, @@ -318,16 +303,13 @@ describe('Asset Transfer Proxies', () => { it('should do nothing if transferring 0 amount of a token', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Perform a transfer from fromAddress to toAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(0); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc20Proxy.address, @@ -348,17 +330,14 @@ describe('Asset Transfer Proxies', () => { it('should revert if allowances are too low', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Create allowance less than transfer amount. Set allowance on proxy. const allowance = new BigNumber(0); const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); - await erc20TokenA.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); + await erc20TokenA.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: fromAddress, }); const erc20Balances = await erc20Wrapper.getBalancesAsync(); @@ -377,21 +356,18 @@ describe('Asset Transfer Proxies', () => { it('should revert if allowances are too low and token does not return a value', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(); // Create allowance less than transfer amount. Set allowance on proxy. const allowance = new BigNumber(0); const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); - await noReturnErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); + await noReturnErc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: fromAddress, }); - const initialFromBalance = await noReturnErc20Token.balanceOf.callAsync(fromAddress); - const initialToBalance = await noReturnErc20Token.balanceOf.callAsync(toAddress); + const initialFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); + const initialToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); // Perform a transfer; expect this to fail. await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ @@ -401,23 +377,20 @@ describe('Asset Transfer Proxies', () => { }), RevertReason.TransferFailed, ); - const newFromBalance = await noReturnErc20Token.balanceOf.callAsync(fromAddress); - const newToBalance = await noReturnErc20Token.balanceOf.callAsync(toAddress); + const newFromBalance = await noReturnErc20Token.balanceOf(fromAddress).callAsync(); + const newToBalance = await noReturnErc20Token.balanceOf(toAddress).callAsync(); expect(newFromBalance).to.be.bignumber.equal(initialFromBalance); expect(newToBalance).to.be.bignumber.equal(initialToBalance); }); it('should revert if caller is not authorized', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ @@ -433,18 +406,15 @@ describe('Asset Transfer Proxies', () => { it('should revert if token returns more than 32 bytes', async () => { // Construct ERC20 asset data - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync( - multipleReturnErc20Token.address, - ); + const encodedAssetData = await devUtils + .encodeERC20AssetData(multipleReturnErc20Token.address) + .callAsync(); const amount = new BigNumber(10); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); - const initialFromBalance = await multipleReturnErc20Token.balanceOf.callAsync(fromAddress); - const initialToBalance = await multipleReturnErc20Token.balanceOf.callAsync(toAddress); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); + const initialFromBalance = await multipleReturnErc20Token.balanceOf(fromAddress).callAsync(); + const initialToBalance = await multipleReturnErc20Token.balanceOf(toAddress).callAsync(); // Perform a transfer; expect this to fail. await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ @@ -454,8 +424,8 @@ describe('Asset Transfer Proxies', () => { }), RevertReason.TransferFailed, ); - const newFromBalance = await multipleReturnErc20Token.balanceOf.callAsync(fromAddress); - const newToBalance = await multipleReturnErc20Token.balanceOf.callAsync(toAddress); + const newFromBalance = await multipleReturnErc20Token.balanceOf(fromAddress).callAsync(); + const newToBalance = await multipleReturnErc20Token.balanceOf(toAddress).callAsync(); expect(newFromBalance).to.be.bignumber.equal(initialFromBalance); expect(newToBalance).to.be.bignumber.equal(initialToBalance); }); @@ -475,28 +445,24 @@ describe('Asset Transfer Proxies', () => { ); }); it('should have an id of 0x02571792', async () => { - const proxyId = await erc721Proxy.getProxyId.callAsync(); + const proxyId = await erc721Proxy.getProxyId().callAsync(); const expectedProxyId = '0x02571792'; expect(proxyId).to.equal(expectedProxyId); }); describe('transferFrom', () => { it('should successfully transfer tokens', async () => { // Construct ERC721 asset data - const encodedAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const encodedAssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, @@ -506,28 +472,24 @@ describe('Asset Transfer Proxies', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.bignumber.equal(toAddress); }); it('should successfully transfer tokens and ignore extra assetData', async () => { // Construct ERC721 asset data const extraData = '0102030405060708'; - const encodedAssetData = `${await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - )}${extraData}`; + const encodedAssetData = `${await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync()}${extraData}`; // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, @@ -537,27 +499,23 @@ describe('Asset Transfer Proxies', () => { constants.AWAIT_TRANSACTION_MINED_MS, ); // Verify transfer was successful - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.bignumber.equal(toAddress); }); it('should not call onERC721Received when transferring to a smart contract', async () => { // Construct ERC721 asset data - const encodedAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const encodedAssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - erc721Receiver.address, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, erc721Receiver.address, amount) + .getABIEncodedTransactionData(); const logDecoder = new LogDecoder(web3Wrapper, { ...artifacts, ...erc721Artifacts }); const tx = await logDecoder.getTxWithDecodedLogsAsync( await web3Wrapper.sendTransactionAsync({ @@ -570,27 +528,23 @@ describe('Asset Transfer Proxies', () => { // Verify that no log was emitted by erc721 receiver expect(tx.logs.length).to.be.equal(1); // Verify transfer was successful - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.bignumber.equal(erc721Receiver.address); }); it('should revert if transferring 0 amount of a token', async () => { // Construct ERC721 asset data - const encodedAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const encodedAssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(0); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, @@ -599,27 +553,23 @@ describe('Asset Transfer Proxies', () => { }), RevertReason.InvalidAmount, ); - const newOwner = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); it('should revert if transferring > 1 amount of a token', async () => { // Construct ERC721 asset data - const encodedAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const encodedAssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(500); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, @@ -628,35 +578,31 @@ describe('Asset Transfer Proxies', () => { }), RevertReason.InvalidAmount, ); - const newOwner = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); it('should revert if allowances are too low', async () => { // Construct ERC721 asset data - const encodedAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const encodedAssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Remove blanket transfer approval for fromAddress. - await erc721TokenA.setApprovalForAll.awaitTransactionSuccessAsync(erc721Proxy.address, false, { + await erc721TokenA.setApprovalForAll(erc721Proxy.address, false).awaitTransactionSuccessAsync({ from: fromAddress, }); // Remove token transfer approval for fromAddress. - await erc721TokenA.approve.awaitTransactionSuccessAsync(constants.NULL_ADDRESS, erc721AFromTokenId, { + await erc721TokenA.approve(constants.NULL_ADDRESS, erc721AFromTokenId).awaitTransactionSuccessAsync({ from: fromAddress, }); // Perform a transfer; expect this to fail. const amount = new BigNumber(1); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, @@ -665,27 +611,23 @@ describe('Asset Transfer Proxies', () => { }), RevertReason.TransferFailed, ); - const newOwner = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); it('should revert if caller is not authorized', async () => { // Construct ERC721 asset data - const encodedAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const encodedAssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); // Verify pre-condition - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); // Perform a transfer from fromAddress to toAddress const amount = new BigNumber(1); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - encodedAssetData, - fromAddress, - toAddress, - amount, - ); + const data = assetProxyInterface + .transferFrom(encodedAssetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: erc721Proxy.address, @@ -694,7 +636,7 @@ describe('Asset Transfer Proxies', () => { }), RevertReason.SenderNotAuthorized, ); - const newOwner = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwner = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwner).to.be.equal(ownerFromAsset); }); }); @@ -712,7 +654,7 @@ describe('Asset Transfer Proxies', () => { ); }); it('should have an id of 0x94cfcdd7', async () => { - const proxyId = await multiAssetProxy.getProxyId.callAsync(); + const proxyId = await multiAssetProxy.getProxyId().callAsync(); // first 4 bytes of `keccak256('MultiAsset(uint256[],bytes[])')` const expectedProxyId = '0x94cfcdd7'; expect(proxyId).to.equal(expectedProxyId); @@ -721,16 +663,13 @@ describe('Asset Transfer Proxies', () => { it('should transfer a single ERC20 token', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -752,16 +691,15 @@ describe('Asset Transfer Proxies', () => { it('should dispatch an ERC20 transfer when input amount is 0', async () => { const inputAmount = constants.ZERO_AMOUNT; const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData]; - const assetData = assetDataInterface.MultiAsset.getABIEncodedTransactionData(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = assetDataInterface + .MultiAsset(amounts, nestedAssetData) + .getABIEncodedTransactionData(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); const logDecoder = new LogDecoder(web3Wrapper, { ...artifacts, ...erc20Artifacts }); const tx = await logDecoder.getTxWithDecodedLogsAsync( @@ -783,17 +721,14 @@ describe('Asset Transfer Proxies', () => { const inputAmount = new BigNumber(1); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); - const erc20AssetData1 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const erc20AssetData2 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData1 = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const erc20AssetData2 = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const amounts = [erc20Amount1, erc20Amount2]; const nestedAssetData = [erc20AssetData1, erc20AssetData2]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -816,17 +751,14 @@ describe('Asset Transfer Proxies', () => { const inputAmount = new BigNumber(1); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); - const erc20AssetData1 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const erc20AssetData2 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); + const erc20AssetData1 = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const erc20AssetData2 = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); const amounts = [erc20Amount1, erc20Amount2]; const nestedAssetData = [erc20AssetData1, erc20AssetData2]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -855,20 +787,16 @@ describe('Asset Transfer Proxies', () => { it('should transfer a single ERC721 token', async () => { const inputAmount = new BigNumber(1); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc721Amount]; const nestedAssetData = [erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -878,34 +806,29 @@ describe('Asset Transfer Proxies', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); }); it('should successfully transfer multiple of the same ERC721 token', async () => { const erc721Balances = await erc721Wrapper.getBalancesAsync(); const erc721AFromTokenId2 = erc721Balances[fromAddress][erc721TokenA.address][1]; - const erc721AssetData1 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); - const erc721AssetData2 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId2, - ); + const erc721AssetData1 = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); + const erc721AssetData2 = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId2) + .callAsync(); const inputAmount = new BigNumber(1); const erc721Amount = new BigNumber(1); const amounts = [erc721Amount, erc721Amount]; const nestedAssetData = [erc721AssetData1, erc721AssetData2]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); - const ownerFromAsset1 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); + const ownerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset1).to.be.equal(fromAddress); - const ownerFromAsset2 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId2); + const ownerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); expect(ownerFromAsset2).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -916,34 +839,29 @@ describe('Asset Transfer Proxies', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newOwnerFromAsset1 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); - const newOwnerFromAsset2 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId2); + const newOwnerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); + const newOwnerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); expect(newOwnerFromAsset1).to.be.equal(toAddress); expect(newOwnerFromAsset2).to.be.equal(toAddress); }); it('should successfully transfer multiple different ERC721 tokens', async () => { - const erc721AssetData1 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); - const erc721AssetData2 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenB.address, - erc721BFromTokenId, - ); + const erc721AssetData1 = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); + const erc721AssetData2 = await devUtils + .encodeERC721AssetData(erc721TokenB.address, erc721BFromTokenId) + .callAsync(); const inputAmount = new BigNumber(1); const erc721Amount = new BigNumber(1); const amounts = [erc721Amount, erc721Amount]; const nestedAssetData = [erc721AssetData1, erc721AssetData2]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); - const ownerFromAsset1 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); + const ownerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset1).to.be.equal(fromAddress); - const ownerFromAsset2 = await erc721TokenB.ownerOf.callAsync(erc721BFromTokenId); + const ownerFromAsset2 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); expect(ownerFromAsset2).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -954,8 +872,8 @@ describe('Asset Transfer Proxies', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newOwnerFromAsset1 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); - const newOwnerFromAsset2 = await erc721TokenB.ownerOf.callAsync(erc721BFromTokenId); + const newOwnerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); + const newOwnerFromAsset2 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); expect(newOwnerFromAsset1).to.be.equal(toAddress); expect(newOwnerFromAsset2).to.be.equal(toAddress); }); @@ -975,23 +893,22 @@ describe('Asset Transfer Proxies', () => { ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data - const erc1155AssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const erc1155AssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // encode multi-asset data const multiAssetAmount = new BigNumber(5); const amounts = [valueMultiplier]; const nestedAssetData = [erc1155AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - multiAssetAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) + .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1031,23 +948,22 @@ describe('Asset Transfer Proxies', () => { ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data - const erc1155AssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const erc1155AssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // encode multi-asset data const multiAssetAmount = new BigNumber(5); const amounts = [valueMultiplier]; const nestedAssetData = [erc1155AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - multiAssetAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) + .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1095,23 +1011,22 @@ describe('Asset Transfer Proxies', () => { ]; await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data - const erc1155AssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const erc1155AssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // encode multi-asset data const multiAssetAmount = new BigNumber(1); const amounts = [valueMultiplier]; const nestedAssetData = [erc1155AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - multiAssetAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) + .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1152,29 +1067,30 @@ describe('Asset Transfer Proxies', () => { await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); await erc1155Wrapper2.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // encode erc1155 asset data - const erc1155AssetData1 = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); - const erc1155AssetData2 = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract2.address, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - ); + const erc1155AssetData1 = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); + const erc1155AssetData2 = await devUtils + .encodeERC1155AssetData( + erc1155Contract2.address, + tokensToTransfer, + valuesToTransfer, + receiverCallbackData, + ) + .callAsync(); // encode multi-asset data const multiAssetAmount = new BigNumber(5); const amounts = [valueMultiplier, valueMultiplier]; const nestedAssetData = [erc1155AssetData1, erc1155AssetData2]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - multiAssetAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, multiAssetAmount) + .getABIEncodedTransactionData(); // execute transfer await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1199,35 +1115,33 @@ describe('Asset Transfer Proxies', () => { // setup test parameters const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const erc1155TokenHolders = [fromAddress, toAddress]; const erc1155TokensToTransfer = erc1155FungibleTokens.slice(0, 1); const erc1155ValuesToTransfer = [new BigNumber(25)]; const erc1155Amount = new BigNumber(23); const erc1155ReceiverCallbackData = '0x0102030405'; - const erc1155AssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - erc1155TokensToTransfer, - erc1155ValuesToTransfer, - erc1155ReceiverCallbackData, - ); + const erc1155AssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + erc1155TokensToTransfer, + erc1155ValuesToTransfer, + erc1155ReceiverCallbackData, + ) + .callAsync(); const amounts = [erc20Amount, erc721Amount, erc1155Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData, erc1155AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); // check balances before transfer const erc20Balances = await erc20Wrapper.getBalancesAsync(); - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); const erc1155ExpectedInitialBalances = [ constants.INITIAL_ERC1155_FUNGIBLE_BALANCE, @@ -1257,7 +1171,7 @@ describe('Asset Transfer Proxies', () => { expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); const erc1155TotalValueTransferred = erc1155ValuesToTransfer[0].times(erc1155Amount).times(inputAmount); const expectedFinalBalances = [ @@ -1273,23 +1187,19 @@ describe('Asset Transfer Proxies', () => { it('should successfully transfer a combination of ERC20 and ERC721 tokens', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1307,33 +1217,28 @@ describe('Asset Transfer Proxies', () => { expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); }); it('should successfully transfer tokens and ignore extra assetData', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; const extraData = '0102030405060708090001020304050607080900010203040506070809000102'; - const assetData = `${await devUtils.encodeMultiAssetData.callAsync( - amounts, - nestedAssetData, - )}${extraData}`; - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = `${await devUtils + .encodeMultiAssetData(amounts, nestedAssetData) + .callAsync()}${extraData}`; + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); - const ownerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const ownerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset).to.be.equal(fromAddress); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1351,24 +1256,21 @@ describe('Asset Transfer Proxies', () => { expect(newBalances[toAddress][erc20TokenA.address]).to.be.bignumber.equal( erc20Balances[toAddress][erc20TokenA.address].plus(totalAmount), ); - const newOwnerFromAsset = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const newOwnerFromAsset = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(newOwnerFromAsset).to.be.equal(toAddress); }); it('should successfully transfer correct amounts when the `amount` > 1', async () => { const inputAmount = new BigNumber(100); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); - const erc20AssetData1 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const erc20AssetData2 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); + const erc20AssetData1 = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const erc20AssetData2 = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); const amounts = [erc20Amount1, erc20Amount2]; const nestedAssetData = [erc20AssetData1, erc20AssetData2]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ @@ -1398,28 +1300,24 @@ describe('Asset Transfer Proxies', () => { const inputAmount = new BigNumber(1); const erc20Amount1 = new BigNumber(10); const erc20Amount2 = new BigNumber(20); - const erc20AssetData1 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const erc20AssetData2 = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); + const erc20AssetData1 = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const erc20AssetData2 = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); const erc721Amount = new BigNumber(1); const erc721Balances = await erc721Wrapper.getBalancesAsync(); const erc721AFromTokenId2 = erc721Balances[fromAddress][erc721TokenA.address][1]; const erc721BFromTokenId2 = erc721Balances[fromAddress][erc721TokenB.address][1]; - const erc721AssetData1 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); - const erc721AssetData2 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId2, - ); - const erc721AssetData3 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenB.address, - erc721BFromTokenId, - ); - const erc721AssetData4 = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenB.address, - erc721BFromTokenId2, - ); + const erc721AssetData1 = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); + const erc721AssetData2 = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId2) + .callAsync(); + const erc721AssetData3 = await devUtils + .encodeERC721AssetData(erc721TokenB.address, erc721BFromTokenId) + .callAsync(); + const erc721AssetData4 = await devUtils + .encodeERC721AssetData(erc721TokenB.address, erc721BFromTokenId2) + .callAsync(); const amounts = [erc721Amount, erc20Amount1, erc721Amount, erc20Amount2, erc721Amount, erc721Amount]; const nestedAssetData = [ erc721AssetData1, @@ -1429,20 +1327,17 @@ describe('Asset Transfer Proxies', () => { erc721AssetData3, erc721AssetData4, ]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); - const ownerFromAsset1 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); + const ownerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); expect(ownerFromAsset1).to.be.equal(fromAddress); - const ownerFromAsset2 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId2); + const ownerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); expect(ownerFromAsset2).to.be.equal(fromAddress); - const ownerFromAsset3 = await erc721TokenB.ownerOf.callAsync(erc721BFromTokenId); + const ownerFromAsset3 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); expect(ownerFromAsset3).to.be.equal(fromAddress); - const ownerFromAsset4 = await erc721TokenB.ownerOf.callAsync(erc721BFromTokenId2); + const ownerFromAsset4 = await erc721TokenB.ownerOf(erc721BFromTokenId2).callAsync(); expect(ownerFromAsset4).to.be.equal(fromAddress); const erc20Balances = await erc20Wrapper.getBalancesAsync(); await web3Wrapper.awaitTransactionSuccessAsync( @@ -1454,10 +1349,10 @@ describe('Asset Transfer Proxies', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newOwnerFromAsset1 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId); - const newOwnerFromAsset2 = await erc721TokenA.ownerOf.callAsync(erc721AFromTokenId2); - const newOwnerFromAsset3 = await erc721TokenB.ownerOf.callAsync(erc721BFromTokenId); - const newOwnerFromAsset4 = await erc721TokenB.ownerOf.callAsync(erc721BFromTokenId2); + const newOwnerFromAsset1 = await erc721TokenA.ownerOf(erc721AFromTokenId).callAsync(); + const newOwnerFromAsset2 = await erc721TokenA.ownerOf(erc721AFromTokenId2).callAsync(); + const newOwnerFromAsset3 = await erc721TokenB.ownerOf(erc721BFromTokenId).callAsync(); + const newOwnerFromAsset4 = await erc721TokenB.ownerOf(erc721BFromTokenId2).callAsync(); expect(newOwnerFromAsset1).to.be.equal(toAddress); expect(newOwnerFromAsset2).to.be.equal(toAddress); expect(newOwnerFromAsset3).to.be.equal(toAddress); @@ -1481,22 +1376,18 @@ describe('Asset Transfer Proxies', () => { it('should revert if a single transfer fails', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // 2 is an invalid erc721 amount const erc721Amount = new BigNumber(2); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, @@ -1509,23 +1400,19 @@ describe('Asset Transfer Proxies', () => { it('should revert if an AssetProxy is not registered', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const invalidProxyId = '0x12345678'; const invalidErc721AssetData = `${invalidProxyId}${erc721AssetData.slice(10)}`; const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, invalidErc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, @@ -1538,20 +1425,16 @@ describe('Asset Transfer Proxies', () => { it('should revert if the length of `amounts` does not match the length of `nestedAssetData`', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, @@ -1564,16 +1447,13 @@ describe('Asset Transfer Proxies', () => { it('should revert if amounts multiplication results in an overflow', async () => { const inputAmount = new BigNumber(2).pow(128); const erc20Amount = new BigNumber(2).pow(128); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const amounts = [erc20Amount]; const nestedAssetData = [erc20AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, @@ -1586,18 +1466,15 @@ describe('Asset Transfer Proxies', () => { it('should revert if an element of `nestedAssetData` is < 4 bytes long', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); const erc721AssetData = '0x123456'; const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, @@ -1610,21 +1487,17 @@ describe('Asset Transfer Proxies', () => { it('should revert if caller is not authorized', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ to: multiAssetProxy.address, @@ -1637,21 +1510,17 @@ describe('Asset Transfer Proxies', () => { it('should revert if asset data overflows beyond the bounds of calldata', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); // append asset data to end of tx data with a length of 0x300 bytes, which will extend past actual calldata. const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080'; const invalidOffsetToAssetData = '00000000000000000000000000000000000000000000000000000000000002a0'; @@ -1670,21 +1539,17 @@ describe('Asset Transfer Proxies', () => { it('should revert if asset data resolves to a location beyond the bounds of calldata', async () => { const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); - const data = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - inputAmount, - ); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); + const data = assetProxyInterface + .transferFrom(assetData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080'; const invalidOffsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000400'; const badData = data.replace(offsetToAssetData, invalidOffsetToAssetData); @@ -1704,23 +1569,19 @@ describe('Asset Transfer Proxies', () => { // setup test parameters const inputAmount = new BigNumber(1); const erc20Amount = new BigNumber(10); - const erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const erc20AssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const erc721Amount = new BigNumber(1); - const erc721AssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721TokenA.address, - erc721AFromTokenId, - ); + const erc721AssetData = await devUtils + .encodeERC721AssetData(erc721TokenA.address, erc721AFromTokenId) + .callAsync(); const amounts = [erc20Amount, erc721Amount]; const nestedAssetData = [erc20AssetData, erc721AssetData]; - const assetData = await devUtils.encodeMultiAssetData.callAsync(amounts, nestedAssetData); + const assetData = await devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); const extraData = '01'; const assetDataWithExtraData = `${assetData}${extraData}`; - const badData = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetDataWithExtraData, - fromAddress, - toAddress, - inputAmount, - ); + const badData = assetProxyInterface + .transferFrom(assetDataWithExtraData, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); // execute transfer await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ @@ -1741,12 +1602,9 @@ describe('Asset Transfer Proxies', () => { // so that we know the error is not triggered by another check in the code. const zeros32Bytes = '0'.repeat(64); const assetData36Bytes = `${AssetProxyId.MultiAsset}${zeros32Bytes}`; - const badData = assetProxyInterface.transferFrom.getABIEncodedTransactionData( - assetData36Bytes, - fromAddress, - toAddress, - inputAmount, - ); + const badData = assetProxyInterface + .transferFrom(assetData36Bytes, fromAddress, toAddress, inputAmount) + .getABIEncodedTransactionData(); // execute transfer await expectTransactionFailedAsync( web3Wrapper.sendTransactionAsync({ diff --git a/contracts/asset-proxy/test/static_call_proxy.ts b/contracts/asset-proxy/test/static_call_proxy.ts index 8fcbc57e25..283b5fc26c 100644 --- a/contracts/asset-proxy/test/static_call_proxy.ts +++ b/contracts/asset-proxy/test/static_call_proxy.ts @@ -81,26 +81,21 @@ describe('StaticCallProxy', () => { ); }); it('should have an id of 0xc339d10a', async () => { - const proxyId = await staticCallProxy.getProxyId.callAsync(); + const proxyId = await staticCallProxy.getProxyId().callAsync(); const expectedProxyId = AssetProxyId.StaticCall; expect(proxyId).to.equal(expectedProxyId); }); }); describe('transferFrom', () => { it('should revert if assetData lies outside the bounds of calldata', async () => { - const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData(); + const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData(); const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - const txData = staticCallProxy.transferFrom.getABIEncodedTransactionData( - assetData, - fromAddress, - toAddress, - amount, - ); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + const txData = staticCallProxy + .transferFrom(assetData, fromAddress, toAddress, amount) + .getABIEncodedTransactionData(); const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080'; const txDataEndBuffer = ethUtil.toBuffer((txData.length - 2) / 2 - 4); const paddedTxDataEndBuffer = ethUtil.setLengthLeft(txDataEndBuffer, 32); @@ -118,25 +113,21 @@ describe('StaticCallProxy', () => { it('should revert if the length of assetData is less than 100 bytes', async () => { const staticCallData = constants.NULL_BYTES; const expectedResultHash = constants.KECCAK256_NULL; - const assetData = (await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - )).slice(0, -128); + const assetData = (await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync()).slice(0, -128); const assetDataByteLen = (assetData.length - 2) / 2; expect((assetDataByteLen - 4) % 32).to.equal(0); await expectTransactionFailedWithoutReasonAsync( - staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount), + staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(), ); }); it('should revert if the offset to `staticCallData` points to outside of assetData', async () => { - const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData(); + const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData(); const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); const offsetToStaticCallData = '0000000000000000000000000000000000000000000000000000000000000060'; const assetDataEndBuffer = ethUtil.toBuffer((assetData.length - 2) / 2 - 4); const paddedAssetDataEndBuffer = ethUtil.setLengthLeft(assetDataEndBuffer, 32); @@ -147,94 +138,88 @@ describe('StaticCallProxy', () => { invalidOffsetToStaticCallData, )}${newStaticCallData}`; await expectTransactionFailedWithoutReasonAsync( - staticCallProxy.transferFrom.sendTransactionAsync(badAssetData, fromAddress, toAddress, amount), + staticCallProxy.transferFrom(badAssetData, fromAddress, toAddress, amount).sendTransactionAsync(), ); }); it('should revert if the callTarget attempts to write to state', async () => { - const staticCallData = staticCallTarget.updateState.getABIEncodedTransactionData(); + const staticCallData = staticCallTarget.updateState().getABIEncodedTransactionData(); const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); await expectTransactionFailedWithoutReasonAsync( - staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount), + staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(), ); }); it('should revert with data provided by the callTarget if the staticcall reverts', async () => { - const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1)); + const staticCallData = staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData(); const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); await expectTransactionFailedAsync( - staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount), + staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(), RevertReason.TargetNotEven, ); }); it('should revert if the hash of the output is different than expected expected', async () => { - const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(0)); + const staticCallData = staticCallTarget.isOddNumber(new BigNumber(0)).getABIEncodedTransactionData(); const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001'); const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer)); - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); await expectTransactionFailedAsync( - staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount), + staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(), RevertReason.UnexpectedStaticCallResult, ); }); it('should be successful if a function call with no inputs and no outputs is successful', async () => { - const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData(); + const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData(); const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + await staticCallProxy + .transferFrom(assetData, fromAddress, toAddress, amount) + .awaitTransactionSuccessAsync(); }); it('should be successful if the staticCallTarget is not a contract and no return value is expected', async () => { const staticCallData = '0x0102030405060708'; const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - toAddress, - staticCallData, - expectedResultHash, - ); - await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount); + const assetData = await devUtils + .encodeStaticCallAssetData(toAddress, staticCallData, expectedResultHash) + .callAsync(); + await staticCallProxy + .transferFrom(assetData, fromAddress, toAddress, amount) + .awaitTransactionSuccessAsync(); }); it('should be successful if a function call with one static input returns the correct value', async () => { - const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(1)); + const staticCallData = staticCallTarget.isOddNumber(new BigNumber(1)).getABIEncodedTransactionData(); const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001'); const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer)); - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + await staticCallProxy + .transferFrom(assetData, fromAddress, toAddress, amount) + .awaitTransactionSuccessAsync(); }); it('should be successful if a function with one dynamic input is successful', async () => { const dynamicInput = '0x0102030405060708'; - const staticCallData = staticCallTarget.dynamicInputFunction.getABIEncodedTransactionData(dynamicInput); + const staticCallData = staticCallTarget.dynamicInputFunction(dynamicInput).getABIEncodedTransactionData(); const expectedResultHash = constants.KECCAK256_NULL; - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + await staticCallProxy + .transferFrom(assetData, fromAddress, toAddress, amount) + .awaitTransactionSuccessAsync(); }); it('should be successful if a function call returns a complex type', async () => { const a = new BigNumber(1); const b = new BigNumber(2); - const staticCallData = staticCallTarget.returnComplexType.getABIEncodedTransactionData(a, b); + const staticCallData = staticCallTarget.returnComplexType(a, b).getABIEncodedTransactionData(); const abiEncoder = new AbiEncoder.DynamicBytes({ name: '', type: 'bytes', @@ -247,12 +232,12 @@ describe('StaticCallProxy', () => { const expectedResultHash = ethUtil.bufferToHex( ethUtil.sha3(ethUtil.toBuffer(encodedExpectedResultWithOffset)), ); - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + await staticCallProxy + .transferFrom(assetData, fromAddress, toAddress, amount) + .awaitTransactionSuccessAsync(); }); }); }); diff --git a/contracts/asset-proxy/test/uniswap_bridge.ts b/contracts/asset-proxy/test/uniswap_bridge.ts index 66815b421e..4fad004808 100644 --- a/contracts/asset-proxy/test/uniswap_bridge.ts +++ b/contracts/asset-proxy/test/uniswap_bridge.ts @@ -9,7 +9,6 @@ import { hexRandom, Numberish, randomAddress, - TransactionHelper, } from '@0x/contracts-test-utils'; import { AssetProxyId } from '@0x/types'; import { BigNumber } from '@0x/utils'; @@ -31,7 +30,6 @@ import { } from './wrappers'; blockchainTests.resets('UniswapBridge unit tests', env => { - const txHelper = new TransactionHelper(env.web3Wrapper, artifacts); let testContract: TestUniswapBridgeContract; let wethTokenAddress: string; @@ -42,13 +40,13 @@ blockchainTests.resets('UniswapBridge unit tests', env => { env.txDefaults, artifacts, ); - wethTokenAddress = await testContract.wethToken.callAsync(); + wethTokenAddress = await testContract.wethToken().callAsync(); }); describe('isValidSignature()', () => { it('returns success bytes', async () => { const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381'; - const result = await testContract.isValidSignature.callAsync(hexRandom(), hexRandom(_.random(0, 32))); + const result = await testContract.isValidSignature(hexRandom(), hexRandom(_.random(0, 32))).callAsync(); expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE); }); }); @@ -90,35 +88,35 @@ blockchainTests.resets('UniswapBridge unit tests', env => { async function withdrawToAsync(opts?: Partial): Promise { const _opts = createWithdrawToOpts(opts); + const callData = { value: new BigNumber(_opts.exchangeFillAmount) }; // Create the "from" token and exchange. - [[_opts.fromTokenAddress]] = await txHelper.getResultAndReceiptAsync( - testContract.createTokenAndExchange, + const createFromTokenFn = testContract.createTokenAndExchange( _opts.fromTokenAddress, _opts.exchangeRevertReason, - { value: new BigNumber(_opts.exchangeFillAmount) }, ); + [_opts.fromTokenAddress] = await createFromTokenFn.callAsync(callData); + await createFromTokenFn.awaitTransactionSuccessAsync(callData); + // Create the "to" token and exchange. - [[_opts.toTokenAddress]] = await txHelper.getResultAndReceiptAsync( - testContract.createTokenAndExchange, + const createToTokenFn = testContract.createTokenAndExchange( _opts.toTokenAddress, _opts.exchangeRevertReason, - { value: new BigNumber(_opts.exchangeFillAmount) }, - ); - await testContract.setTokenRevertReason.awaitTransactionSuccessAsync( - _opts.toTokenAddress, - _opts.toTokenRevertReason, - ); - await testContract.setTokenRevertReason.awaitTransactionSuccessAsync( - _opts.fromTokenAddress, - _opts.fromTokenRevertReason, ); + [_opts.toTokenAddress] = await createToTokenFn.callAsync(callData); + await createToTokenFn.awaitTransactionSuccessAsync(callData); + + await testContract + .setTokenRevertReason(_opts.toTokenAddress, _opts.toTokenRevertReason) + .awaitTransactionSuccessAsync(); + await testContract + .setTokenRevertReason(_opts.fromTokenAddress, _opts.fromTokenRevertReason) + .awaitTransactionSuccessAsync(); // Set the token balance for the token we're converting from. - await testContract.setTokenBalance.awaitTransactionSuccessAsync(_opts.fromTokenAddress, { + await testContract.setTokenBalance(_opts.fromTokenAddress).awaitTransactionSuccessAsync({ value: new BigNumber(_opts.fromTokenBalance), }); // Call bridgeTransferFrom(). - const [result, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.bridgeTransferFrom, + const bridgeTransferFromFn = testContract.bridgeTransferFrom( // The "to" token address. _opts.toTokenAddress, // The "from" address. @@ -130,6 +128,8 @@ blockchainTests.resets('UniswapBridge unit tests', env => { // ABI-encoded "from" token address. hexLeftPad(_opts.fromTokenAddress), ); + const result = await bridgeTransferFromFn.callAsync(); + const receipt = await bridgeTransferFromFn.awaitTransactionSuccessAsync(); return { opts: _opts, result, @@ -139,7 +139,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => { } async function getExchangeForTokenAsync(tokenAddress: string): Promise { - return testContract.getExchange.callAsync(tokenAddress); + return testContract.getExchange(tokenAddress).callAsync(); } it('returns magic bytes on success', async () => { @@ -148,11 +148,9 @@ blockchainTests.resets('UniswapBridge unit tests', env => { }); it('just transfers tokens to `to` if the same tokens are in play', async () => { - const [[tokenAddress]] = await txHelper.getResultAndReceiptAsync( - testContract.createTokenAndExchange, - constants.NULL_ADDRESS, - '', - ); + const createTokenFn = await testContract.createTokenAndExchange(constants.NULL_ADDRESS, ''); + const [tokenAddress] = await createTokenFn.callAsync(); + await createTokenFn.awaitTransactionSuccessAsync(); const { opts, result, logs } = await withdrawToAsync({ fromTokenAddress: tokenAddress, toTokenAddress: tokenAddress, @@ -204,14 +202,16 @@ blockchainTests.resets('UniswapBridge unit tests', env => { }); it('fails if "from" token does not exist', async () => { - const tx = testContract.bridgeTransferFrom.awaitTransactionSuccessAsync( - randomAddress(), - randomAddress(), - randomAddress(), - getRandomInteger(1, 1e18), - hexLeftPad(randomAddress()), - ); - return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); + const tx = testContract + .bridgeTransferFrom( + randomAddress(), + randomAddress(), + randomAddress(), + getRandomInteger(1, 1e18), + hexLeftPad(randomAddress()), + ) + .awaitTransactionSuccessAsync(); + return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); it('fails if the exchange fails', async () => { @@ -219,7 +219,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => { const tx = withdrawToAsync({ exchangeRevertReason: revertReason, }); - return expect(tx).to.revertWith(revertReason); + return expect(tx).to.eventually.be.rejectedWith(revertReason); }); }); @@ -276,14 +276,16 @@ blockchainTests.resets('UniswapBridge unit tests', env => { }); it('fails if "from" token does not exist', async () => { - const tx = testContract.bridgeTransferFrom.awaitTransactionSuccessAsync( - randomAddress(), - randomAddress(), - randomAddress(), - getRandomInteger(1, 1e18), - hexLeftPad(wethTokenAddress), - ); - return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); + const tx = testContract + .bridgeTransferFrom( + randomAddress(), + randomAddress(), + randomAddress(), + getRandomInteger(1, 1e18), + hexLeftPad(wethTokenAddress), + ) + .awaitTransactionSuccessAsync(); + return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); it('fails if `WETH.deposit()` fails', async () => { @@ -292,7 +294,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => { toTokenAddress: wethTokenAddress, toTokenRevertReason: revertReason, }); - return expect(tx).to.revertWith(revertReason); + return expect(tx).to.eventually.be.rejectedWith(revertReason); }); it('fails if the exchange fails', async () => { @@ -301,7 +303,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => { toTokenAddress: wethTokenAddress, exchangeRevertReason: revertReason, }); - return expect(tx).to.revertWith(revertReason); + return expect(tx).to.eventually.be.rejectedWith(revertReason); }); }); @@ -334,14 +336,16 @@ blockchainTests.resets('UniswapBridge unit tests', env => { }); it('fails if "to" token does not exist', async () => { - const tx = testContract.bridgeTransferFrom.awaitTransactionSuccessAsync( - wethTokenAddress, - randomAddress(), - randomAddress(), - getRandomInteger(1, 1e18), - hexLeftPad(randomAddress()), - ); - return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); + const tx = testContract + .bridgeTransferFrom( + wethTokenAddress, + randomAddress(), + randomAddress(), + getRandomInteger(1, 1e18), + hexLeftPad(randomAddress()), + ) + .awaitTransactionSuccessAsync(); + return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); it('fails if the `WETH.withdraw()` fails', async () => { @@ -350,7 +354,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => { fromTokenAddress: wethTokenAddress, fromTokenRevertReason: revertReason, }); - return expect(tx).to.revertWith(revertReason); + return expect(tx).to.eventually.be.rejectedWith(revertReason); }); it('fails if the exchange fails', async () => { @@ -359,7 +363,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => { fromTokenAddress: wethTokenAddress, exchangeRevertReason: revertReason, }); - return expect(tx).to.revertWith(revertReason); + return expect(tx).to.eventually.be.rejectedWith(revertReason); }); }); }); diff --git a/contracts/coordinator/test/coordinator_registry.ts b/contracts/coordinator/test/coordinator_registry.ts index 4d732c2af5..8a1ede6009 100644 --- a/contracts/coordinator/test/coordinator_registry.ts +++ b/contracts/coordinator/test/coordinator_registry.ts @@ -25,43 +25,42 @@ blockchainTests.resets('Coordinator Registry tests', env => { }); describe('core', () => { it('Should successfully set a Coordinator endpoint', async () => { - await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(coordinatorEndpoint, { + await coordinatorRegistry.setCoordinatorEndpoint(coordinatorEndpoint).awaitTransactionSuccessAsync({ from: coordinatorOperator, }); - const recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync( - coordinatorOperator, - ); + const recordedCoordinatorEndpoint = await coordinatorRegistry + .getCoordinatorEndpoint(coordinatorOperator) + .callAsync(); expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint); }); it('Should successfully unset a Coordinator endpoint', async () => { // set Coordinator endpoint - await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(coordinatorEndpoint, { + await coordinatorRegistry.setCoordinatorEndpoint(coordinatorEndpoint).awaitTransactionSuccessAsync({ from: coordinatorOperator, }); - let recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync( - coordinatorOperator, - ); + let recordedCoordinatorEndpoint = await coordinatorRegistry + .getCoordinatorEndpoint(coordinatorOperator) + .callAsync(); expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint); // unset Coordinator endpoint - await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(nilCoordinatorEndpoint, { + await coordinatorRegistry.setCoordinatorEndpoint(nilCoordinatorEndpoint).awaitTransactionSuccessAsync({ from: coordinatorOperator, }); - recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync( - coordinatorOperator, - ); + recordedCoordinatorEndpoint = await coordinatorRegistry + .getCoordinatorEndpoint(coordinatorOperator) + .callAsync(); expect(recordedCoordinatorEndpoint).to.be.equal(nilCoordinatorEndpoint); }); it('Should emit an event when setting Coordinator endpoint', async () => { // set Coordinator endpoint - const txReceipt = await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync( - coordinatorEndpoint, - { + const txReceipt = await coordinatorRegistry + .setCoordinatorEndpoint(coordinatorEndpoint) + .awaitTransactionSuccessAsync({ from: coordinatorOperator, - }, - ); - const recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync( - coordinatorOperator, - ); + }); + const recordedCoordinatorEndpoint = await coordinatorRegistry + .getCoordinatorEndpoint(coordinatorOperator) + .callAsync(); expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint); // validate event const expectedEvent: CoordinatorRegistryCoordinatorEndpointSetEventArgs = { diff --git a/contracts/coordinator/test/libs.ts b/contracts/coordinator/test/libs.ts index 44ca15253d..3b19d521b7 100644 --- a/contracts/coordinator/test/libs.ts +++ b/contracts/coordinator/test/libs.ts @@ -46,7 +46,7 @@ blockchainTests.resets('Libs tests', env => { transactionSignature: signedTx.signature, }; const expectedApprovalHash = hashUtils.getApprovalHashHex(signedTx, coordinatorContract.address, txOrigin); - const approvalHash = await coordinatorContract.getCoordinatorApprovalHash.callAsync(approval); + const approvalHash = await coordinatorContract.getCoordinatorApprovalHash(approval).callAsync(); expect(expectedApprovalHash).to.eq(approvalHash); }); }); diff --git a/contracts/coordinator/test/mixins.ts b/contracts/coordinator/test/mixins.ts index 2534fa676d..78fc05c27a 100644 --- a/contracts/coordinator/test/mixins.ts +++ b/contracts/coordinator/test/mixins.ts @@ -75,14 +75,14 @@ blockchainTests.resets('Mixins tests', env => { const data = constants.NULL_BYTES; const transaction = await transactionFactory.newSignedTransactionAsync({ data }, SignatureType.EthSign); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature); + const signerAddress = await mixins.getSignerAddress(transactionHash, transaction.signature).callAsync(); expect(transaction.signerAddress).to.eq(signerAddress); }); it('should return the correct address using the EIP712 signature type', async () => { const data = constants.NULL_BYTES; const transaction = await transactionFactory.newSignedTransactionAsync({ data }, SignatureType.EIP712); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature); + const signerAddress = await mixins.getSignerAddress(transactionHash, transaction.signature).callAsync(); expect(transaction.signerAddress).to.eq(signerAddress); }); it('should revert with with the Illegal signature type', async () => { @@ -93,7 +93,7 @@ blockchainTests.resets('Mixins tests', env => { SignatureType.Illegal, ); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith( + expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith( new CoordinatorRevertErrors.SignatureError( CoordinatorRevertErrors.SignatureErrorCodes.Illegal, transactionHash, @@ -106,7 +106,7 @@ blockchainTests.resets('Mixins tests', env => { const transaction = await transactionFactory.newSignedTransactionAsync({ data }); transaction.signature = hexConcat(SignatureType.Invalid); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith( + expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith( new CoordinatorRevertErrors.SignatureError( CoordinatorRevertErrors.SignatureErrorCodes.Invalid, transactionHash, @@ -122,7 +122,7 @@ blockchainTests.resets('Mixins tests', env => { SignatureType.NSignatureTypes, ); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith( + expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith( new CoordinatorRevertErrors.SignatureError( CoordinatorRevertErrors.SignatureErrorCodes.Unsupported, transactionHash, @@ -138,7 +138,7 @@ blockchainTests.resets('Mixins tests', env => { SignatureType.Wallet, ); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith( + expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith( new CoordinatorRevertErrors.SignatureError( CoordinatorRevertErrors.SignatureErrorCodes.Unsupported, transactionHash, @@ -153,7 +153,7 @@ blockchainTests.resets('Mixins tests', env => { it(`should correctly decode the orders for ${fnName} data`, async () => { const orders = [defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); - const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data); + const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync(); const decodedSignedOrders = decodedOrders.map(order => ({ ...order, signature: constants.NULL_BYTES, @@ -167,7 +167,7 @@ blockchainTests.resets('Mixins tests', env => { it(`should correctly decode the orders for ${fnName} data`, async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); - const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data); + const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync(); const decodedSignedOrders = decodedOrders.map(order => ({ ...order, signature: constants.NULL_BYTES, @@ -181,7 +181,7 @@ blockchainTests.resets('Mixins tests', env => { it(`should correctly decode the orders for ${fnName} data`, async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); - const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data); + const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync(); const decodedSignedOrders = decodedOrders.map(order => ({ ...order, signature: constants.NULL_BYTES, @@ -195,7 +195,7 @@ blockchainTests.resets('Mixins tests', env => { it(`should correctly decode the orders for ${fnName} data`, async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); - const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data); + const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync(); const decodedSignedOrders = decodedOrders.map(order => ({ ...order, signature: constants.NULL_BYTES, @@ -209,14 +209,14 @@ blockchainTests.resets('Mixins tests', env => { it(`should correctly decode the orders for ${fnName} data`, async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); - const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data); + const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync(); const emptyArray: any[] = []; expect(emptyArray).to.deep.eq(decodedOrders); }); } it('should decode an empty array for invalid data', async () => { const data = '0x0123456789'; - const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data); + const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync(); const emptyArray: any[] = []; expect(emptyArray).to.deep.eq(decodedOrders); }); @@ -227,7 +227,7 @@ blockchainTests.resets('Mixins tests', env => { new BigNumber(3), // the length of data new BigNumber(4), ); - return expect(mixins.decodeOrdersFromFillData.callAsync(data)).to.revertWith(expectedError); + return expect(mixins.decodeOrdersFromFillData(data).callAsync()).to.revertWith(expectedError); }); }); @@ -238,13 +238,11 @@ blockchainTests.resets('Mixins tests', env => { const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval.signature], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[null], approval_sig=[approver1]`, async () => { const order = { @@ -255,54 +253,42 @@ blockchainTests.resets('Mixins tests', env => { const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval.signature], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[]`, async () => { const orders = [defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - approvalSignerAddress1, - transaction.signature, - [], - { + await mixins + .assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, []) + .callAsync({ from: approvalSignerAddress1, - }, - ); + }); }); it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[approver1]`, async () => { const orders = [defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - approvalSignerAddress1, - transaction.signature, - [approval.signature], - { from: approvalSignerAddress1 }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: approvalSignerAddress1 }); }); it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[]`, async () => { const orders = [defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - approvalSignerAddress1, - transaction.signature, - [], - { + await mixins + .assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, []) + .callAsync({ from: approvalSignerAddress1, - }, - ); + }); }); it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[invalid]`, async () => { const orders = [defaultOrder]; @@ -314,13 +300,11 @@ blockchainTests.resets('Mixins tests', env => { '0xFFFFFFFF', hexSlice(approval.signature, 6), ); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [signature], - { from: transactionSignerAddress }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + signature, + ]) + .callAsync({ from: transactionSignerAddress }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); expect(tx).to.revertWith( @@ -333,13 +317,11 @@ blockchainTests.resets('Mixins tests', env => { const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval.signature], - { from: approvalSignerAddress2 }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: approvalSignerAddress2 }); expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress)); }); } @@ -355,13 +337,11 @@ blockchainTests.resets('Mixins tests', env => { const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval.signature], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => { const orders = [defaultOrder, defaultOrder].map(order => ({ @@ -371,13 +351,11 @@ blockchainTests.resets('Mixins tests', env => { const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval.signature], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[]`, async () => { const orders = [defaultOrder, defaultOrder].map(order => ({ @@ -386,26 +364,20 @@ blockchainTests.resets('Mixins tests', env => { })); const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, []) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,null], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => { const orders = [defaultOrder, { ...defaultOrder, senderAddress: constants.NULL_ADDRESS }]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval.signature], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval.signature, + ]) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver1,approver2]`, async () => { const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }]; @@ -413,25 +385,20 @@ blockchainTests.resets('Mixins tests', env => { const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval1 = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); const approval2 = approvalFactory2.newSignedApproval(transaction, transactionSignerAddress); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval1.signature, approval2.signature], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval1.signature, + approval2.signature, + ]) + .callAsync({ from: transactionSignerAddress }); }); it(`Should be successful: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[]`, async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - approvalSignerAddress1, - transaction.signature, - [], - { from: approvalSignerAddress1 }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, []) + .callAsync({ from: approvalSignerAddress1 }); }); it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver2]`, async () => { const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }]; @@ -439,26 +406,20 @@ blockchainTests.resets('Mixins tests', env => { const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval2 = approvalFactory2.newSignedApproval(transaction, transactionSignerAddress); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval2.signature], - { from: approvalSignerAddress1 }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval2.signature, + ]) + .callAsync({ from: approvalSignerAddress1 }); expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress)); }); it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[]`, async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [], - { from: transactionSignerAddress }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, []) + .callAsync({ from: transactionSignerAddress }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); expect(tx).to.revertWith( @@ -475,13 +436,11 @@ blockchainTests.resets('Mixins tests', env => { '0xFFFFFFFF', hexSlice(approval.signature, 6), ); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [signature], - { from: transactionSignerAddress }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + signature, + ]) + .callAsync({ from: transactionSignerAddress }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); expect(tx).to.revertWith( @@ -499,13 +458,12 @@ blockchainTests.resets('Mixins tests', env => { '0xFFFFFFFF', hexSlice(approval2.signature, 6), ); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval1.signature, approvalSignature2], - { from: transactionSignerAddress }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval1.signature, + approvalSignature2, + ]) + .callAsync({ from: transactionSignerAddress }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); expect(tx).to.revertWith( @@ -522,13 +480,11 @@ blockchainTests.resets('Mixins tests', env => { '0xFFFFFFFF', hexSlice(approval2.signature, 6), ); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - approvalSignerAddress1, - transaction.signature, - [approvalSignature2], - { from: approvalSignerAddress1 }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [ + approvalSignature2, + ]) + .callAsync({ from: approvalSignerAddress1 }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); expect(tx).to.revertWith( @@ -541,13 +497,11 @@ blockchainTests.resets('Mixins tests', env => { const transaction = await transactionFactory.newSignedTransactionAsync({ data }); const approval1 = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress); - const tx = mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [approval1.signature], - { from: approvalSignerAddress2 }, - ); + const tx = mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [ + approval1.signature, + ]) + .callAsync({ from: approvalSignerAddress2 }); expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress)); }); } @@ -557,36 +511,24 @@ blockchainTests.resets('Mixins tests', env => { const orders = [defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrder, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, []) + .callAsync({ from: transactionSignerAddress }); }); it('should allow the tx signer to call `batchCancelOrders` without approval', async () => { const orders = [defaultOrder, defaultOrder]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.BatchCancelOrders, orders); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, []) + .callAsync({ from: transactionSignerAddress }); }); it('should allow the tx signer to call `cancelOrdersUpTo` without approval', async () => { const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrdersUpTo); const transaction = await transactionFactory.newSignedTransactionAsync({ data }); - await mixins.assertValidCoordinatorApprovals.callAsync( - transaction, - transactionSignerAddress, - transaction.signature, - [], - { from: transactionSignerAddress }, - ); + await mixins + .assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, []) + .callAsync({ from: transactionSignerAddress }); }); }); }); diff --git a/contracts/erc1155/src/erc1155_wrapper.ts b/contracts/erc1155/src/erc1155_wrapper.ts index a0c3b21848..cf0916c29d 100644 --- a/contracts/erc1155/src/erc1155_wrapper.ts +++ b/contracts/erc1155/src/erc1155_wrapper.ts @@ -27,7 +27,7 @@ export class Erc1155Wrapper { return this._erc1155Contract; } public async getBalancesAsync(owners: string[], tokens: BigNumber[]): Promise { - const balances = await this._erc1155Contract.balanceOfBatch.callAsync(owners, tokens); + const balances = await this._erc1155Contract.balanceOfBatch(owners, tokens).callAsync(); return balances; } public async safeTransferFromAsync( @@ -41,7 +41,7 @@ export class Erc1155Wrapper { const spender = delegatedSpender === undefined ? from : delegatedSpender; const callbackDataHex = callbackData === undefined ? '0x' : callbackData; const tx = await this._logDecoder.getTxWithDecodedLogsAsync( - await this._erc1155Contract.safeTransferFrom.sendTransactionAsync(from, to, token, value, callbackDataHex, { + await this._erc1155Contract.safeTransferFrom(from, to, token, value, callbackDataHex).sendTransactionAsync({ from: spender, }), ); @@ -58,14 +58,9 @@ export class Erc1155Wrapper { const spender = delegatedSpender === undefined ? from : delegatedSpender; const callbackDataHex = callbackData === undefined ? '0x' : callbackData; const tx = await this._logDecoder.getTxWithDecodedLogsAsync( - await this._erc1155Contract.safeBatchTransferFrom.sendTransactionAsync( - from, - to, - tokens, - values, - callbackDataHex, - { from: spender }, - ), + await this._erc1155Contract + .safeBatchTransferFrom(from, to, tokens, values, callbackDataHex) + .sendTransactionAsync({ from: spender }), ); return tx; } @@ -76,7 +71,7 @@ export class Erc1155Wrapper { const tokenUri = 'dummyFungibleToken'; const tokenIsNonFungible = false; const tx = await this._logDecoder.getTxWithDecodedLogsAsync( - await this._erc1155Contract.create.sendTransactionAsync(tokenUri, tokenIsNonFungible, { + await this._erc1155Contract.create(tokenUri, tokenIsNonFungible).sendTransactionAsync({ from: this._contractOwner, }), ); @@ -97,25 +92,22 @@ export class Erc1155Wrapper { tokenAmountsAsArray.push(tokenAmounts); }); } - await this._erc1155Contract.mintFungible.awaitTransactionSuccessAsync( - tokenId, - beneficiaries, - tokenAmountsAsArray, - { from: this._contractOwner }, - ); + await this._erc1155Contract + .mintFungible(tokenId, beneficiaries, tokenAmountsAsArray) + .awaitTransactionSuccessAsync({ from: this._contractOwner }); } public async mintNonFungibleTokensAsync(beneficiaries: string[]): Promise<[BigNumber, BigNumber[]]> { const tokenUri = 'dummyNonFungibleToken'; const tokenIsNonFungible = true; const tx = await this._logDecoder.getTxWithDecodedLogsAsync( - await this._erc1155Contract.create.sendTransactionAsync(tokenUri, tokenIsNonFungible, { + await this._erc1155Contract.create(tokenUri, tokenIsNonFungible).sendTransactionAsync({ from: this._contractOwner, }), ); // tslint:disable-next-line no-unnecessary-type-assertion const createFungibleTokenLog = tx.logs[0] as LogWithDecodedArgs; const token = createFungibleTokenLog.args.id; - await this._erc1155Contract.mintNonFungible.awaitTransactionSuccessAsync(token, beneficiaries, { + await this._erc1155Contract.mintNonFungible(token, beneficiaries).awaitTransactionSuccessAsync({ from: this._contractOwner, }); const encodedNftIds: BigNumber[] = []; @@ -134,14 +126,14 @@ export class Erc1155Wrapper { isApproved: boolean, ): Promise { const tx = await this._logDecoder.getTxWithDecodedLogsAsync( - await this._erc1155Contract.setApprovalForAll.sendTransactionAsync(beneficiary, isApproved, { + await this._erc1155Contract.setApprovalForAll(beneficiary, isApproved).sendTransactionAsync({ from: owner, }), ); return tx; } public async isApprovedForAllAsync(owner: string, beneficiary: string): Promise { - const isApprovedForAll = await this._erc1155Contract.isApprovedForAll.callAsync(owner, beneficiary); + const isApprovedForAll = await this._erc1155Contract.isApprovedForAll(owner, beneficiary).callAsync(); return isApprovedForAll; } public async assertBalancesAsync( @@ -163,18 +155,18 @@ export class Erc1155Wrapper { }); } public async isNonFungibleItemAsync(tokenId: BigNumber): Promise { - return this._erc1155Contract.isNonFungibleItem.callAsync(tokenId); + return this._erc1155Contract.isNonFungibleItem(tokenId).callAsync(); } public async isFungibleItemAsync(tokenId: BigNumber): Promise { return !(await this.isNonFungibleItemAsync(tokenId)); } public async getOwnerOfAsync(tokenId: BigNumber): Promise { - return this._erc1155Contract.ownerOf.callAsync(tokenId); + return this._erc1155Contract.ownerOf(tokenId).callAsync(); } /** * @dev Get the balance of an ERC1155 token for a given owner and token ID. */ public async getBalanceAsync(ownerAddress: string, tokenId: BigNumber): Promise { - return this._erc1155Contract.balanceOf.callAsync(ownerAddress, tokenId); + return this._erc1155Contract.balanceOf(ownerAddress, tokenId).callAsync(); } } diff --git a/contracts/erc1155/test/erc1155_token.ts b/contracts/erc1155/test/erc1155_token.ts index c06ceeb976..71d2821337 100644 --- a/contracts/erc1155/test/erc1155_token.ts +++ b/contracts/erc1155/test/erc1155_token.ts @@ -176,14 +176,9 @@ describe('ERC1155Token', () => { valueToTransfer, ); // execute transfer - const tx = erc1155Contract.safeTransferFrom.sendTransactionAsync( - spender, - receiver, - tokenToTransfer, - valueToTransfer, - receiverCallbackData, - { from: spender }, - ); + const tx = erc1155Contract + .safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData) + .sendTransactionAsync({ from: spender }); return expect(tx).to.revertWith(expectedError); }); it('should revert if callback reverts', async () => { @@ -193,19 +188,14 @@ describe('ERC1155Token', () => { // set receiver to reject balances const shouldRejectTransfer = true; await web3Wrapper.awaitTransactionSuccessAsync( - await erc1155Receiver.setRejectTransferFlag.sendTransactionAsync(shouldRejectTransfer), + await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).sendTransactionAsync(), constants.AWAIT_TRANSACTION_MINED_MS, ); // execute transfer await expectTransactionFailedAsync( - erc1155Contract.safeTransferFrom.sendTransactionAsync( - spender, - receiver, - tokenToTransfer, - valueToTransfer, - receiverCallbackData, - { from: spender }, - ), + erc1155Contract + .safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData) + .sendTransactionAsync({ from: spender }), RevertReason.TransferRejected, ); }); @@ -352,14 +342,9 @@ describe('ERC1155Token', () => { valuesToTransfer[0], ); // execute transfer - const tx = erc1155Contract.safeBatchTransferFrom.sendTransactionAsync( - spender, - receiver, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - { from: spender }, - ); + const tx = erc1155Contract + .safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData) + .sendTransactionAsync({ from: spender }); return expect(tx).to.revertWith(expectedError); }); it('should revert if callback reverts', async () => { @@ -369,19 +354,14 @@ describe('ERC1155Token', () => { // set receiver to reject balances const shouldRejectTransfer = true; await web3Wrapper.awaitTransactionSuccessAsync( - await erc1155Receiver.setRejectTransferFlag.sendTransactionAsync(shouldRejectTransfer), + await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).sendTransactionAsync(), constants.AWAIT_TRANSACTION_MINED_MS, ); // execute transfer await expectTransactionFailedAsync( - erc1155Contract.safeBatchTransferFrom.sendTransactionAsync( - spender, - receiver, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - { from: spender }, - ), + erc1155Contract + .safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData) + .sendTransactionAsync({ from: spender }), RevertReason.TransferRejected, ); }); @@ -429,14 +409,9 @@ describe('ERC1155Token', () => { await erc1155Wrapper.assertBalancesAsync(tokenHolders, [tokenToTransfer], expectedInitialBalances); // execute transfer await expectTransactionFailedAsync( - erc1155Contract.safeTransferFrom.sendTransactionAsync( - spender, - receiver, - tokenToTransfer, - valueToTransfer, - receiverCallbackData, - { from: delegatedSpender }, - ), + erc1155Contract + .safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData) + .sendTransactionAsync({ from: delegatedSpender }), RevertReason.InsufficientAllowance, ); }); @@ -482,14 +457,9 @@ describe('ERC1155Token', () => { await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances); // execute transfer await expectTransactionFailedAsync( - erc1155Contract.safeBatchTransferFrom.sendTransactionAsync( - spender, - receiver, - tokensToTransfer, - valuesToTransfer, - receiverCallbackData, - { from: delegatedSpender }, - ), + erc1155Contract + .safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData) + .sendTransactionAsync({ from: delegatedSpender }), RevertReason.InsufficientAllowance, ); }); diff --git a/contracts/erc20/test/lib_erc20_token.ts b/contracts/erc20/test/lib_erc20_token.ts index 48c85587ea..2d864302c9 100644 --- a/contracts/erc20/test/lib_erc20_token.ts +++ b/contracts/erc20/test/lib_erc20_token.ts @@ -39,13 +39,9 @@ blockchainTests('LibERC20Token', env => { it('calls the target with the correct arguments', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const { logs } = await testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - spender, - allowance, - ); + const { logs } = await testContract + .testApprove(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, spender, allowance) + .awaitTransactionSuccessAsync(); expect(logs).to.be.length(1); verifyEventsFromLogs(logs, [{ spender, allowance }], TestLibERC20TokenTargetEvents.ApproveCalled); }); @@ -53,37 +49,25 @@ blockchainTests('LibERC20Token', env => { it('succeeds if the target returns true', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - await testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - spender, - allowance, - ); + await testContract + .testApprove(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, spender, allowance) + .awaitTransactionSuccessAsync(); }); it('succeeds if the target returns nothing', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - await testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - constants.NULL_BYTES, - spender, - allowance, - ); + await testContract + .testApprove(false, encodeRevert(REVERT_STRING), constants.NULL_BYTES, spender, allowance) + .awaitTransactionSuccessAsync(); }); it('fails if the target returns false', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const tx = testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_FALSE, - spender, - allowance, - ); + const tx = testContract + .testApprove(false, encodeRevert(REVERT_STRING), ENCODED_FALSE, spender, allowance) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_FALSE); return expect(tx).to.revertWith(expectedError); }); @@ -91,13 +75,9 @@ blockchainTests('LibERC20Token', env => { it('fails if the target returns nonzero and not true', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const tx = testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TWO, - spender, - allowance, - ); + const tx = testContract + .testApprove(false, encodeRevert(REVERT_STRING), ENCODED_TWO, spender, allowance) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_TWO); return expect(tx).to.revertWith(expectedError); }); @@ -105,13 +85,9 @@ blockchainTests('LibERC20Token', env => { it('fails if the target returns less than 32 bytes', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const tx = testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_SHORT_TRUE, - spender, - allowance, - ); + const tx = testContract + .testApprove(false, encodeRevert(REVERT_STRING), ENCODED_SHORT_TRUE, spender, allowance) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_SHORT_TRUE); return expect(tx).to.revertWith(expectedError); }); @@ -119,13 +95,9 @@ blockchainTests('LibERC20Token', env => { it('fails if the target returns greater than 32 bytes', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const tx = testContract.testApprove.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_LONG_TRUE, - spender, - allowance, - ); + const tx = testContract + .testApprove(false, encodeRevert(REVERT_STRING), ENCODED_LONG_TRUE, spender, allowance) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_LONG_TRUE); return expect(tx).to.revertWith(expectedError); }); @@ -133,26 +105,18 @@ blockchainTests('LibERC20Token', env => { it('fails if the target reverts', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const tx = testContract.testApprove.awaitTransactionSuccessAsync( - true, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - spender, - allowance, - ); + const tx = testContract + .testApprove(true, encodeRevert(REVERT_STRING), ENCODED_TRUE, spender, allowance) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(REVERT_STRING); }); it('fails if the target reverts with no data', async () => { const spender = randomAddress(); const allowance = getRandomInteger(0, 100e18); - const tx = testContract.testApprove.awaitTransactionSuccessAsync( - true, - constants.NULL_BYTES, - ENCODED_TRUE, - spender, - allowance, - ); + const tx = testContract + .testApprove(true, constants.NULL_BYTES, ENCODED_TRUE, spender, allowance) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.rejectedWith('revert'); }); }); @@ -161,13 +125,9 @@ blockchainTests('LibERC20Token', env => { it('calls the target with the correct arguments', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - to, - amount, - ); + const { logs } = await testContract + .testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, to, amount) + .awaitTransactionSuccessAsync(); expect(logs).to.be.length(1); verifyEventsFromLogs(logs, [{ to, amount }], TestLibERC20TokenTargetEvents.TransferCalled); }); @@ -175,37 +135,25 @@ blockchainTests('LibERC20Token', env => { it('succeeds if the target returns true', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - await testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - to, - amount, - ); + await testContract + .testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, to, amount) + .awaitTransactionSuccessAsync(); }); it('succeeds if the target returns nothing', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - await testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - constants.NULL_BYTES, - to, - amount, - ); + await testContract + .testTransfer(false, encodeRevert(REVERT_STRING), constants.NULL_BYTES, to, amount) + .awaitTransactionSuccessAsync(); }); it('fails if the target returns false', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_FALSE, - to, - amount, - ); + const tx = testContract + .testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_FALSE, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_FALSE); return expect(tx).to.revertWith(expectedError); }); @@ -213,13 +161,9 @@ blockchainTests('LibERC20Token', env => { it('fails if the target returns nonzero and not true', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TWO, - to, - amount, - ); + const tx = testContract + .testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_TWO, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_TWO); return expect(tx).to.revertWith(expectedError); }); @@ -227,13 +171,9 @@ blockchainTests('LibERC20Token', env => { it('fails if the target returns less than 32 bytes', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_SHORT_TRUE, - to, - amount, - ); + const tx = testContract + .testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_SHORT_TRUE, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_SHORT_TRUE); return expect(tx).to.revertWith(expectedError); }); @@ -241,13 +181,9 @@ blockchainTests('LibERC20Token', env => { it('fails if the target returns greater than 32 bytes', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransfer.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_LONG_TRUE, - to, - amount, - ); + const tx = testContract + .testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_LONG_TRUE, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_LONG_TRUE); return expect(tx).to.revertWith(expectedError); }); @@ -255,26 +191,18 @@ blockchainTests('LibERC20Token', env => { it('fails if the target reverts', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransfer.awaitTransactionSuccessAsync( - true, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - to, - amount, - ); + const tx = testContract + .testTransfer(true, encodeRevert(REVERT_STRING), ENCODED_TRUE, to, amount) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(REVERT_STRING); }); it('fails if the target reverts with no data', async () => { const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransfer.awaitTransactionSuccessAsync( - true, - constants.NULL_BYTES, - ENCODED_TRUE, - to, - amount, - ); + const tx = testContract + .testTransfer(true, constants.NULL_BYTES, ENCODED_TRUE, to, amount) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.rejectedWith('revert'); }); }); @@ -284,14 +212,9 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - owner, - to, - amount, - ); + const { logs } = await testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, owner, to, amount) + .awaitTransactionSuccessAsync(); expect(logs).to.be.length(1); verifyEventsFromLogs(logs, [{ from: owner, to, amount }], TestLibERC20TokenTargetEvents.TransferFromCalled); }); @@ -300,42 +223,27 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - await testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - owner, - to, - amount, - ); + await testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, owner, to, amount) + .awaitTransactionSuccessAsync(); }); it('succeeds if the target returns nothing', async () => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - await testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - constants.NULL_BYTES, - owner, - to, - amount, - ); + await testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), constants.NULL_BYTES, owner, to, amount) + .awaitTransactionSuccessAsync(); }); it('fails if the target returns false', async () => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_FALSE, - owner, - to, - amount, - ); + const tx = testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_FALSE, owner, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_FALSE); return expect(tx).to.revertWith(expectedError); }); @@ -344,14 +252,9 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_TWO, - owner, - to, - amount, - ); + const tx = testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_TWO, owner, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_TWO); return expect(tx).to.revertWith(expectedError); }); @@ -360,14 +263,9 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_SHORT_TRUE, - owner, - to, - amount, - ); + const tx = testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_SHORT_TRUE, owner, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_SHORT_TRUE); return expect(tx).to.revertWith(expectedError); }); @@ -376,14 +274,9 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync( - false, - encodeRevert(REVERT_STRING), - ENCODED_LONG_TRUE, - owner, - to, - amount, - ); + const tx = testContract + .testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_LONG_TRUE, owner, to, amount) + .awaitTransactionSuccessAsync(); const expectedError = new RawRevertError(ENCODED_LONG_TRUE); return expect(tx).to.revertWith(expectedError); }); @@ -392,14 +285,9 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync( - true, - encodeRevert(REVERT_STRING), - ENCODED_TRUE, - owner, - to, - amount, - ); + const tx = testContract + .testTransferFrom(true, encodeRevert(REVERT_STRING), ENCODED_TRUE, owner, to, amount) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(REVERT_STRING); }); @@ -407,14 +295,9 @@ blockchainTests('LibERC20Token', env => { const owner = randomAddress(); const to = randomAddress(); const amount = getRandomInteger(0, 100e18); - const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync( - true, - constants.NULL_BYTES, - ENCODED_TRUE, - owner, - to, - amount, - ); + const tx = testContract + .testTransferFrom(true, constants.NULL_BYTES, ENCODED_TRUE, owner, to, amount) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.rejectedWith('revert'); }); }); diff --git a/contracts/erc20/test/unlimited_allowance_token.ts b/contracts/erc20/test/unlimited_allowance_token.ts index 34d2e9333f..e5f61e327f 100644 --- a/contracts/erc20/test/unlimited_allowance_token.ts +++ b/contracts/erc20/test/unlimited_allowance_token.ts @@ -46,7 +46,7 @@ describe('UnlimitedAllowanceToken', () => { constants.DUMMY_TOKEN_TOTAL_SUPPLY, ); await web3Wrapper.awaitTransactionSuccessAsync( - await token.mint.sendTransactionAsync(MAX_MINT_VALUE, { from: owner }), + await token.mint(MAX_MINT_VALUE).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); }); @@ -58,24 +58,24 @@ describe('UnlimitedAllowanceToken', () => { }); describe('transfer', () => { it('should revert if owner has insufficient balance', async () => { - const ownerBalance = await token.balanceOf.callAsync(owner); + const ownerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = ownerBalance.plus(1); return expectContractCallFailedAsync( - token.transfer.callAsync(spender, amountToTransfer, { from: owner }), + token.transfer(spender, amountToTransfer).callAsync({ from: owner }), RevertReason.Erc20InsufficientBalance, ); }); it('should transfer balance from sender to receiver', async () => { const receiver = spender; - const initOwnerBalance = await token.balanceOf.callAsync(owner); + const initOwnerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = new BigNumber(1); await web3Wrapper.awaitTransactionSuccessAsync( - await token.transfer.sendTransactionAsync(receiver, amountToTransfer, { from: owner }), + await token.transfer(receiver, amountToTransfer).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const finalOwnerBalance = await token.balanceOf.callAsync(owner); - const finalReceiverBalance = await token.balanceOf.callAsync(receiver); + const finalOwnerBalance = await token.balanceOf(owner).callAsync(); + const finalReceiverBalance = await token.balanceOf(receiver).callAsync(); const expectedFinalOwnerBalance = initOwnerBalance.minus(amountToTransfer); const expectedFinalReceiverBalance = amountToTransfer; @@ -84,7 +84,7 @@ describe('UnlimitedAllowanceToken', () => { }); it('should return true on a 0 value transfer', async () => { - const didReturnTrue = await token.transfer.callAsync(spender, new BigNumber(0), { + const didReturnTrue = await token.transfer(spender, new BigNumber(0)).callAsync({ from: owner, }); expect(didReturnTrue).to.be.true(); @@ -93,14 +93,14 @@ describe('UnlimitedAllowanceToken', () => { describe('transferFrom', () => { it('should revert if owner has insufficient balance', async () => { - const ownerBalance = await token.balanceOf.callAsync(owner); + const ownerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = ownerBalance.plus(1); await web3Wrapper.awaitTransactionSuccessAsync( - await token.approve.sendTransactionAsync(spender, amountToTransfer, { from: owner }), + await token.approve(spender, amountToTransfer).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); return expectContractCallFailedAsync( - token.transferFrom.callAsync(owner, spender, amountToTransfer, { + token.transferFrom(owner, spender, amountToTransfer).callAsync({ from: spender, }), RevertReason.Erc20InsufficientBalance, @@ -108,15 +108,15 @@ describe('UnlimitedAllowanceToken', () => { }); it('should revert if spender has insufficient allowance', async () => { - const ownerBalance = await token.balanceOf.callAsync(owner); + const ownerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = ownerBalance; - const spenderAllowance = await token.allowance.callAsync(owner, spender); + const spenderAllowance = await token.allowance(owner, spender).callAsync(); const isSpenderAllowanceInsufficient = spenderAllowance.comparedTo(amountToTransfer) < 0; expect(isSpenderAllowanceInsufficient).to.be.true(); return expectContractCallFailedAsync( - token.transferFrom.callAsync(owner, spender, amountToTransfer, { + token.transferFrom(owner, spender, amountToTransfer).callAsync({ from: spender, }), RevertReason.Erc20InsufficientAllowance, @@ -125,72 +125,72 @@ describe('UnlimitedAllowanceToken', () => { it('should return true on a 0 value transfer', async () => { const amountToTransfer = new BigNumber(0); - const didReturnTrue = await token.transferFrom.callAsync(owner, spender, amountToTransfer, { + const didReturnTrue = await token.transferFrom(owner, spender, amountToTransfer).callAsync({ from: spender, }); expect(didReturnTrue).to.be.true(); }); it('should not modify spender allowance if spender allowance is 2^256 - 1', async () => { - const initOwnerBalance = await token.balanceOf.callAsync(owner); + const initOwnerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = initOwnerBalance; const initSpenderAllowance = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; await web3Wrapper.awaitTransactionSuccessAsync( - await token.approve.sendTransactionAsync(spender, initSpenderAllowance, { from: owner }), + await token.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await token.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, { + await token.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({ from: spender, gas: constants.MAX_TOKEN_TRANSFERFROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newSpenderAllowance = await token.allowance.callAsync(owner, spender); + const newSpenderAllowance = await token.allowance(owner, spender).callAsync(); expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance); }); it('should transfer the correct balances if spender has sufficient allowance', async () => { - const initOwnerBalance = await token.balanceOf.callAsync(owner); + const initOwnerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = initOwnerBalance; const initSpenderAllowance = initOwnerBalance; await web3Wrapper.awaitTransactionSuccessAsync( - await token.approve.sendTransactionAsync(spender, initSpenderAllowance, { from: owner }), + await token.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await token.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, { + await token.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({ from: spender, gas: constants.MAX_TOKEN_TRANSFERFROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newOwnerBalance = await token.balanceOf.callAsync(owner); - const newSpenderBalance = await token.balanceOf.callAsync(spender); + const newOwnerBalance = await token.balanceOf(owner).callAsync(); + const newSpenderBalance = await token.balanceOf(spender).callAsync(); expect(newOwnerBalance).to.be.bignumber.equal(0); expect(newSpenderBalance).to.be.bignumber.equal(initOwnerBalance); }); it('should modify allowance if spender has sufficient allowance less than 2^256 - 1', async () => { - const initOwnerBalance = await token.balanceOf.callAsync(owner); + const initOwnerBalance = await token.balanceOf(owner).callAsync(); const amountToTransfer = initOwnerBalance; const initSpenderAllowance = initOwnerBalance; await web3Wrapper.awaitTransactionSuccessAsync( - await token.approve.sendTransactionAsync(spender, initSpenderAllowance, { from: owner }), + await token.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await token.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, { + await token.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({ from: spender, gas: constants.MAX_TOKEN_TRANSFERFROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newSpenderAllowance = await token.allowance.callAsync(owner, spender); + const newSpenderAllowance = await token.allowance(owner, spender).callAsync(); expect(newSpenderAllowance).to.be.bignumber.equal(0); }); }); diff --git a/contracts/erc20/test/weth9.ts b/contracts/erc20/test/weth9.ts index 1d766184fe..f6595b3735 100644 --- a/contracts/erc20/test/weth9.ts +++ b/contracts/erc20/test/weth9.ts @@ -56,16 +56,16 @@ describe('EtherToken', () => { const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); const ethToDeposit = initEthBalance.plus(1); - return expectInsufficientFundsAsync(etherToken.deposit.sendTransactionAsync({ value: ethToDeposit })); + return expectInsufficientFundsAsync(etherToken.deposit().sendTransactionAsync({ value: ethToDeposit })); }); it('should convert deposited Ether to wrapped Ether tokens', async () => { const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); - const initEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const initEthTokenBalance = await etherToken.balanceOf(account).callAsync(); const ethToDeposit = new BigNumber(Web3Wrapper.toWei(new BigNumber(1))); - const txHash = await etherToken.deposit.sendTransactionAsync({ value: ethToDeposit }); + const txHash = await etherToken.deposit().sendTransactionAsync({ value: ethToDeposit }); const receipt = await web3Wrapper.awaitTransactionSuccessAsync( txHash, constants.AWAIT_TRANSACTION_MINED_MS, @@ -73,7 +73,7 @@ describe('EtherToken', () => { const ethSpentOnGas = gasPrice.times(receipt.gasUsed); const finalEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); - const finalEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const finalEthTokenBalance = await etherToken.balanceOf(account).callAsync(); expect(finalEthBalance).to.be.bignumber.equal(initEthBalance.minus(ethToDeposit.plus(ethSpentOnGas))); expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.plus(ethToDeposit)); @@ -82,25 +82,25 @@ describe('EtherToken', () => { describe('withdraw', () => { it('should revert if caller attempts to withdraw greater than caller balance', async () => { - const initEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const initEthTokenBalance = await etherToken.balanceOf(account).callAsync(); const ethTokensToWithdraw = initEthTokenBalance.plus(1); return expectTransactionFailedWithoutReasonAsync( - etherToken.withdraw.sendTransactionAsync(ethTokensToWithdraw), + etherToken.withdraw(ethTokensToWithdraw).sendTransactionAsync(), ); }); it('should convert ether tokens to ether with sufficient balance', async () => { const ethToDeposit = new BigNumber(Web3Wrapper.toWei(new BigNumber(1))); await web3Wrapper.awaitTransactionSuccessAsync( - await etherToken.deposit.sendTransactionAsync({ value: ethToDeposit }), + await etherToken.deposit().sendTransactionAsync({ value: ethToDeposit }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const initEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const initEthTokenBalance = await etherToken.balanceOf(account).callAsync(); const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); const ethTokensToWithdraw = initEthTokenBalance; expect(ethTokensToWithdraw).to.not.be.bignumber.equal(0); - const txHash = await etherToken.withdraw.sendTransactionAsync(ethTokensToWithdraw, { + const txHash = await etherToken.withdraw(ethTokensToWithdraw).sendTransactionAsync({ gas: constants.MAX_ETHERTOKEN_WITHDRAW_GAS, }); const receipt = await web3Wrapper.awaitTransactionSuccessAsync( @@ -110,7 +110,7 @@ describe('EtherToken', () => { const ethSpentOnGas = gasPrice.times(receipt.gasUsed); const finalEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); - const finalEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const finalEthTokenBalance = await etherToken.balanceOf(account).callAsync(); expect(finalEthBalance).to.be.bignumber.equal( initEthBalance.plus(ethTokensToWithdraw.minus(ethSpentOnGas)), @@ -122,7 +122,7 @@ describe('EtherToken', () => { describe('fallback', () => { it('should convert sent ether to ether tokens', async () => { const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); - const initEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const initEthTokenBalance = await etherToken.balanceOf(account).callAsync(); const ethToDeposit = Web3Wrapper.toBaseUnitAmount(new BigNumber(1), 18); @@ -140,7 +140,7 @@ describe('EtherToken', () => { const ethSpentOnGas = gasPrice.times(receipt.gasUsed); const finalEthBalance = await web3Wrapper.getBalanceInWeiAsync(account); - const finalEthTokenBalance = await etherToken.balanceOf.callAsync(account); + const finalEthTokenBalance = await etherToken.balanceOf(account).callAsync(); expect(finalEthBalance).to.be.bignumber.equal(initEthBalance.minus(ethToDeposit.plus(ethSpentOnGas))); expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.plus(ethToDeposit)); diff --git a/contracts/erc20/test/zrx_token.ts b/contracts/erc20/test/zrx_token.ts index 068d8c5c56..82d7dfc881 100644 --- a/contracts/erc20/test/zrx_token.ts +++ b/contracts/erc20/test/zrx_token.ts @@ -44,25 +44,25 @@ describe('ZRXToken', () => { }); describe('constants', () => { it('should have 18 decimals', async () => { - const decimals = new BigNumber(await zrxToken.decimals.callAsync()); + const decimals = new BigNumber(await zrxToken.decimals().callAsync()); const expectedDecimals = 18; expect(decimals).to.be.bignumber.equal(expectedDecimals); }); it('should have a total supply of 1 billion tokens', async () => { - const totalSupply = new BigNumber(await zrxToken.totalSupply.callAsync()); + const totalSupply = new BigNumber(await zrxToken.totalSupply().callAsync()); const expectedTotalSupply = 1000000000; expect(Web3Wrapper.toUnitAmount(totalSupply, 18)).to.be.bignumber.equal(expectedTotalSupply); }); it('should be named 0x Protocol Token', async () => { - const name = await zrxToken.name.callAsync(); + const name = await zrxToken.name().callAsync(); const expectedName = '0x Protocol Token'; expect(name).to.be.equal(expectedName); }); it('should have the symbol ZRX', async () => { - const symbol = await zrxToken.symbol.callAsync(); + const symbol = await zrxToken.symbol().callAsync(); const expectedSymbol = 'ZRX'; expect(symbol).to.be.equal(expectedSymbol); }); @@ -70,8 +70,8 @@ describe('ZRXToken', () => { describe('constructor', () => { it('should initialize owner balance to totalSupply', async () => { - const ownerBalance = await zrxToken.balanceOf.callAsync(owner); - const totalSupply = new BigNumber(await zrxToken.totalSupply.callAsync()); + const ownerBalance = await zrxToken.balanceOf(owner).callAsync(); + const totalSupply = new BigNumber(await zrxToken.totalSupply().callAsync()); expect(totalSupply).to.be.bignumber.equal(ownerBalance); }); }); @@ -79,14 +79,14 @@ describe('ZRXToken', () => { describe('transfer', () => { it('should transfer balance from sender to receiver', async () => { const receiver = spender; - const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner); + const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync(); const amountToTransfer = new BigNumber(1); await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.transfer.sendTransactionAsync(receiver, amountToTransfer, { from: owner }), + await zrxToken.transfer(receiver, amountToTransfer).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const finalOwnerBalance = await zrxToken.balanceOf.callAsync(owner); - const finalReceiverBalance = await zrxToken.balanceOf.callAsync(receiver); + const finalOwnerBalance = await zrxToken.balanceOf(owner).callAsync(); + const finalReceiverBalance = await zrxToken.balanceOf(receiver).callAsync(); const expectedFinalOwnerBalance = initOwnerBalance.minus(amountToTransfer); const expectedFinalReceiverBalance = amountToTransfer; @@ -95,7 +95,7 @@ describe('ZRXToken', () => { }); it('should return true on a 0 value transfer', async () => { - const didReturnTrue = await zrxToken.transfer.callAsync(spender, new BigNumber(0), { + const didReturnTrue = await zrxToken.transfer(spender, new BigNumber(0)).callAsync({ from: owner, }); expect(didReturnTrue).to.be.true(); @@ -104,30 +104,30 @@ describe('ZRXToken', () => { describe('transferFrom', () => { it('should return false if owner has insufficient balance', async () => { - const ownerBalance = await zrxToken.balanceOf.callAsync(owner); + const ownerBalance = await zrxToken.balanceOf(owner).callAsync(); const amountToTransfer = ownerBalance.plus(1); await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.approve.sendTransactionAsync(spender, amountToTransfer, { + await zrxToken.approve(spender, amountToTransfer).sendTransactionAsync({ from: owner, gas: constants.MAX_TOKEN_APPROVE_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const didReturnTrue = await zrxToken.transferFrom.callAsync(owner, spender, amountToTransfer, { + const didReturnTrue = await zrxToken.transferFrom(owner, spender, amountToTransfer).callAsync({ from: spender, }); expect(didReturnTrue).to.be.false(); }); it('should return false if spender has insufficient allowance', async () => { - const ownerBalance = await zrxToken.balanceOf.callAsync(owner); + const ownerBalance = await zrxToken.balanceOf(owner).callAsync(); const amountToTransfer = ownerBalance; - const spenderAllowance = await zrxToken.allowance.callAsync(owner, spender); + const spenderAllowance = await zrxToken.allowance(owner, spender).callAsync(); const isSpenderAllowanceInsufficient = spenderAllowance.comparedTo(amountToTransfer) < 0; expect(isSpenderAllowanceInsufficient).to.be.true(); - const didReturnTrue = await zrxToken.transferFrom.callAsync(owner, spender, amountToTransfer, { + const didReturnTrue = await zrxToken.transferFrom(owner, spender, amountToTransfer).callAsync({ from: spender, }); expect(didReturnTrue).to.be.false(); @@ -135,75 +135,75 @@ describe('ZRXToken', () => { it('should return true on a 0 value transfer', async () => { const amountToTransfer = new BigNumber(0); - const didReturnTrue = await zrxToken.transferFrom.callAsync(owner, spender, amountToTransfer, { + const didReturnTrue = await zrxToken.transferFrom(owner, spender, amountToTransfer).callAsync({ from: spender, }); expect(didReturnTrue).to.be.true(); }); it('should not modify spender allowance if spender allowance is 2^256 - 1', async () => { - const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner); + const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync(); const amountToTransfer = initOwnerBalance; const initSpenderAllowance = MAX_UINT; await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.approve.sendTransactionAsync(spender, initSpenderAllowance, { + await zrxToken.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner, gas: constants.MAX_TOKEN_APPROVE_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, { + await zrxToken.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({ from: spender, gas: constants.MAX_TOKEN_TRANSFERFROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newSpenderAllowance = await zrxToken.allowance.callAsync(owner, spender); + const newSpenderAllowance = await zrxToken.allowance(owner, spender).callAsync(); expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance); }); it('should transfer the correct balances if spender has sufficient allowance', async () => { - const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner); - const initSpenderBalance = await zrxToken.balanceOf.callAsync(spender); + const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync(); + const initSpenderBalance = await zrxToken.balanceOf(spender).callAsync(); const amountToTransfer = initOwnerBalance; const initSpenderAllowance = initOwnerBalance; await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.approve.sendTransactionAsync(spender, initSpenderAllowance), + await zrxToken.approve(spender, initSpenderAllowance).sendTransactionAsync(), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, { + await zrxToken.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({ from: spender, gas: constants.MAX_TOKEN_TRANSFERFROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newOwnerBalance = await zrxToken.balanceOf.callAsync(owner); - const newSpenderBalance = await zrxToken.balanceOf.callAsync(spender); + const newOwnerBalance = await zrxToken.balanceOf(owner).callAsync(); + const newSpenderBalance = await zrxToken.balanceOf(spender).callAsync(); expect(newOwnerBalance).to.be.bignumber.equal(0); expect(newSpenderBalance).to.be.bignumber.equal(initSpenderBalance.plus(initOwnerBalance)); }); it('should modify allowance if spender has sufficient allowance less than 2^256 - 1', async () => { - const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner); + const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync(); const amountToTransfer = initOwnerBalance; await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.approve.sendTransactionAsync(spender, amountToTransfer), + await zrxToken.approve(spender, amountToTransfer).sendTransactionAsync(), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await zrxToken.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, { + await zrxToken.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({ from: spender, gas: constants.MAX_TOKEN_TRANSFERFROM_GAS, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newSpenderAllowance = await zrxToken.allowance.callAsync(owner, spender); + const newSpenderAllowance = await zrxToken.allowance(owner, spender).callAsync(); expect(newSpenderAllowance).to.be.bignumber.equal(0); }); }); diff --git a/contracts/erc721/test/erc721_token.ts b/contracts/erc721/test/erc721_token.ts index 04cbc1e549..73829651d8 100644 --- a/contracts/erc721/test/erc721_token.ts +++ b/contracts/erc721/test/erc721_token.ts @@ -61,7 +61,7 @@ describe('ERC721Token', () => { ); logDecoder = new LogDecoder(web3Wrapper, artifacts); await web3Wrapper.awaitTransactionSuccessAsync( - await token.mint.sendTransactionAsync(owner, tokenId, { from: owner }), + await token.mint(owner, tokenId).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); }); @@ -78,7 +78,7 @@ describe('ERC721Token', () => { const to = erc721Receiver.address; const unownedTokenId = new BigNumber(2); await expectTransactionFailedAsync( - token.transferFrom.sendTransactionAsync(from, to, unownedTokenId), + token.transferFrom(from, to, unownedTokenId).sendTransactionAsync(), RevertReason.Erc721ZeroOwner, ); }); @@ -86,7 +86,7 @@ describe('ERC721Token', () => { const from = owner; const to = constants.NULL_ADDRESS; await expectTransactionFailedAsync( - token.transferFrom.sendTransactionAsync(from, to, tokenId), + token.transferFrom(from, to, tokenId).sendTransactionAsync(), RevertReason.Erc721ZeroToAddress, ); }); @@ -94,7 +94,7 @@ describe('ERC721Token', () => { const from = spender; const to = erc721Receiver.address; await expectTransactionFailedAsync( - token.transferFrom.sendTransactionAsync(from, to, tokenId), + token.transferFrom(from, to, tokenId).sendTransactionAsync(), RevertReason.Erc721OwnerMismatch, ); }); @@ -102,7 +102,7 @@ describe('ERC721Token', () => { const from = owner; const to = erc721Receiver.address; await expectTransactionFailedAsync( - token.transferFrom.sendTransactionAsync(from, to, tokenId, { from: spender }), + token.transferFrom(from, to, tokenId).sendTransactionAsync({ from: spender }), RevertReason.Erc721InvalidSpender, ); }); @@ -110,9 +110,9 @@ describe('ERC721Token', () => { const from = owner; const to = erc721Receiver.address; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.transferFrom.sendTransactionAsync(from, to, tokenId), + await token.transferFrom(from, to, tokenId).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); const log = txReceipt.logs[0] as LogWithDecodedArgs; expect(log.args._from).to.be.equal(from); @@ -122,16 +122,16 @@ describe('ERC721Token', () => { it('should transfer the token if spender is approved for all', async () => { const isApproved = true; await web3Wrapper.awaitTransactionSuccessAsync( - await token.setApprovalForAll.sendTransactionAsync(spender, isApproved), + await token.setApprovalForAll(spender, isApproved).sendTransactionAsync(), constants.AWAIT_TRANSACTION_MINED_MS, ); const from = owner; const to = erc721Receiver.address; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.transferFrom.sendTransactionAsync(from, to, tokenId), + await token.transferFrom(from, to, tokenId).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); const log = txReceipt.logs[0] as LogWithDecodedArgs; expect(log.args._from).to.be.equal(from); @@ -140,19 +140,19 @@ describe('ERC721Token', () => { }); it('should transfer the token if spender is individually approved', async () => { await web3Wrapper.awaitTransactionSuccessAsync( - await token.approve.sendTransactionAsync(spender, tokenId), + await token.approve(spender, tokenId).sendTransactionAsync(), constants.AWAIT_TRANSACTION_MINED_MS, ); const from = owner; const to = erc721Receiver.address; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.transferFrom.sendTransactionAsync(from, to, tokenId), + await token.transferFrom(from, to, tokenId).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); - const approvedAddress = await token.getApproved.callAsync(tokenId); + const approvedAddress = await token.getApproved(tokenId).callAsync(); expect(approvedAddress).to.be.equal(constants.NULL_ADDRESS); const log = txReceipt.logs[0] as LogWithDecodedArgs; expect(log.args._from).to.be.equal(from); @@ -165,9 +165,9 @@ describe('ERC721Token', () => { const from = owner; const to = spender; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId), + await token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); const log = txReceipt.logs[0] as LogWithDecodedArgs; expect(log.args._from).to.be.equal(from); @@ -186,7 +186,7 @@ describe('ERC721Token', () => { const from = owner; const to = contract.address; await expectTransactionFailedWithoutReasonAsync( - token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId), + token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(), ); }); it('should revert if onERC721Received does not return the correct value', async () => { @@ -199,7 +199,7 @@ describe('ERC721Token', () => { const from = owner; const to = invalidErc721Receiver.address; await expectTransactionFailedAsync( - token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId), + token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(), RevertReason.Erc721InvalidSelector, ); }); @@ -207,9 +207,9 @@ describe('ERC721Token', () => { const from = owner; const to = erc721Receiver.address; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId), + await token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); const transferLog = txReceipt.logs[0] as LogWithDecodedArgs; const receiverLog = txReceipt.logs[1] as LogWithDecodedArgs; @@ -228,9 +228,9 @@ describe('ERC721Token', () => { const from = owner; const to = spender; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data), + await token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); const log = txReceipt.logs[0] as LogWithDecodedArgs; expect(log.args._from).to.be.equal(from); @@ -249,7 +249,7 @@ describe('ERC721Token', () => { const from = owner; const to = contract.address; await expectTransactionFailedWithoutReasonAsync( - token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data), + token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(), ); }); it('should revert if onERC721Received does not return the correct value', async () => { @@ -262,7 +262,7 @@ describe('ERC721Token', () => { const from = owner; const to = invalidErc721Receiver.address; await expectTransactionFailedAsync( - token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data), + token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(), RevertReason.Erc721InvalidSelector, ); }); @@ -270,9 +270,9 @@ describe('ERC721Token', () => { const from = owner; const to = erc721Receiver.address; const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data), + await token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(), ); - const newOwner = await token.ownerOf.callAsync(tokenId); + const newOwner = await token.ownerOf(tokenId).callAsync(); expect(newOwner).to.be.equal(to); const transferLog = txReceipt.logs[0] as LogWithDecodedArgs; const receiverLog = txReceipt.logs[1] as LogWithDecodedArgs; diff --git a/contracts/exchange-libs/test/lib_eip712_exchange_domain.ts b/contracts/exchange-libs/test/lib_eip712_exchange_domain.ts index 536aff2f22..ddee5eaf1c 100644 --- a/contracts/exchange-libs/test/lib_eip712_exchange_domain.ts +++ b/contracts/exchange-libs/test/lib_eip712_exchange_domain.ts @@ -25,7 +25,7 @@ blockchainTests('LibEIP712ExchangeDomain', env => { version: constants.EIP712_DOMAIN_VERSION, }; const expectedDomainHash = ethUtil.bufferToHex(signTypedDataUtils.generateDomainHash(domain)); - const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH.callAsync(); + const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH().callAsync(); expect(actualDomainHash).to.be.equal(expectedDomainHash); }); it('should calculate the correct domain hash when verifyingContractAddressIfExists is set to a non-null address', async () => { @@ -46,7 +46,7 @@ blockchainTests('LibEIP712ExchangeDomain', env => { version: constants.EIP712_DOMAIN_VERSION, }; const expectedDomainHash = ethUtil.bufferToHex(signTypedDataUtils.generateDomainHash(domain)); - const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH.callAsync(); + const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH().callAsync(); expect(actualDomainHash).to.be.equal(expectedDomainHash); }); }); diff --git a/contracts/exchange-libs/test/lib_fill_results.ts b/contracts/exchange-libs/test/lib_fill_results.ts index 8d65b0d0ac..7e79a3a1d9 100644 --- a/contracts/exchange-libs/test/lib_fill_results.ts +++ b/contracts/exchange-libs/test/lib_fill_results.ts @@ -109,12 +109,14 @@ blockchainTests('LibFillResults', env => { otherAmount: BigNumber, ): Promise { const order = makeOrder(otherAmount, orderTakerAssetAmount, otherAmount, otherAmount); - return libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - takerAssetFilledAmount, // Using this so that the gas price is distinct from protocolFeeMultiplier - otherAmount, - ); + return libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + takerAssetFilledAmount, // Using this so that the gas price is distinct from protocolFeeMultiplier + otherAmount, + ) + .callAsync(); } testCombinatoriallyWithReferenceFunc( @@ -148,12 +150,14 @@ blockchainTests('LibFillResults', env => { DEFAULT_PROTOCOL_FEE_MULTIPLIER, DEFAULT_GAS_PRICE, ); - const actual = await libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ); + const actual = await libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(); expect(actual).to.deep.eq(expected); }); @@ -170,12 +174,14 @@ blockchainTests('LibFillResults', env => { order.makerAssetAmount, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -198,12 +204,14 @@ blockchainTests('LibFillResults', env => { order.makerFee, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -221,12 +229,14 @@ blockchainTests('LibFillResults', env => { order.takerFee, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -238,12 +248,14 @@ blockchainTests('LibFillResults', env => { const takerAssetFilledAmount = ONE_ETHER; const expectedError = new LibMathRevertErrors.DivisionByZeroError(); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -259,12 +271,14 @@ blockchainTests('LibFillResults', env => { order.makerAssetAmount, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -286,12 +300,14 @@ blockchainTests('LibFillResults', env => { order.makerFee, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -313,12 +329,14 @@ blockchainTests('LibFillResults', env => { order.takerFee, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); @@ -336,12 +354,9 @@ blockchainTests('LibFillResults', env => { MAX_UINT256, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - MAX_UINT256, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults(order, takerAssetFilledAmount, MAX_UINT256, DEFAULT_GAS_PRICE) + .callAsync(), ).to.revertWith(expectedError); }); @@ -363,12 +378,14 @@ blockchainTests('LibFillResults', env => { order.makerFee, ); return expect( - libsContract.calculateFillResults.callAsync( - order, - takerAssetFilledAmount, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - DEFAULT_GAS_PRICE, - ), + libsContract + .calculateFillResults( + order, + takerAssetFilledAmount, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + DEFAULT_GAS_PRICE, + ) + .callAsync(), ).to.revertWith(expectedError); }); }); @@ -396,7 +413,7 @@ blockchainTests('LibFillResults', env => { it('matches the output of the reference function', async () => { const [a, b] = DEFAULT_FILL_RESULTS; const expected = addFillResults(a, b); - const actual = await libsContract.addFillResults.callAsync(a, b); + const actual = await libsContract.addFillResults(a, b).callAsync(); expect(actual).to.deep.equal(expected); }); @@ -408,7 +425,7 @@ blockchainTests('LibFillResults', env => { a.makerAssetFilledAmount, b.makerAssetFilledAmount, ); - return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError); + return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError); }); it('reverts if computing `takerAssetFilledAmount` overflows', async () => { @@ -419,7 +436,7 @@ blockchainTests('LibFillResults', env => { a.takerAssetFilledAmount, b.takerAssetFilledAmount, ); - return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError); + return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError); }); it('reverts if computing `makerFeePaid` overflows', async () => { @@ -430,7 +447,7 @@ blockchainTests('LibFillResults', env => { a.makerFeePaid, b.makerFeePaid, ); - return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError); + return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError); }); it('reverts if computing `takerFeePaid` overflows', async () => { @@ -441,7 +458,7 @@ blockchainTests('LibFillResults', env => { a.takerFeePaid, b.takerFeePaid, ); - return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError); + return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError); }); it('reverts if computing `protocolFeePaid` overflows', async () => { @@ -452,7 +469,7 @@ blockchainTests('LibFillResults', env => { a.protocolFeePaid, b.protocolFeePaid, ); - return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError); + return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError); }); }); }); @@ -516,16 +533,17 @@ blockchainTests('LibFillResults', env => { gasPrice: BigNumber, from?: string, ): Promise { - const actualMatchedFillResults = await libsContract.calculateMatchedFillResults.callAsync( - leftOrder, - rightOrder, - leftOrderTakerAssetFilledAmount, - rightOrderTakerAssetFilledAmount, - protocolFeeMultiplier, - gasPrice, - false, - { from }, - ); + const actualMatchedFillResults = await libsContract + .calculateMatchedFillResults( + leftOrder, + rightOrder, + leftOrderTakerAssetFilledAmount, + rightOrderTakerAssetFilledAmount, + protocolFeeMultiplier, + gasPrice, + false, + ) + .callAsync({ from }); expect(actualMatchedFillResults).to.be.deep.eq(expectedMatchedFillResults); } @@ -1187,16 +1205,17 @@ blockchainTests('LibFillResults', env => { gasPrice: BigNumber, from?: string, ): Promise { - const actualMatchedFillResults = await libsContract.calculateMatchedFillResults.callAsync( - leftOrder, - rightOrder, - leftOrderTakerAssetFilledAmount, - rightOrderTakerAssetFilledAmount, - protocolFeeMultiplier, - gasPrice, - true, - { from }, - ); + const actualMatchedFillResults = await libsContract + .calculateMatchedFillResults( + leftOrder, + rightOrder, + leftOrderTakerAssetFilledAmount, + rightOrderTakerAssetFilledAmount, + protocolFeeMultiplier, + gasPrice, + true, + ) + .callAsync({ from }); expect(actualMatchedFillResults).to.be.deep.eq(expectedMatchedFillResults); } diff --git a/contracts/exchange-libs/test/lib_math.ts b/contracts/exchange-libs/test/lib_math.ts index a5d1c73a19..3834c3b6b2 100644 --- a/contracts/exchange-libs/test/lib_math.ts +++ b/contracts/exchange-libs/test/lib_math.ts @@ -43,8 +43,7 @@ blockchainTests('LibMath', env => { function createContractTestFunction(name: string): (...args: any[]) => Promise { return async (...args: any[]): Promise => { - const method = (libsContract as any)[name] as { callAsync: (...args: any[]) => Promise }; - return method.callAsync(...args); + return (libsContract as any)[name](...args).callAsync; }; } @@ -64,7 +63,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = getPartialAmountFloor(numerator, denominator, target); - const actual = await libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -73,7 +72,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.times(1.8); const target = ONE_ETHER; const expected = ONE_ETHER.dividedToIntegerBy(3); - const actual = await libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -87,7 +86,7 @@ blockchainTests('LibMath', env => { denominator, ); return expect( - libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -101,7 +100,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -123,7 +122,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = getPartialAmountCeil(numerator, denominator, target); - const actual = await libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -132,7 +131,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.times(1.8); const target = ONE_ETHER; const expected = ONE_ETHER.dividedToIntegerBy(3).plus(1); - const actual = await libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -147,7 +146,7 @@ blockchainTests('LibMath', env => { new BigNumber(1), ); return expect( - libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -161,7 +160,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -183,7 +182,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = safeGetPartialAmountFloor(numerator, denominator, target); - const actual = await libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -192,7 +191,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.times(1.8); const target = ONE_ETHER; const expected = ONE_ETHER.dividedToIntegerBy(3); - const actual = await libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -202,7 +201,7 @@ blockchainTests('LibMath', env => { const target = new BigNumber(333); const expectedError = new LibMathRevertErrors.RoundingError(numerator, denominator, target); return expect( - libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -212,7 +211,7 @@ blockchainTests('LibMath', env => { const target = ONE_ETHER.times(0.01); const expectedError = new LibMathRevertErrors.DivisionByZeroError(); return expect( - libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -226,7 +225,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -248,7 +247,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = safeGetPartialAmountCeil(numerator, denominator, target); - const actual = await libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -257,7 +256,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.times(1.8); const target = ONE_ETHER; const expected = ONE_ETHER.dividedToIntegerBy(3).plus(1); - const actual = await libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(); expect(actual).to.bignumber.eq(expected); }); @@ -267,7 +266,7 @@ blockchainTests('LibMath', env => { const target = new BigNumber(333); const expectedError = new LibMathRevertErrors.RoundingError(numerator, denominator, target); return expect( - libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -277,7 +276,7 @@ blockchainTests('LibMath', env => { const target = ONE_ETHER.times(0.01); const expectedError = new LibMathRevertErrors.DivisionByZeroError(); return expect( - libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -291,7 +290,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -313,7 +312,7 @@ blockchainTests('LibMath', env => { const denominator = new BigNumber(102); const target = new BigNumber(52); // tslint:disable-next-line: boolean-naming - const actual = await libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(); expect(actual).to.eq(true); }); @@ -322,7 +321,7 @@ blockchainTests('LibMath', env => { const denominator = new BigNumber(101); const target = new BigNumber(92); // tslint:disable-next-line: boolean-naming - const actual = await libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(); expect(actual).to.eq(false); }); @@ -333,7 +332,7 @@ blockchainTests('LibMath', env => { // tslint:disable-next-line: boolean-naming const expected = isRoundingErrorFloor(numerator, denominator, target); // tslint:disable-next-line: boolean-naming - const actual = await libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target); + const actual = await libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(); expect(actual).to.eq(expected); }); @@ -343,7 +342,7 @@ blockchainTests('LibMath', env => { const target = ONE_ETHER.times(0.01); const expectedError = new LibMathRevertErrors.DivisionByZeroError(); return expect( - libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target), + libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -357,7 +356,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target), + libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -379,7 +378,7 @@ blockchainTests('LibMath', env => { const denominator = new BigNumber(101); const target = new BigNumber(92); // tslint:disable-next-line: boolean-naming - const actual = await libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(); expect(actual).to.eq(true); }); @@ -388,7 +387,7 @@ blockchainTests('LibMath', env => { const denominator = new BigNumber(102); const target = new BigNumber(52); // tslint:disable-next-line: boolean-naming - const actual = await libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(); expect(actual).to.eq(false); }); @@ -399,7 +398,7 @@ blockchainTests('LibMath', env => { // tslint:disable-next-line: boolean-naming const expected = isRoundingErrorCeil(numerator, denominator, target); // tslint:disable-next-line: boolean-naming - const actual = await libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target); + const actual = await libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(); expect(actual).to.eq(expected); }); @@ -408,9 +407,9 @@ blockchainTests('LibMath', env => { const denominator = ZERO_AMOUNT; const target = ONE_ETHER.times(0.01); const expectedError = new LibMathRevertErrors.DivisionByZeroError(); - return expect(libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target)).to.revertWith( - expectedError, - ); + return expect( + libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(), + ).to.revertWith(expectedError); }); it('reverts if `numerator * target` overflows', async () => { @@ -422,9 +421,9 @@ blockchainTests('LibMath', env => { numerator, target, ); - return expect(libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target)).to.revertWith( - expectedError, - ); + return expect( + libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(), + ).to.revertWith(expectedError); }); }); }); diff --git a/contracts/exchange-libs/test/lib_order.ts b/contracts/exchange-libs/test/lib_order.ts index dac5b7e1cf..65cdc289dd 100644 --- a/contracts/exchange-libs/test/lib_order.ts +++ b/contracts/exchange-libs/test/lib_order.ts @@ -58,7 +58,7 @@ blockchainTests('LibOrder', env => { version: constants.EIP712_DOMAIN_VERSION, }), ); - const actualHash = await libOrderContract.getTypedDataHash.callAsync(order, domainHash); + const actualHash = await libOrderContract.getTypedDataHash(order, domainHash).callAsync(); expect(actualHash).to.be.eq(expectedHash); } @@ -108,8 +108,8 @@ blockchainTests('LibOrder', env => { chainId: 1337, }), ); - const orderHashHex1 = await libOrderContract.getTypedDataHash.callAsync(EMPTY_ORDER, domainHash1); - const orderHashHex2 = await libOrderContract.getTypedDataHash.callAsync(EMPTY_ORDER, domainHash2); + const orderHashHex1 = await libOrderContract.getTypedDataHash(EMPTY_ORDER, domainHash1).callAsync(); + const orderHashHex2 = await libOrderContract.getTypedDataHash(EMPTY_ORDER, domainHash2).callAsync(); expect(orderHashHex1).to.be.not.equal(orderHashHex2); }); }); @@ -120,7 +120,7 @@ blockchainTests('LibOrder', env => { async function testGetStructHashAsync(order: Order): Promise { const typedData = eip712Utils.createOrderTypedData(order); const expectedHash = ethUtil.bufferToHex(signTypedDataUtils.generateTypedDataHashWithoutDomain(typedData)); - const actualHash = await libOrderContract.getStructHash.callAsync(order); + const actualHash = await libOrderContract.getStructHash(order).callAsync(); expect(actualHash).to.be.eq(expectedHash); } diff --git a/contracts/exchange-libs/test/lib_zero_ex_transaction.ts b/contracts/exchange-libs/test/lib_zero_ex_transaction.ts index 1c4b9c8d17..828497a629 100644 --- a/contracts/exchange-libs/test/lib_zero_ex_transaction.ts +++ b/contracts/exchange-libs/test/lib_zero_ex_transaction.ts @@ -50,7 +50,7 @@ blockchainTests('LibZeroExTransaction', env => { version: constants.EIP712_DOMAIN_VERSION, }), ); - const actualHash = await libZeroExTransactionContract.getTypedDataHash.callAsync(transaction, domainHash); + const actualHash = await libZeroExTransactionContract.getTypedDataHash(transaction, domainHash).callAsync(); expect(actualHash).to.be.eq(expectedHash); } @@ -94,14 +94,12 @@ blockchainTests('LibZeroExTransaction', env => { chainId: 1337, }), ); - const transactionHashHex1 = await libZeroExTransactionContract.getTypedDataHash.callAsync( - EMPTY_TRANSACTION, - domainHash1, - ); - const transactionHashHex2 = await libZeroExTransactionContract.getTypedDataHash.callAsync( - EMPTY_TRANSACTION, - domainHash2, - ); + const transactionHashHex1 = await libZeroExTransactionContract + .getTypedDataHash(EMPTY_TRANSACTION, domainHash1) + .callAsync(); + const transactionHashHex2 = await libZeroExTransactionContract + .getTypedDataHash(EMPTY_TRANSACTION, domainHash2) + .callAsync(); expect(transactionHashHex1).to.be.not.equal(transactionHashHex2); }); }); @@ -112,7 +110,7 @@ blockchainTests('LibZeroExTransaction', env => { async function testGetStructHashAsync(transaction: ZeroExTransaction): Promise { const typedData = eip712Utils.createZeroExTransactionTypedData(transaction); const expectedHash = ethUtil.bufferToHex(signTypedDataUtils.generateTypedDataHashWithoutDomain(typedData)); - const actualHash = await libZeroExTransactionContract.getStructHash.callAsync(transaction); + const actualHash = await libZeroExTransactionContract.getStructHash(transaction).callAsync(); expect(actualHash).to.be.eq(expectedHash); } diff --git a/contracts/exchange/src/balance_stores/blockchain_balance_store.ts b/contracts/exchange/src/balance_stores/blockchain_balance_store.ts index a7f4748dc4..cd31207578 100644 --- a/contracts/exchange/src/balance_stores/blockchain_balance_store.ts +++ b/contracts/exchange/src/balance_stores/blockchain_balance_store.ts @@ -64,7 +64,7 @@ export class BlockchainBalanceStore extends BalanceStore { this._ownerAddresses.map(async account => _.zipObject( this._tokenContracts.erc20.map(token => token.address), - await Promise.all(this._tokenContracts.erc20.map(token => token.balanceOf.callAsync(account))), + await Promise.all(this._tokenContracts.erc20.map(token => token.balanceOf(account).callAsync())), ), ), ); @@ -83,7 +83,7 @@ export class BlockchainBalanceStore extends BalanceStore { this.balances.erc721 = {}; for (const [tokenAddress, tokenIds] of Object.entries(this._tokenIds.erc721)) { for (const tokenId of tokenIds) { - const tokenOwner = await erc721ContractsByAddress[tokenAddress].ownerOf.callAsync(tokenId); + const tokenOwner = await erc721ContractsByAddress[tokenAddress].ownerOf(tokenId).callAsync(); _.update(this.balances.erc721, [tokenOwner, tokenAddress], nfts => _.union([tokenId], nfts).sort()); } } @@ -108,10 +108,9 @@ export class BlockchainBalanceStore extends BalanceStore { const [_tokenIds, _tokenOwners] = _.unzip( combinatorics.cartesianProduct(tokenIds, this._ownerAddresses).toArray(), ); - const balances = await contract.balanceOfBatch.callAsync( - _tokenOwners as string[], - _tokenIds as BigNumber[], - ); + const balances = await contract + .balanceOfBatch(_tokenOwners as string[], _tokenIds as BigNumber[]) + .callAsync(); let i = 0; for (const tokenOwner of this._ownerAddresses) { diff --git a/contracts/exchange/src/balance_stores/local_balance_store.ts b/contracts/exchange/src/balance_stores/local_balance_store.ts index 0c80f3930a..ed2a357e07 100644 --- a/contracts/exchange/src/balance_stores/local_balance_store.ts +++ b/contracts/exchange/src/balance_stores/local_balance_store.ts @@ -81,11 +81,11 @@ export class LocalBalanceStore extends BalanceStore { if (fromAddress === toAddress) { return; } - const assetProxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const assetProxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (assetProxyId) { case AssetProxyId.ERC20: { // tslint:disable-next-line:no-unused-variable - const [_proxyId, tokenAddress] = await this._devUtils.decodeERC20AssetData.callAsync(assetData); + const [_proxyId, tokenAddress] = await this._devUtils.decodeERC20AssetData(assetData).callAsync(); _.update(this.balances.erc20, [fromAddress, tokenAddress], balance => balance.minus(amount)); _.update(this.balances.erc20, [toAddress, tokenAddress], balance => (balance || constants.ZERO_AMOUNT).plus(amount), @@ -94,9 +94,9 @@ export class LocalBalanceStore extends BalanceStore { } case AssetProxyId.ERC721: { // tslint:disable-next-line:no-unused-variable - const [_proxyId, tokenAddress, tokenId] = await this._devUtils.decodeERC721AssetData.callAsync( - assetData, - ); + const [_proxyId, tokenAddress, tokenId] = await this._devUtils + .decodeERC721AssetData(assetData) + .callAsync(); const fromTokens = _.get(this.balances.erc721, [fromAddress, tokenAddress], []); const toTokens = _.get(this.balances.erc721, [toAddress, tokenAddress], []); if (amount.gte(1)) { @@ -117,7 +117,7 @@ export class LocalBalanceStore extends BalanceStore { tokenAddress, tokenIds, tokenValues, - ] = await this._devUtils.decodeERC1155AssetData.callAsync(assetData); + ] = await this._devUtils.decodeERC1155AssetData(assetData).callAsync(); const fromBalances = { // tslint:disable-next-line:no-inferred-empty-object-type fungible: _.get(this.balances.erc1155, [fromAddress, tokenAddress, 'fungible'], {}), @@ -155,9 +155,9 @@ export class LocalBalanceStore extends BalanceStore { } case AssetProxyId.MultiAsset: { // tslint:disable-next-line:no-unused-variable - const [_proxyId, amounts, nestedAssetData] = await this._devUtils.decodeMultiAssetData.callAsync( - assetData, - ); + const [_proxyId, amounts, nestedAssetData] = await this._devUtils + .decodeMultiAssetData(assetData) + .callAsync(); for (const [i, amt] of amounts.entries()) { const nestedAmount = amount.times(amt); await this.transferAssetAsync(fromAddress, toAddress, nestedAmount, nestedAssetData[i]); diff --git a/contracts/exchange/src/exchange_data_encoder.ts b/contracts/exchange/src/exchange_data_encoder.ts index 24022757fb..06830bf8fe 100644 --- a/contracts/exchange/src/exchange_data_encoder.ts +++ b/contracts/exchange/src/exchange_data_encoder.ts @@ -9,44 +9,38 @@ export const exchangeDataEncoder = { const exchangeInstance = new IExchangeContract(constants.NULL_ADDRESS, provider); let data; if (constants.SINGLE_FILL_FN_NAMES.indexOf(fnName) !== -1) { - data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData( - orders[0], - orders[0].takerAssetAmount, - orders[0].signature, - ); + data = (exchangeInstance as any) + [fnName](orders[0], orders[0].takerAssetAmount, orders[0].signature) + .getABIEncodedTransactionData(); } else if (constants.BATCH_FILL_FN_NAMES.indexOf(fnName) !== -1) { - data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData( - orders, - orders.map(order => order.takerAssetAmount), - orders.map(order => order.signature), - ); + data = (exchangeInstance as any) + [fnName](orders, orders.map(order => order.takerAssetAmount), orders.map(order => order.signature)) + .getABIEncodedTransactionData(); } else if (constants.MARKET_FILL_FN_NAMES.indexOf(fnName) !== -1) { const fillAsset = /Buy/.test(fnName) ? 'makerAssetAmount' : 'takerAssetAmount'; - data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData( - orders, - orders.map(order => order[fillAsset]).reduce((prev, curr) => prev.plus(curr)), - orders.map(order => order.signature), - ); + data = (exchangeInstance as any) + [fnName]( + orders, + orders.map(order => order[fillAsset]).reduce((prev, curr) => prev.plus(curr)), + orders.map(order => order.signature), + ) + .getABIEncodedTransactionData(); } else if (constants.MATCH_ORDER_FN_NAMES.indexOf(fnName) !== -1) { - data = exchangeInstance.matchOrders.getABIEncodedTransactionData( - orders[0], - orders[1], - orders[0].signature, - orders[1].signature, - ); + data = exchangeInstance + .matchOrders(orders[0], orders[1], orders[0].signature, orders[1].signature) + .getABIEncodedTransactionData(); } else if (fnName === ExchangeFunctionName.CancelOrder) { - data = exchangeInstance.cancelOrder.getABIEncodedTransactionData(orders[0]); + data = exchangeInstance.cancelOrder(orders[0]).getABIEncodedTransactionData(); } else if (fnName === ExchangeFunctionName.BatchCancelOrders) { - data = exchangeInstance.batchCancelOrders.getABIEncodedTransactionData(orders); + data = exchangeInstance.batchCancelOrders(orders).getABIEncodedTransactionData(); } else if (fnName === ExchangeFunctionName.CancelOrdersUpTo) { - data = exchangeInstance.cancelOrdersUpTo.getABIEncodedTransactionData(constants.ZERO_AMOUNT); + data = exchangeInstance.cancelOrdersUpTo(constants.ZERO_AMOUNT).getABIEncodedTransactionData(); } else if (fnName === ExchangeFunctionName.PreSign) { - data = exchangeInstance.preSign.getABIEncodedTransactionData(orderHashUtils.getOrderHashHex(orders[0])); + data = exchangeInstance.preSign(orderHashUtils.getOrderHashHex(orders[0])).getABIEncodedTransactionData(); } else if (fnName === ExchangeFunctionName.SetSignatureValidatorApproval) { - data = exchangeInstance.setSignatureValidatorApproval.getABIEncodedTransactionData( - constants.NULL_ADDRESS, - true, - ); + data = exchangeInstance + .setSignatureValidatorApproval(constants.NULL_ADDRESS, true) + .getABIEncodedTransactionData(); } else { throw new Error(`Error: ${fnName} not a supported function`); } diff --git a/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts b/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts index c6df6a38ca..a5dc4cd6ad 100644 --- a/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts +++ b/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts @@ -154,9 +154,9 @@ export class FillOrderWrapper { ): Promise { // Get init state await this._blockchainBalanceStore.updateBalancesAsync(); - const initTakerAssetFilledAmount = await this._exchange.filled.callAsync( - orderHashUtils.getOrderHashHex(signedOrder), - ); + const initTakerAssetFilledAmount = await this._exchange + .filled(orderHashUtils.getOrderHashHex(signedOrder)) + .callAsync(); // Assert init state of exchange await this._assertOrderStateAsync(signedOrder, initTakerAssetFilledAmount); // Simulate and execute fill then assert outputs @@ -187,18 +187,12 @@ export class FillOrderWrapper { opts: { takerAssetFillAmount?: BigNumber } = {}, ): Promise<[FillResults, FillEventArgs, TransactionReceiptWithDecodedLogs]> { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const fillResults = await this._exchange.fillOrder.callAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from }, - ); - const txReceipt = await this._exchange.fillOrder.awaitTransactionSuccessAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from }, - ); + const fillResults = await this._exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .callAsync({ from }); + const txReceipt = await this._exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .awaitTransactionSuccessAsync({ from }); const fillEvent = FillOrderWrapper._extractFillEventsfromReceipt(txReceipt)[0]; return [fillResults, fillEvent, txReceipt]; } @@ -213,7 +207,7 @@ export class FillOrderWrapper { order: SignedOrder, expectedFilledAmount: BigNumber = new BigNumber(0), ): Promise { - const orderInfo = await this._exchange.getOrderInfo.callAsync(order); + const orderInfo = await this._exchange.getOrderInfo(order).callAsync(); // Check filled amount of order. const actualFilledAmount = orderInfo.orderTakerAssetFilledAmount; expect(actualFilledAmount, 'order filled amount').to.be.bignumber.equal(expectedFilledAmount); diff --git a/contracts/exchange/test/core.ts b/contracts/exchange/test/core.ts index c8059fa765..743d415fcf 100644 --- a/contracts/exchange/test/core.ts +++ b/contracts/exchange/test/core.ts @@ -152,22 +152,22 @@ blockchainTests.resets('Exchange core', () => { exchange.address, ); // Configure ERC20Proxy - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner }); + await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure ERC721Proxy - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner }); + await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure ERC1155Proxy - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner }); + await erc1155Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure MultiAssetProxy - await multiAssetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { from: owner }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { from: owner }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(staticCallProxy.address, { from: owner }); + await multiAssetProxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxy.registerAssetProxy(staticCallProxy.address).awaitTransactionSuccessAsync({ from: owner }); // Configure Exchange exchangeWrapper = new ExchangeWrapper(exchange); @@ -211,10 +211,10 @@ blockchainTests.resets('Exchange core', () => { ...constants.STATIC_ORDER_PARAMS, makerAddress, feeRecipientAddress, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeAssetAddress), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeAssetAddress).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeAssetAddress).callAsync(), exchangeAddress: exchange.address, chainId, }; @@ -252,24 +252,19 @@ blockchainTests.resets('Exchange core', () => { describe('callback signature types', () => { beforeEach(async () => { // Approve the ERC20 proxy with the test validator wallet. - await validatorWallet.approveERC20.awaitTransactionSuccessAsync( - erc20TokenA.address, - erc20Proxy.address, - constants.INITIAL_ERC20_ALLOWANCE, - ); + await validatorWallet + .approveERC20(erc20TokenA.address, erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync(); // Mint some ERC20 tokens to the test validator wallet. - await erc20TokenA.setBalance.awaitTransactionSuccessAsync( - validatorWallet.address, - constants.INITIAL_ERC20_BALANCE, - ); + await erc20TokenA + .setBalance(validatorWallet.address, constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync(); // Approve the validator. - await exchange.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - true, - { + await exchange + .setSignatureValidatorApproval(validatorWallet.address, true) + .awaitTransactionSuccessAsync({ from: makerAddress, - }, - ); + }); signedOrder = await orderFactory.newSignedOrderAsync({ makerFee: constants.ZERO_AMOUNT, takerFee: constants.ZERO_AMOUNT, @@ -281,19 +276,15 @@ blockchainTests.resets('Exchange core', () => { signedOrder.signature = signatureHex; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Allow the signature check for the first fill. - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - ValidatorWalletAction.Accept, - constants.NULL_BYTES, - ); + await validatorWallet + .prepare(orderHashHex, ValidatorWalletAction.Accept, constants.NULL_BYTES) + .awaitTransactionSuccessAsync(); const fillAmount = signedOrder.takerAssetAmount.div(10); await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount }); // Reject the signature check for the second fill. - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - ValidatorWalletAction.Reject, - constants.NULL_BYTES, - ); + await validatorWallet + .prepare(orderHashHex, ValidatorWalletAction.Reject, constants.NULL_BYTES) + .awaitTransactionSuccessAsync(); const tx = exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount, }); @@ -312,19 +303,15 @@ blockchainTests.resets('Exchange core', () => { signedOrder.signature = signatureHex; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Allow the signature check for the first fill. - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - ValidatorWalletAction.Accept, - constants.NULL_BYTES, - ); + await validatorWallet + .prepare(orderHashHex, ValidatorWalletAction.Accept, constants.NULL_BYTES) + .awaitTransactionSuccessAsync(); const fillAmount = signedOrder.takerAssetAmount.div(10); await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount }); // Reject the signature check for the second fill. - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - ValidatorWalletAction.Reject, - constants.NULL_BYTES, - ); + await validatorWallet + .prepare(orderHashHex, ValidatorWalletAction.Reject, constants.NULL_BYTES) + .awaitTransactionSuccessAsync(); const tx = exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount, }); @@ -343,19 +330,15 @@ blockchainTests.resets('Exchange core', () => { signedOrder.signature = signatureHex; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Allow the signature check for the first fill. - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - ValidatorWalletAction.Accept, - constants.NULL_BYTES, - ); + await validatorWallet + .prepare(orderHashHex, ValidatorWalletAction.Accept, constants.NULL_BYTES) + .awaitTransactionSuccessAsync(); const fillAmount = signedOrder.takerAssetAmount.div(10); await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount }); // Reject the signature check for the second fill. - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - ValidatorWalletAction.Reject, - constants.NULL_BYTES, - ); + await validatorWallet + .prepare(orderHashHex, ValidatorWalletAction.Reject, constants.NULL_BYTES) + .awaitTransactionSuccessAsync(); const tx = exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount, }); @@ -420,9 +403,11 @@ blockchainTests.resets('Exchange core', () => { describe('Fill transfer ordering', () => { it('should allow the maker to exchange assets received by the taker', async () => { // Set maker/taker assetData to the same asset - const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const takerAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const takerAssetAmount = new BigNumber(1); - const makerAssetData = await devUtils.encodeMultiAssetData.callAsync([takerAssetAmount], [takerAssetData]); + const makerAssetData = await devUtils + .encodeMultiAssetData([takerAssetAmount], [takerAssetData]) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, takerAssetData, @@ -432,33 +417,33 @@ blockchainTests.resets('Exchange core', () => { takerFee: constants.ZERO_AMOUNT, }); // Set maker balance to 0 so that the asset must be received by the taker in order for the fill to succeed - await erc20TokenA.setBalance.awaitTransactionSuccessAsync(makerAddress, constants.ZERO_AMOUNT, { + await erc20TokenA.setBalance(makerAddress, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({ from: owner, }); await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress); }); it('should allow the taker to pay fees with an asset that received by the maker', async () => { - const makerAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const makerAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ takerFeeAssetData: makerAssetData, makerFee: constants.ZERO_AMOUNT, takerFee: new BigNumber(1), }); // Set taker balance to 0 so that the asset must be received by the maker in order for the fill to succeed - await erc20TokenA.setBalance.awaitTransactionSuccessAsync(takerAddress, constants.ZERO_AMOUNT, { + await erc20TokenA.setBalance(takerAddress, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({ from: owner, }); await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress); }); it('should allow the maker to pay fees with an asset that received by the taker', async () => { - const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); + const takerAssetData = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerFeeAssetData: takerAssetData, makerFee: new BigNumber(1), takerFee: constants.ZERO_AMOUNT, }); // Set maker balance to 0 so that the asset must be received by the taker in order for the fill to succeed - await erc20TokenB.setBalance.awaitTransactionSuccessAsync(makerAddress, constants.ZERO_AMOUNT, { + await erc20TokenB.setBalance(makerAddress, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({ from: owner, }); await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress); @@ -466,19 +451,16 @@ blockchainTests.resets('Exchange core', () => { }); describe('Testing exchange of ERC20 tokens with no return values', () => { before(async () => { - await noReturnErc20Token.setBalance.awaitTransactionSuccessAsync( - makerAddress, - constants.INITIAL_ERC20_BALANCE, - ); - await noReturnErc20Token.approve.awaitTransactionSuccessAsync( - erc20Proxy.address, - constants.INITIAL_ERC20_ALLOWANCE, - { from: makerAddress }, - ); + await noReturnErc20Token + .setBalance(makerAddress, constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync(); + await noReturnErc20Token + .approve(erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync({ from: makerAddress }); }); it('should transfer the correct amounts when makerAssetAmount === takerAssetAmount', async () => { signedOrder = await orderFactory.newSignedOrderAsync({ - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address), + makerAssetData: await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18), }); @@ -486,7 +468,7 @@ blockchainTests.resets('Exchange core', () => { }); it('should transfer the correct amounts when makerAssetAmount > takerAssetAmount', async () => { signedOrder = await orderFactory.newSignedOrderAsync({ - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address), + makerAssetData: await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18), }); @@ -494,7 +476,7 @@ blockchainTests.resets('Exchange core', () => { }); it('should transfer the correct amounts when makerAssetAmount < takerAssetAmount', async () => { signedOrder = await orderFactory.newSignedOrderAsync({ - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address), + makerAssetData: await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), 18), }); @@ -671,14 +653,14 @@ blockchainTests.resets('Exchange core', () => { signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetAmount: new BigNumber(1), takerAssetAmount: new BigNumber(1), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId), - takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(), + takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(), }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Verify pre-conditions - const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync(); expect(initialOwnerMakerAsset).to.be.bignumber.not.equal(makerAddress); - const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId); + const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync(); expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; @@ -698,14 +680,14 @@ blockchainTests.resets('Exchange core', () => { signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetAmount: new BigNumber(1), takerAssetAmount: new BigNumber(1), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId), - takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(), + takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(), }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Verify pre-conditions - const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync(); expect(initialOwnerMakerAsset).to.be.bignumber.equal(makerAddress); - const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId); + const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync(); expect(initialOwnerTakerAsset).to.be.bignumber.not.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; @@ -725,14 +707,14 @@ blockchainTests.resets('Exchange core', () => { signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetAmount: new BigNumber(2), takerAssetAmount: new BigNumber(1), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId), - takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(), + takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(), }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Verify pre-conditions - const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync(); expect(initialOwnerMakerAsset).to.be.bignumber.equal(makerAddress); - const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId); + const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync(); expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; @@ -752,14 +734,14 @@ blockchainTests.resets('Exchange core', () => { signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetAmount: new BigNumber(1), takerAssetAmount: new BigNumber(500), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId), - takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(), + takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(), }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); // Verify pre-conditions - const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId); + const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync(); expect(initialOwnerMakerAsset).to.be.bignumber.equal(makerAddress); - const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId); + const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync(); expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount; @@ -778,8 +760,8 @@ blockchainTests.resets('Exchange core', () => { signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetAmount: new BigNumber(1), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(), }); // Call Exchange const takerAssetFillAmount = signedOrder.takerAssetAmount.div(2); @@ -797,12 +779,12 @@ blockchainTests.resets('Exchange core', () => { it('should allow multiple assets to be exchanged for a single asset', async () => { const makerAmounts = [new BigNumber(10), new BigNumber(20)]; const makerNestedAssetData = [ - await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address), - await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address), + await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(), + await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(), ]; - const makerAssetData = await devUtils.encodeMultiAssetData.callAsync(makerAmounts, makerNestedAssetData); + const makerAssetData = await devUtils.encodeMultiAssetData(makerAmounts, makerNestedAssetData).callAsync(); const makerAssetAmount = new BigNumber(1); - const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(feeToken.address); + const takerAssetData = await devUtils.encodeERC20AssetData(feeToken.address).callAsync(); const takerAssetAmount = new BigNumber(10); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, @@ -817,18 +799,18 @@ blockchainTests.resets('Exchange core', () => { it('should allow multiple assets to be exchanged for multiple assets', async () => { const makerAmounts = [new BigNumber(10), new BigNumber(20)]; const makerNestedAssetData = [ - await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address), - await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address), + await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(), + await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(), ]; - const makerAssetData = await devUtils.encodeMultiAssetData.callAsync(makerAmounts, makerNestedAssetData); + const makerAssetData = await devUtils.encodeMultiAssetData(makerAmounts, makerNestedAssetData).callAsync(); const makerAssetAmount = new BigNumber(1); const takerAmounts = [new BigNumber(10), new BigNumber(1)]; const takerAssetId = erc721TakerAssetIds[0]; const takerNestedAssetData = [ - await devUtils.encodeERC20AssetData.callAsync(feeToken.address), - await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId), + await devUtils.encodeERC20AssetData(feeToken.address).callAsync(), + await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(), ]; - const takerAssetData = await devUtils.encodeMultiAssetData.callAsync(takerAmounts, takerNestedAssetData); + const takerAssetData = await devUtils.encodeMultiAssetData(takerAmounts, takerNestedAssetData).callAsync(); const takerAssetAmount = new BigNumber(1); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, @@ -843,12 +825,12 @@ blockchainTests.resets('Exchange core', () => { it('should allow an order selling multiple assets to be partially filled', async () => { const makerAmounts = [new BigNumber(10), new BigNumber(20)]; const makerNestedAssetData = [ - await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address), - await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address), + await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(), + await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(), ]; - const makerAssetData = await devUtils.encodeMultiAssetData.callAsync(makerAmounts, makerNestedAssetData); + const makerAssetData = await devUtils.encodeMultiAssetData(makerAmounts, makerNestedAssetData).callAsync(); const makerAssetAmount = new BigNumber(30); - const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(feeToken.address); + const takerAssetData = await devUtils.encodeERC20AssetData(feeToken.address).callAsync(); const takerAssetAmount = new BigNumber(10); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, @@ -865,12 +847,12 @@ blockchainTests.resets('Exchange core', () => { it('should allow an order buying multiple assets to be partially filled', async () => { const takerAmounts = [new BigNumber(10), new BigNumber(20)]; const takerNestedAssetData = [ - await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address), - await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address), + await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(), + await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(), ]; - const takerAssetData = await devUtils.encodeMultiAssetData.callAsync(takerAmounts, takerNestedAssetData); + const takerAssetData = await devUtils.encodeMultiAssetData(takerAmounts, takerNestedAssetData).callAsync(); const takerAssetAmount = new BigNumber(30); - const makerAssetData = await devUtils.encodeERC20AssetData.callAsync(feeToken.address); + const makerAssetData = await devUtils.encodeERC20AssetData(feeToken.address).callAsync(); const makerAssetAmount = new BigNumber(10); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, @@ -896,18 +878,22 @@ blockchainTests.resets('Exchange core', () => { const makerAssetAmount = new BigNumber(1); const takerAssetAmount = new BigNumber(1); const receiverCallbackData = '0x'; - const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - makerAssetsToTransfer, - makerValuesToTransfer, - receiverCallbackData, - ); - const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - takerAssetsToTransfer, - takerValuesToTransfer, - receiverCallbackData, - ); + const makerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + makerAssetsToTransfer, + makerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); + const takerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + takerAssetsToTransfer, + takerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, takerAssetData, @@ -931,18 +917,22 @@ blockchainTests.resets('Exchange core', () => { const makerAssetAmount = new BigNumber(1); const takerAssetAmount = new BigNumber(1); const receiverCallbackData = '0x'; - const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - makerAssetsToTransfer, - makerValuesToTransfer, - receiverCallbackData, - ); - const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - takerAssetsToTransfer, - takerValuesToTransfer, - receiverCallbackData, - ); + const makerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + makerAssetsToTransfer, + makerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); + const takerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + takerAssetsToTransfer, + takerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, takerAssetData, @@ -965,18 +955,22 @@ blockchainTests.resets('Exchange core', () => { const makerAssetAmount = new BigNumber(1); const takerAssetAmount = new BigNumber(1); const receiverCallbackData = '0x'; - const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - makerAssetsToTransfer, - makerValuesToTransfer, - receiverCallbackData, - ); - const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - takerAssetsToTransfer, - takerValuesToTransfer, - receiverCallbackData, - ); + const makerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + makerAssetsToTransfer, + makerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); + const takerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + takerAssetsToTransfer, + takerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, takerAssetData, @@ -1005,18 +999,22 @@ blockchainTests.resets('Exchange core', () => { const makerAssetAmount = new BigNumber(1); const takerAssetAmount = new BigNumber(1); const receiverCallbackData = '0x'; - const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - makerAssetsToTransfer, - makerValuesToTransfer, - receiverCallbackData, - ); - const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - takerAssetsToTransfer, - takerValuesToTransfer, - receiverCallbackData, - ); + const makerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + makerAssetsToTransfer, + makerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); + const takerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + takerAssetsToTransfer, + takerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, takerAssetData, @@ -1050,18 +1048,22 @@ blockchainTests.resets('Exchange core', () => { const makerAssetAmount = new BigNumber(10); const takerAssetAmount = new BigNumber(20); const receiverCallbackData = '0x'; - const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - makerAssetsToTransfer, - makerValuesToTransfer, - receiverCallbackData, - ); - const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync( - erc1155Contract.address, - takerAssetsToTransfer, - takerValuesToTransfer, - receiverCallbackData, - ); + const makerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + makerAssetsToTransfer, + makerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); + const takerAssetData = await devUtils + .encodeERC1155AssetData( + erc1155Contract.address, + takerAssetsToTransfer, + takerValuesToTransfer, + receiverCallbackData, + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData, takerAssetData, @@ -1086,12 +1088,10 @@ blockchainTests.resets('Exchange core', () => { ); }); it('should revert if the staticcall is unsuccessful', async () => { - const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1)); - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - constants.KECCAK256_NULL, - ); + const staticCallData = staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData(); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); const expectedError = new ExchangeRevertErrors.AssetProxyTransferError( @@ -1103,28 +1103,26 @@ blockchainTests.resets('Exchange core', () => { return expect(tx).to.revertWith(expectedError); }); it('should fill the order if the staticcall is successful', async () => { - const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData( - constants.ZERO_AMOUNT, - ); - const assetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - constants.KECCAK256_NULL, - ); + const staticCallData = staticCallTarget + .assertEvenNumber(constants.ZERO_AMOUNT) + .getABIEncodedTransactionData(); + const assetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData }); await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress); }); it('should revert if the staticcall is unsuccessful using the MultiAssetProxy', async () => { - const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1)); - const staticCallAssetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - constants.KECCAK256_NULL, - ); - const assetData = await devUtils.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), staticCallAssetData], - ); + const staticCallData = staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData(); + const staticCallAssetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL) + .callAsync(); + const assetData = await devUtils + .encodeMultiAssetData( + [new BigNumber(1), new BigNumber(1)], + [await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), staticCallAssetData], + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); const expectedError = new ExchangeRevertErrors.AssetProxyTransferError( @@ -1136,18 +1134,18 @@ blockchainTests.resets('Exchange core', () => { return expect(tx).to.revertWith(expectedError); }); it('should fill the order is the staticcall is successful using the MultiAssetProxy', async () => { - const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData( - constants.ZERO_AMOUNT, - ); - const staticCallAssetData = await devUtils.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - constants.KECCAK256_NULL, - ); - const assetData = await devUtils.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), staticCallAssetData], - ); + const staticCallData = staticCallTarget + .assertEvenNumber(constants.ZERO_AMOUNT) + .getABIEncodedTransactionData(); + const staticCallAssetData = await devUtils + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL) + .callAsync(); + const assetData = await devUtils + .encodeMultiAssetData( + [new BigNumber(1), new BigNumber(1)], + [await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), staticCallAssetData], + ) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData }); await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress); }); diff --git a/contracts/exchange/test/dispatcher.ts b/contracts/exchange/test/dispatcher.ts index e26a28ae54..51fd67329a 100644 --- a/contracts/exchange/test/dispatcher.ts +++ b/contracts/exchange/test/dispatcher.ts @@ -79,10 +79,10 @@ describe('AssetProxyDispatcher', () => { txDefaults, dependencyArtifacts, ); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(assetProxyDispatcher.address, { + await erc20Proxy.addAuthorizedAddress(assetProxyDispatcher.address).awaitTransactionSuccessAsync({ from: owner, }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(assetProxyDispatcher.address, { + await erc721Proxy.addAuthorizedAddress(assetProxyDispatcher.address).awaitTransactionSuccessAsync({ from: owner, }); }); @@ -94,34 +94,34 @@ describe('AssetProxyDispatcher', () => { }); describe('registerAssetProxy', () => { it('should record proxy upon registration', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20); + const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync(); expect(proxyAddress).to.be.equal(erc20Proxy.address); }); it('should be able to record multiple proxies', async () => { // Record first proxy - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - let proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20); + let proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync(); expect(proxyAddress).to.be.equal(erc20Proxy.address); // Record another proxy - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC721); + proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC721).callAsync(); expect(proxyAddress).to.be.equal(erc721Proxy.address); }); it('should revert if a proxy with the same id is already registered', async () => { // Initial registration - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20); + const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync(); expect(proxyAddress).to.be.equal(erc20Proxy.address); // Deploy a new version of the ERC20 Transfer Proxy contract const newErc20TransferProxy = await ERC20ProxyContract.deployFrom0xArtifactAsync( @@ -131,7 +131,7 @@ describe('AssetProxyDispatcher', () => { dependencyArtifacts, ); const expectedError = new ExchangeRevertErrors.AssetProxyExistsError(AssetProxyId.ERC20, proxyAddress); - const tx = assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(newErc20TransferProxy.address, { + const tx = assetProxyDispatcher.registerAssetProxy(newErc20TransferProxy.address).sendTransactionAsync({ from: owner, }); return expect(tx).to.revertWith(expectedError); @@ -139,7 +139,7 @@ describe('AssetProxyDispatcher', () => { it('should revert if requesting address is not owner', async () => { const expectedError = new OwnableRevertErrors.OnlyOwnerError(notOwner, owner); - const tx = assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, { + const tx = assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).sendTransactionAsync({ from: notOwner, }); return expect(tx).to.revertWith(expectedError); @@ -147,7 +147,7 @@ describe('AssetProxyDispatcher', () => { it('should revert if the proxy is not a contract address', async () => { const errMessage = 'VM Exception while processing transaction: revert'; - const tx = assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(notOwner, { + const tx = assetProxyDispatcher.registerAssetProxy(notOwner).sendTransactionAsync({ from: owner, }); return expect(tx).to.be.rejectedWith(errMessage); @@ -156,7 +156,7 @@ describe('AssetProxyDispatcher', () => { it('should log an event with correct arguments when an asset proxy is registered', async () => { const logDecoder = new LogDecoder(web3Wrapper, artifacts); const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).sendTransactionAsync({ from: owner, }), ); @@ -169,15 +169,15 @@ describe('AssetProxyDispatcher', () => { describe('getAssetProxy', () => { it('should return correct address of registered proxy', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20); + const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync(); expect(proxyAddress).to.be.equal(erc20Proxy.address); }); it('should return NULL address if requesting non-existent proxy', async () => { - const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20); + const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync(); expect(proxyAddress).to.be.equal(constants.NULL_ADDRESS); }); }); @@ -186,23 +186,18 @@ describe('AssetProxyDispatcher', () => { const orderHash = orderUtils.generatePseudoRandomOrderHash(); it('should dispatch transfer to registered proxy', async () => { // Register ERC20 proxy - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); // Construct metadata for ERC20 proxy - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Perform a transfer from makerAddress to takerAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = new BigNumber(10); - await assetProxyDispatcher.dispatchTransferFrom.awaitTransactionSuccessAsync( - orderHash, - encodedAssetData, - makerAddress, - takerAddress, - amount, - { from: owner }, - ); + await assetProxyDispatcher + .dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount) + .awaitTransactionSuccessAsync({ from: owner }); // Verify transfer was successful const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances[makerAddress][erc20TokenA.address]).to.be.bignumber.equal( @@ -215,23 +210,18 @@ describe('AssetProxyDispatcher', () => { it('should not dispatch a transfer if amount == 0', async () => { // Register ERC20 proxy - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); // Construct metadata for ERC20 proxy - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Perform a transfer from makerAddress to takerAddress const erc20Balances = await erc20Wrapper.getBalancesAsync(); const amount = constants.ZERO_AMOUNT; - const txReceipt = await assetProxyDispatcher.dispatchTransferFrom.awaitTransactionSuccessAsync( - orderHash, - encodedAssetData, - makerAddress, - takerAddress, - amount, - { from: owner }, - ); + const txReceipt = await assetProxyDispatcher + .dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount) + .awaitTransactionSuccessAsync({ from: owner }); expect(txReceipt.logs.length).to.be.equal(0); const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances).to.deep.equal(erc20Balances); @@ -239,7 +229,7 @@ describe('AssetProxyDispatcher', () => { it('should revert if dispatching to unregistered proxy', async () => { // Construct metadata for ERC20 proxy - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); // Perform a transfer from makerAddress to takerAddress const amount = new BigNumber(10); @@ -248,70 +238,58 @@ describe('AssetProxyDispatcher', () => { orderHash, encodedAssetData, ); - const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync( - orderHash, - encodedAssetData, - makerAddress, - takerAddress, - amount, - { from: owner }, - ); + const tx = assetProxyDispatcher + .dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount) + .sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); it('should revert with the correct error when assetData length < 4 bytes', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const encodedAssetData = (await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address)).slice(0, 8); + const encodedAssetData = (await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync()).slice(0, 8); const amount = new BigNumber(1); const expectedError = new ExchangeRevertErrors.AssetProxyDispatchError( ExchangeRevertErrors.AssetProxyDispatchErrorCode.InvalidAssetDataLength, orderHash, encodedAssetData, ); - const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync( - orderHash, - encodedAssetData, - makerAddress, - takerAddress, - amount, - { from: owner }, - ); + const tx = assetProxyDispatcher + .dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount) + .sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); it('should revert if assetData is not padded to 32 bytes (excluding the id)', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); // Shave off the last byte - const encodedAssetData = (await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address)).slice(0, 72); + const encodedAssetData = (await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync()).slice( + 0, + 72, + ); const amount = new BigNumber(1); const expectedError = new ExchangeRevertErrors.AssetProxyDispatchError( ExchangeRevertErrors.AssetProxyDispatchErrorCode.InvalidAssetDataLength, orderHash, encodedAssetData, ); - const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync( - orderHash, - encodedAssetData, - makerAddress, - takerAddress, - amount, - { from: owner }, - ); + const tx = assetProxyDispatcher + .dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount) + .sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); it('should revert with the reason provided by the AssetProxy when a transfer fails', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - await erc20TokenA.approve.awaitTransactionSuccessAsync(erc20Proxy.address, constants.ZERO_AMOUNT, { + await erc20TokenA.approve(erc20Proxy.address, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({ from: makerAddress, }); - const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); + const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); const amount = new BigNumber(1); const nestedError = new StringRevertError(RevertReason.TransferFailed).encode(); const expectedError = new ExchangeRevertErrors.AssetProxyTransferError( @@ -319,25 +297,20 @@ describe('AssetProxyDispatcher', () => { encodedAssetData, nestedError, ); - const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync( - orderHash, - encodedAssetData, - makerAddress, - takerAddress, - amount, - { from: owner }, - ); + const tx = assetProxyDispatcher + .dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount) + .sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); }); describe('simulateDispatchTransferFromCalls', () => { it('should revert with the information specific to the failed transfer', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const assetDataA = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const assetDataB = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); - await erc20TokenB.approve.awaitTransactionSuccessAsync(erc20Proxy.address, constants.ZERO_AMOUNT, { + const assetDataA = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const assetDataB = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); + await erc20TokenB.approve(erc20Proxy.address, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({ from: makerAddress, }); const transferIndexAsBytes32 = '0x0000000000000000000000000000000000000000000000000000000000000001'; @@ -347,59 +320,67 @@ describe('AssetProxyDispatcher', () => { assetDataB, nestedError, ); - const tx = assetProxyDispatcher.simulateDispatchTransferFromCalls.sendTransactionAsync( - [assetDataA, assetDataB], - [makerAddress, makerAddress], - [takerAddress, takerAddress], - [new BigNumber(1), new BigNumber(1)], - ); + const tx = assetProxyDispatcher + .simulateDispatchTransferFromCalls( + [assetDataA, assetDataB], + [makerAddress, makerAddress], + [takerAddress, takerAddress], + [new BigNumber(1), new BigNumber(1)], + ) + .sendTransactionAsync(); return expect(tx).to.revertWith(expectedError); }); it('should forward the revert reason from the underlying failed transfer', async () => { - const assetDataA = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const assetDataB = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); + const assetDataA = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const assetDataB = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); const transferIndexAsBytes32 = '0x0000000000000000000000000000000000000000000000000000000000000000'; const expectedError = new ExchangeRevertErrors.AssetProxyDispatchError( ExchangeRevertErrors.AssetProxyDispatchErrorCode.UnknownAssetProxy, transferIndexAsBytes32, assetDataA, ); - const tx = assetProxyDispatcher.simulateDispatchTransferFromCalls.sendTransactionAsync( - [assetDataA, assetDataB], - [makerAddress, makerAddress], - [takerAddress, takerAddress], - [new BigNumber(1), new BigNumber(1)], - ); + const tx = assetProxyDispatcher + .simulateDispatchTransferFromCalls( + [assetDataA, assetDataB], + [makerAddress, makerAddress], + [takerAddress, takerAddress], + [new BigNumber(1), new BigNumber(1)], + ) + .sendTransactionAsync(); return expect(tx).to.revertWith(expectedError); }); it('should revert with TRANSFERS_SUCCESSFUL if no transfers fail', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const assetDataA = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const assetDataB = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); - const tx = assetProxyDispatcher.simulateDispatchTransferFromCalls.sendTransactionAsync( - [assetDataA, assetDataB], - [makerAddress, makerAddress], - [takerAddress, takerAddress], - [new BigNumber(1), new BigNumber(1)], - ); + const assetDataA = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const assetDataB = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); + const tx = assetProxyDispatcher + .simulateDispatchTransferFromCalls( + [assetDataA, assetDataB], + [makerAddress, makerAddress], + [takerAddress, takerAddress], + [new BigNumber(1), new BigNumber(1)], + ) + .sendTransactionAsync(); return expect(tx).to.revertWith(RevertReason.TransfersSuccessful); }); it('should not modify balances if all transfers are successful', async () => { - await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - const assetDataA = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address); - const assetDataB = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address); + const assetDataA = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(); + const assetDataB = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(); const balances = await erc20Wrapper.getBalancesAsync(); try { - await assetProxyDispatcher.simulateDispatchTransferFromCalls.awaitTransactionSuccessAsync( - [assetDataA, assetDataB], - [makerAddress, makerAddress], - [takerAddress, takerAddress], - [new BigNumber(1), new BigNumber(1)], - ); + await assetProxyDispatcher + .simulateDispatchTransferFromCalls( + [assetDataA, assetDataB], + [makerAddress, makerAddress], + [takerAddress, takerAddress], + [new BigNumber(1), new BigNumber(1)], + ) + .awaitTransactionSuccessAsync(); } catch (err) { const newBalances = await erc20Wrapper.getBalancesAsync(); expect(newBalances).to.deep.equal(balances); diff --git a/contracts/exchange/test/exchange_transfer_simulator_test.ts b/contracts/exchange/test/exchange_transfer_simulator_test.ts index 1363047157..6c9359c232 100644 --- a/contracts/exchange/test/exchange_transfer_simulator_test.ts +++ b/contracts/exchange/test/exchange_transfer_simulator_test.ts @@ -25,7 +25,6 @@ blockchainTests('ExchangeTransferSimulator', env => { let recipient: string; let exampleAssetData: string; let exchangeTransferSimulator: ExchangeTransferSimulator; - let txHash: string; let erc20ProxyAddress: string; const devUtils = new DevUtilsContract(constants.NULL_ADDRESS, env.provider); before(async function(): Promise { @@ -65,7 +64,7 @@ blockchainTests('ExchangeTransferSimulator', env => { totalSupply, ); - exampleAssetData = await devUtils.encodeERC20AssetData.callAsync(dummyERC20Token.address); + exampleAssetData = await devUtils.encodeERC20AssetData(dummyERC20Token.address).callAsync(); }); beforeEach(async () => { await env.blockchainLifecycle.startAsync(); @@ -103,10 +102,9 @@ blockchainTests('ExchangeTransferSimulator', env => { ).to.be.rejectedWith(ExchangeContractErrs.InsufficientTakerAllowance); }); it("throws if the user doesn't have enough balance", async () => { - txHash = await dummyERC20Token.approve.sendTransactionAsync(erc20ProxyAddress, transferAmount, { + await dummyERC20Token.approve(erc20ProxyAddress, transferAmount).awaitTransactionSuccessAsync({ from: sender, }); - await env.web3Wrapper.awaitTransactionSuccessAsync(txHash); return expect( exchangeTransferSimulator.transferFromAsync( exampleAssetData, @@ -119,15 +117,12 @@ blockchainTests('ExchangeTransferSimulator', env => { ).to.be.rejectedWith(ExchangeContractErrs.InsufficientMakerBalance); }); it('updates balances and proxyAllowance after transfer', async () => { - txHash = await dummyERC20Token.transfer.sendTransactionAsync(sender, transferAmount, { + await dummyERC20Token.transfer(sender, transferAmount).awaitTransactionSuccessAsync({ from: coinbase, }); - await env.web3Wrapper.awaitTransactionSuccessAsync(txHash); - - txHash = await dummyERC20Token.approve.sendTransactionAsync(erc20ProxyAddress, transferAmount, { + await dummyERC20Token.approve(erc20ProxyAddress, transferAmount).awaitTransactionSuccessAsync({ from: sender, }); - await env.web3Wrapper.awaitTransactionSuccessAsync(txHash); await exchangeTransferSimulator.transferFromAsync( exampleAssetData, @@ -146,18 +141,14 @@ blockchainTests('ExchangeTransferSimulator', env => { expect(senderProxyAllowance).to.be.bignumber.equal(0); }); it("doesn't update proxyAllowance after transfer if unlimited", async () => { - txHash = await dummyERC20Token.transfer.sendTransactionAsync(sender, transferAmount, { + await dummyERC20Token.transfer(sender, transferAmount).awaitTransactionSuccessAsync({ from: coinbase, }); - await env.web3Wrapper.awaitTransactionSuccessAsync(txHash); - txHash = await dummyERC20Token.approve.sendTransactionAsync( - erc20ProxyAddress, - constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - { + await dummyERC20Token + .approve(erc20ProxyAddress, constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS) + .awaitTransactionSuccessAsync({ from: sender, - }, - ); - await env.web3Wrapper.awaitTransactionSuccessAsync(txHash); + }); await exchangeTransferSimulator.transferFromAsync( exampleAssetData, sender, diff --git a/contracts/exchange/test/internal.ts b/contracts/exchange/test/internal.ts index 897662a2ad..e9aa0c9bfd 100644 --- a/contracts/exchange/test/internal.ts +++ b/contracts/exchange/test/internal.ts @@ -1,5 +1,5 @@ import { ReferenceFunctions as LibReferenceFunctions } from '@0x/contracts-exchange-libs'; -import { blockchainTests, constants, expect, hexRandom, LogDecoder } from '@0x/contracts-test-utils'; +import { blockchainTests, constants, expect, hexRandom } from '@0x/contracts-test-utils'; import { ExchangeRevertErrors, orderHashUtils } from '@0x/order-utils'; import { Order } from '@0x/types'; import { BigNumber, SafeMathRevertErrors } from '@0x/utils'; @@ -21,7 +21,6 @@ blockchainTests('Exchange core internal functions', env => { const randomHash = () => hexRandom(constants.WORD_LENGTH); const randomAssetData = () => hexRandom(36); let testExchange: TestExchangeInternalsContract; - let logDecoder: LogDecoder; let senderAddress: string; const DEFAULT_PROTOCOL_MULTIPLIER = new BigNumber(150000); const DEFAULT_GAS_PRICE = new BigNumber(200000); @@ -37,7 +36,6 @@ blockchainTests('Exchange core internal functions', env => { {}, new BigNumber(CHAIN_ID), ); - logDecoder = new LogDecoder(env.web3Wrapper, artifacts); }); blockchainTests('assertValidMatch', () => { @@ -82,7 +80,9 @@ blockchainTests('Exchange core internal functions', env => { leftOrder.makerAssetAmount, rightOrder.makerAssetAmount, ); - return expect(testExchange.assertValidMatch.callAsync(leftOrder, rightOrder)).to.revertWith(expectedError); + return expect(testExchange.assertValidMatch(leftOrder, rightOrder).callAsync()).to.revertWith( + expectedError, + ); }); it('should revert if the taker asset multiplication should overflow', async () => { @@ -99,7 +99,9 @@ blockchainTests('Exchange core internal functions', env => { leftOrder.takerAssetAmount, rightOrder.takerAssetAmount, ); - return expect(testExchange.assertValidMatch.callAsync(leftOrder, rightOrder)).to.revertWith(expectedError); + return expect(testExchange.assertValidMatch(leftOrder, rightOrder).callAsync()).to.revertWith( + expectedError, + ); }); it('should revert if the prices of the left order is less than the price of the right order', async () => { @@ -114,7 +116,9 @@ blockchainTests('Exchange core internal functions', env => { const orderHashHexLeft = orderHashUtils.getOrderHashHex(leftOrder); const orderHashHexRight = orderHashUtils.getOrderHashHex(rightOrder); const expectedError = new ExchangeRevertErrors.NegativeSpreadError(orderHashHexLeft, orderHashHexRight); - return expect(testExchange.assertValidMatch.callAsync(leftOrder, rightOrder)).to.revertWith(expectedError); + return expect(testExchange.assertValidMatch(leftOrder, rightOrder).callAsync()).to.revertWith( + expectedError, + ); }); it('should succeed if the prices of the left and right orders are equal', async () => { @@ -126,7 +130,7 @@ blockchainTests('Exchange core internal functions', env => { makerAssetAmount: Web3Wrapper.toBaseUnitAmount(100, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(50, 18), }); - return expect(testExchange.assertValidMatch.callAsync(leftOrder, rightOrder)).to.be.fulfilled(''); + return expect(testExchange.assertValidMatch(leftOrder, rightOrder).callAsync()).to.be.fulfilled(''); }); it('should succeed if the price of the left order is higher than the price of the right', async () => { @@ -138,7 +142,7 @@ blockchainTests('Exchange core internal functions', env => { makerAssetAmount: Web3Wrapper.toBaseUnitAmount(100, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(50, 18), }); - return expect(testExchange.assertValidMatch.callAsync(leftOrder, rightOrder)).to.be.fulfilled(''); + return expect(testExchange.assertValidMatch(leftOrder, rightOrder).callAsync()).to.be.fulfilled(''); }); }); @@ -185,17 +189,12 @@ blockchainTests('Exchange core internal functions', env => { // CAll `testUpdateFilledState()`, which will set the `filled` // state for this order to `orderTakerAssetFilledAmount` before // calling `_updateFilledState()`. - const receipt = await logDecoder.getTxWithDecodedLogsAsync( - await testExchange.testUpdateFilledState.sendTransactionAsync( - order, - takerAddress, - orderHash, - orderTakerAssetFilledAmount, - fillResults, - ), - ); + const receipt = await testExchange + .testUpdateFilledState(order, takerAddress, orderHash, orderTakerAssetFilledAmount, fillResults) + .awaitTransactionSuccessAsync(); + // Grab the new `filled` state for this order. - const actualFilledState = await testExchange.filled.callAsync(orderHash); + const actualFilledState = await testExchange.filled(orderHash).callAsync(); // Assert the `filled` state for this order. expect(actualFilledState).to.bignumber.eq(expectedFilledState); // Assert the logs. @@ -247,13 +246,15 @@ blockchainTests('Exchange core internal functions', env => { takerAssetFillAmount, ); return expect( - testExchange.testUpdateFilledState.awaitTransactionSuccessAsync( - order, - randomAddress(), - randomHash(), - orderTakerAssetFilledAmount, - fillResults, - ), + testExchange + .testUpdateFilledState( + order, + randomAddress(), + randomHash(), + orderTakerAssetFilledAmount, + fillResults, + ) + .awaitTransactionSuccessAsync(), ).to.revertWith(expectedError); }); }); @@ -287,9 +288,9 @@ blockchainTests('Exchange core internal functions', env => { takerFeePaid: ONE_ETHER.times(0.025), protocolFeePaid: constants.ZERO_AMOUNT, }; - const receipt = await logDecoder.getTxWithDecodedLogsAsync( - await testExchange.settleOrder.sendTransactionAsync(orderHash, order, takerAddress, fillResults), - ); + const receipt = await testExchange + .settleOrder(orderHash, order, takerAddress, fillResults) + .awaitTransactionSuccessAsync(); const logs = receipt.logs as Array< LogWithDecodedArgs >; @@ -380,14 +381,16 @@ blockchainTests('Exchange core internal functions', env => { ); // Ensure that the call to `settleMatchOrders()` fails with the expected error. - const tx = testExchange.settleMatchOrders.sendTransactionAsync( - leftOrderHash, - rightOrderHash, - leftOrder, - rightOrder, - takerAddress, - matchedFillResults, - ); + const tx = testExchange + .settleMatchOrders( + leftOrderHash, + rightOrderHash, + leftOrder, + rightOrder, + takerAddress, + matchedFillResults, + ) + .sendTransactionAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -419,14 +422,16 @@ blockchainTests('Exchange core internal functions', env => { // The call to `settleMatchOrders()` should be successful. return expect( - testExchange.settleMatchOrders.sendTransactionAsync( - leftOrderHash, - rightOrderHash, - leftOrder, - rightOrder, - takerAddress, - matchedFillResults, - ), + testExchange + .settleMatchOrders( + leftOrderHash, + rightOrderHash, + leftOrder, + rightOrder, + takerAddress, + matchedFillResults, + ) + .sendTransactionAsync(), ).to.be.fulfilled(''); }); @@ -460,16 +465,16 @@ blockchainTests('Exchange core internal functions', env => { rightOrder.takerFeeAssetData = leftOrder.takerFeeAssetData; // Call settleMatchOrders and collect the logs - const receipt = await logDecoder.getTxWithDecodedLogsAsync( - await testExchange.settleMatchOrders.sendTransactionAsync( + const receipt = await testExchange + .settleMatchOrders( leftOrderHash, rightOrderHash, leftOrder, rightOrder, takerAddress, matchedFillResults, - ), - ); + ) + .awaitTransactionSuccessAsync(); const logs = receipt.logs as Array< LogWithDecodedArgs >; @@ -554,16 +559,16 @@ blockchainTests('Exchange core internal functions', env => { }; // Call settleMatchOrders and collect the logs - const receipt = await logDecoder.getTxWithDecodedLogsAsync( - await testExchange.settleMatchOrders.sendTransactionAsync( + const receipt = await testExchange + .settleMatchOrders( leftOrderHash, rightOrderHash, leftOrder, rightOrder, takerAddress, matchedFillResults, - ), - ); + ) + .awaitTransactionSuccessAsync(); const logs = receipt.logs as Array< LogWithDecodedArgs >; diff --git a/contracts/exchange/test/lib_exchange_rich_error_decoder.ts b/contracts/exchange/test/lib_exchange_rich_error_decoder.ts index 400fb4890b..7d7185b956 100644 --- a/contracts/exchange/test/lib_exchange_rich_error_decoder.ts +++ b/contracts/exchange/test/lib_exchange_rich_error_decoder.ts @@ -14,7 +14,7 @@ import * as _ from 'lodash'; import { artifacts } from './artifacts'; import { TestLibExchangeRichErrorDecoderContract } from './wrappers'; -blockchainTests.resets('LibExchangeRichErrorDecoder', ({ provider, txDefaults }) => { +blockchainTests.resets.only('LibExchangeRichErrorDecoder', ({ provider, txDefaults }) => { const ASSET_PROXY_ID_LENGTH = 4; const SIGNATURE_LENGTH = 66; const ASSET_DATA_LENGTH = 36; @@ -38,7 +38,7 @@ blockchainTests.resets('LibExchangeRichErrorDecoder', ({ provider, txDefaults }) // Solidity counterparts. const endpointName = `decode${revert.name}`; const callAsync = (_encoded: string) => { - return (decoder as any)[endpointName].callAsync.call((decoder as any)[endpointName], _encoded); + return (decoder as any)[endpointName](_encoded).callAsync.call((decoder as any)[endpointName]); }; describe(`${endpointName}()`, async () => { it('decodes encoded parameters', async () => { diff --git a/contracts/exchange/test/match_orders.ts b/contracts/exchange/test/match_orders.ts index 66714ee59e..820a6acbdd 100644 --- a/contracts/exchange/test/match_orders.ts +++ b/contracts/exchange/test/match_orders.ts @@ -146,28 +146,28 @@ describe('matchOrders', () => { await exchangeWrapper.registerAssetProxyAsync(erc1155Proxy.address, owner); await exchangeWrapper.registerAssetProxyAsync(multiAssetProxyContract.address, owner); // Authorize proxies. - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await multiAssetProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { + await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc1155Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await multiAssetProxyContract.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxyContract.address, { + await erc20Proxy.addAuthorizedAddress(multiAssetProxyContract.address).awaitTransactionSuccessAsync({ from: owner, }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxyContract.address, { + await erc721Proxy.addAuthorizedAddress(multiAssetProxyContract.address).awaitTransactionSuccessAsync({ from: owner, }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxyContract.address, { + await erc1155Proxy.addAuthorizedAddress(multiAssetProxyContract.address).awaitTransactionSuccessAsync({ from: owner, }); - await multiAssetProxyContract.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await multiAssetProxyContract.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - await multiAssetProxyContract.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { + await multiAssetProxyContract.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - await multiAssetProxyContract.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, { + await multiAssetProxyContract.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); @@ -182,10 +182,10 @@ describe('matchOrders', () => { const defaultOrderParamsLeft = { ...constants.STATIC_ORDER_PARAMS, makerAddress: makerAddressLeft, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(), feeRecipientAddress: feeRecipientAddressLeft, exchangeAddress: exchange.address, chainId, @@ -193,10 +193,10 @@ describe('matchOrders', () => { const defaultOrderParamsRight = { ...constants.STATIC_ORDER_PARAMS, makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(), feeRecipientAddress: feeRecipientAddressRight, exchangeAddress: exchange.address, chainId, @@ -349,8 +349,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(83, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(49, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -403,8 +403,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -454,8 +454,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(83, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(49, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -503,8 +503,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -548,8 +548,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(2126, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1063, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -1173,7 +1173,7 @@ describe('matchOrders', () => { const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({ makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), + makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), feeRecipientAddress: makerAddressLeft, }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ @@ -1270,7 +1270,7 @@ describe('matchOrders', () => { takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(2, 18), }); @@ -1297,7 +1297,7 @@ describe('matchOrders', () => { it('should revert if the right maker asset is not equal to the left taker asset', async () => { // Create orders to match const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({ - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), }); @@ -1451,8 +1451,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(87, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(48, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -1539,8 +1539,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -1590,8 +1590,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(87, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(48, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -1636,8 +1636,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -1681,8 +1681,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -1800,8 +1800,8 @@ describe('matchOrders', () => { }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ makerAddress: makerAddressRight, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(2126, 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1063, 0), feeRecipientAddress: feeRecipientAddressRight, @@ -2254,7 +2254,7 @@ describe('matchOrders', () => { const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({ makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), + makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), feeRecipientAddress: makerAddressLeft, }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ @@ -2351,7 +2351,7 @@ describe('matchOrders', () => { takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), }); const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({ - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(2, 18), }); @@ -2378,7 +2378,7 @@ describe('matchOrders', () => { it('should revert if the right maker asset is not equal to the left taker asset', async () => { // Create orders to match const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({ - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress), + takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18), }); @@ -2687,29 +2687,29 @@ describe('matchOrders', () => { let nameToMultiAssetAsset: { [name: string]: [BigNumber[], string[]] }; async function getAssetDataAsync(assetType: AssetType): Promise { - const encodeERC20AssetData = await devUtils.encodeERC20AssetData.callAsync; - const encodeERC721AssetData = await devUtils.encodeERC721AssetData.callAsync; - const encodeERC1155AssetData = await devUtils.encodeERC1155AssetData.callAsync; - const encodeMultiAssetData = await devUtils.encodeMultiAssetData.callAsync; if (nameToERC20Asset[assetType] !== undefined) { const tokenAddress = nameToERC20Asset[assetType]; - return encodeERC20AssetData(tokenAddress); + return devUtils.encodeERC20AssetData(tokenAddress).callAsync(); } if (nameToERC721Asset[assetType] !== undefined) { const [tokenAddress, tokenId] = nameToERC721Asset[assetType]; - return encodeERC721AssetData(tokenAddress, tokenId); + return devUtils.encodeERC721AssetData(tokenAddress, tokenId).callAsync(); } if (nameToERC1155FungibleAsset[assetType] !== undefined) { const [tokenAddress, tokenId] = nameToERC1155FungibleAsset[assetType]; - return encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES); + return devUtils + .encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES) + .callAsync(); } if (nameToERC1155NonFungibleAsset[assetType] !== undefined) { const [tokenAddress, tokenId] = nameToERC1155NonFungibleAsset[assetType]; - return encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES); + return devUtils + .encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES) + .callAsync(); } if (nameToMultiAssetAsset[assetType] !== undefined) { const [amounts, nestedAssetData] = nameToMultiAssetAsset[assetType]; - return encodeMultiAssetData(amounts, nestedAssetData); + return devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync(); } throw new Error(`Unknown asset type: ${assetType}`); } @@ -2755,49 +2755,57 @@ describe('matchOrders', () => { MULTI_ASSET_A: [ [ONE, TWO], [ - await devUtils.encodeERC20AssetData.callAsync(erc20Tokens[0].address), - await devUtils.encodeERC1155AssetData.callAsync( - defaultERC1155AssetAddress, - [erc1155FungibleTokens[0]], - [ONE], - constants.NULL_BYTES, - ), + await devUtils.encodeERC20AssetData(erc20Tokens[0].address).callAsync(), + await devUtils + .encodeERC1155AssetData( + defaultERC1155AssetAddress, + [erc1155FungibleTokens[0]], + [ONE], + constants.NULL_BYTES, + ) + .callAsync(), ], ], MULTI_ASSET_B: [ [ONE, TWO], [ - await devUtils.encodeERC20AssetData.callAsync(erc20Tokens[1].address), - await devUtils.encodeERC1155AssetData.callAsync( - defaultERC1155AssetAddress, - [erc1155FungibleTokens[1]], - [ONE], - constants.NULL_BYTES, - ), + await devUtils.encodeERC20AssetData(erc20Tokens[1].address).callAsync(), + await devUtils + .encodeERC1155AssetData( + defaultERC1155AssetAddress, + [erc1155FungibleTokens[1]], + [ONE], + constants.NULL_BYTES, + ) + .callAsync(), ], ], MULTI_ASSET_C: [ [ONE, TWO], [ - await devUtils.encodeERC20AssetData.callAsync(erc20Tokens[2].address), - await devUtils.encodeERC1155AssetData.callAsync( - defaultERC1155AssetAddress, - [erc1155FungibleTokens[2]], - [ONE], - constants.NULL_BYTES, - ), + await devUtils.encodeERC20AssetData(erc20Tokens[2].address).callAsync(), + await devUtils + .encodeERC1155AssetData( + defaultERC1155AssetAddress, + [erc1155FungibleTokens[2]], + [ONE], + constants.NULL_BYTES, + ) + .callAsync(), ], ], MULTI_ASSET_D: [ [ONE, TWO], [ - await devUtils.encodeERC20AssetData.callAsync(erc20Tokens[3].address), - await devUtils.encodeERC1155AssetData.callAsync( - erc1155Token.address, - [erc1155FungibleTokens[3]], - [ONE], - constants.NULL_BYTES, - ), + await devUtils.encodeERC20AssetData(erc20Tokens[3].address).callAsync(), + await devUtils + .encodeERC1155AssetData( + erc1155Token.address, + [erc1155FungibleTokens[3]], + [ONE], + constants.NULL_BYTES, + ) + .callAsync(), ], ], }; diff --git a/contracts/exchange/test/protocol_fees.ts b/contracts/exchange/test/protocol_fees.ts index c01cd6e9b5..a3a18f366e 100644 --- a/contracts/exchange/test/protocol_fees.ts +++ b/contracts/exchange/test/protocol_fees.ts @@ -32,244 +32,223 @@ blockchainTests('Protocol Fee Payments', env => { blockchainTests.resets('fillOrder Protocol Fees', () => { it('should not pay protocol fee when there is no registered protocol fee collector', async () => { - await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - false, - { + await testProtocolFeesReceiver + .testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, false) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should not forward ETH when too little value is sent', async () => { - await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.minus(10), - }, - ); + }); }); it('should pay protocol fee in ETH when the correct value is sent', async () => { - await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should pay protocol fee in ETH when extra value is sent', async () => { - await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.plus(10), - }, - ); + }); }); }); blockchainTests.resets('matchOrders Protocol Fees', () => { it('should not pay protocol fee when there is no registered protocol fee collector', async () => { - await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - false, - { + await testProtocolFeesReceiver + .testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, false) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should not forward ETH twice when too little value is sent', async () => { - await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.minus(10), - }, - ); + }); }); it('should pay protocol fee in ETH and then not forward ETH when exactly one protocol fee is sent', async () => { - await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should pay protocol fee in ETH and then not forward ETH when a bit more than one protocol fee is sent', async () => { - await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.plus(10), - }, - ); + }); }); it('should pay protocol fee in ETH when exactly double the protocol fee is sent', async () => { - await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.times(2), - }, - ); + }); }); it('should pay protocol fee in ETH when more than double the protocol fee is sent', async () => { - await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - true, - { + await testProtocolFeesReceiver + .testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.times(2).plus(10), - }, - ); + }); }); }); blockchainTests.resets('batchFillOrder ProtocolFees', () => { it('should not pay protocol fees when there is not a protocolFeeCollector registered', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(2), // If successful, create a `batchFillOrders` with 2 orders. - false, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(2), // If successful, create a `batchFillOrders` with 2 orders. + false, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should not forward ETH when less than one protocol fee is sent and only one order is in the batch', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(1), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(1), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.minus(10), - }, - ); + }); }); it('should pay one protocol fee in ETH when the exact protocol fee is sent and only one order is in the batch', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(1), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(1), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should pay one protocol fee in ETH when more than the exact protocol fee is sent and only one order is in the batch', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(1), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(1), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.plus(10), - }, - ); + }); }); it('should not forward ETH twice when an insuffiecent amount of ETH for one protocol fee is sent', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(2), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(2), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.minus(10), - }, - ); + }); }); it('should pay a protocol in ETH and not forward ETH for the second when exactly one protocol fee in ETH is sent', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(2), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(2), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE, - }, - ); + }); }); it('should pay both protocol fees in ETH when exactly two protocol fees in ETH is sent', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(2), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(2), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.times(2), - }, - ); + }); }); it('should pay two protocol fees in ETH and then not forward ETH for a third when exactly two protocol fees in ETH is sent', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(3), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(3), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.times(2), - }, - ); + }); }); it('should pay three protocol fees in ETH when more than three protocol fees in ETH is sent', async () => { - await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync( - testProtocolFees.address, - DEFAULT_PROTOCOL_FEE_MULTIPLIER, - new BigNumber(3), - true, - { + await testProtocolFeesReceiver + .testBatchFillOrdersProtocolFees( + testProtocolFees.address, + DEFAULT_PROTOCOL_FEE_MULTIPLIER, + new BigNumber(3), + true, + ) + .awaitTransactionSuccessAsync({ gasPrice: DEFAULT_GAS_PRICE, value: DEFAULT_PROTOCOL_FEE.times(3).plus(10), - }, - ); + }); }); }); }); diff --git a/contracts/exchange/test/protocol_fees_manager.ts b/contracts/exchange/test/protocol_fees_manager.ts index 480b1d9de0..8d56dea1c1 100644 --- a/contracts/exchange/test/protocol_fees_manager.ts +++ b/contracts/exchange/test/protocol_fees_manager.ts @@ -43,7 +43,7 @@ blockchainTests.resets('MixinProtocolFees', env => { const expectedError = new OwnableRevertErrors.OnlyOwnerError(nonOwner, owner); // Ensure that the transaction reverts with the expected rich error. - const tx = exchange.setProtocolFeeCollectorAddress.sendTransactionAsync(protocolFeeCollector, { + const tx = exchange.setProtocolFeeCollectorAddress(protocolFeeCollector).sendTransactionAsync({ from: nonOwner, }); return expect(tx).to.revertWith(expectedError); @@ -51,15 +51,14 @@ blockchainTests.resets('MixinProtocolFees', env => { it('should succeed and emit an ProtocolFeeMultiplier event if msg.sender == owner', async () => { // Call the `setProtocolFeeMultiplier()` function and get the receipt. - const receipt = await exchange.setProtocolFeeMultiplier.awaitTransactionSuccessAsync( - protocolFeeMultiplier, - { + const receipt = await exchange + .setProtocolFeeMultiplier(protocolFeeMultiplier) + .awaitTransactionSuccessAsync({ from: owner, - }, - ); + }); // Verify that the protocolFeeCollector address was actually updated to the correct address. - const updated = await exchange.protocolFeeMultiplier.callAsync(); + const updated = await exchange.protocolFeeMultiplier().callAsync(); expect(updated).bignumber.to.be.eq(protocolFeeMultiplier); // Ensure that the correct `ProtocolFeeCollectorAddress` event was logged. @@ -76,7 +75,7 @@ blockchainTests.resets('MixinProtocolFees', env => { const expectedError = new OwnableRevertErrors.OnlyOwnerError(nonOwner, owner); // Ensure that the transaction reverts with the expected rich error. - const tx = exchange.setProtocolFeeCollectorAddress.sendTransactionAsync(protocolFeeCollector, { + const tx = exchange.setProtocolFeeCollectorAddress(protocolFeeCollector).sendTransactionAsync({ from: nonOwner, }); return expect(tx).to.revertWith(expectedError); @@ -84,15 +83,14 @@ blockchainTests.resets('MixinProtocolFees', env => { it('should succeed and emit an ProtocolFeeCollectorAddress event if msg.sender == owner', async () => { // Call the `setProtocolFeeCollectorAddress()` function and get the receipt. - const receipt = await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync( - protocolFeeCollector, - { + const receipt = await exchange + .setProtocolFeeCollectorAddress(protocolFeeCollector) + .awaitTransactionSuccessAsync({ from: owner, - }, - ); + }); // Verify that the protocolFeeCollector address was actually updated to the correct address. - const updated = await exchange.protocolFeeCollector.callAsync(); + const updated = await exchange.protocolFeeCollector().callAsync(); expect(updated).to.be.eq(protocolFeeCollector); // Ensure that the correct `UpdatedProtocolFeeCollectorAddress` event was logged. @@ -109,23 +107,23 @@ blockchainTests.resets('MixinProtocolFees', env => { const expectedError = new OwnableRevertErrors.OnlyOwnerError(nonOwner, owner); // Ensure that the transaction reverts with the expected rich error. - const tx = exchange.detachProtocolFeeCollector.sendTransactionAsync({ + const tx = exchange.detachProtocolFeeCollector().sendTransactionAsync({ from: nonOwner, }); return expect(tx).to.revertWith(expectedError); }); it('should succeed and emit an ProtocolFeeCollectorAddress event if msg.sender == owner', async () => { - await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync(protocolFeeCollector, { + await exchange.setProtocolFeeCollectorAddress(protocolFeeCollector).awaitTransactionSuccessAsync({ from: owner, }); - const receipt = await exchange.detachProtocolFeeCollector.awaitTransactionSuccessAsync({ + const receipt = await exchange.detachProtocolFeeCollector().awaitTransactionSuccessAsync({ from: owner, }); // Verify that the protocolFeeCollector address was actually updated to the correct address. - const updated = await exchange.protocolFeeCollector.callAsync(); + const updated = await exchange.protocolFeeCollector().callAsync(); expect(updated).to.be.eq(constants.NULL_ADDRESS); // Ensure that the correct `UpdatedProtocolFeeCollectorAddress` event was logged. diff --git a/contracts/exchange/test/reentrancy_tests.ts b/contracts/exchange/test/reentrancy_tests.ts index 148bfb60c1..a57e712aeb 100644 --- a/contracts/exchange/test/reentrancy_tests.ts +++ b/contracts/exchange/test/reentrancy_tests.ts @@ -102,8 +102,8 @@ blockchainTests.resets('Reentrancy Tests', env => { for (const fn of NON_REENTRANT_FUNCTIONS) { it(`${fn.name}()`, async () => { const inputs = createFunctionInputs(fn.inputs); - const callData = (testerContract as any)[fn.name].getABIEncodedTransactionData(...inputs); - const isReentrant = await testerContract.isReentrant.callAsync(callData); + const callData = (testerContract as any)[fn.name](...inputs).getABIEncodedTransactionData(); + const isReentrant = await testerContract.isReentrant(callData).callAsync(); expect(isReentrant).to.be.false(); }); } @@ -113,8 +113,8 @@ blockchainTests.resets('Reentrancy Tests', env => { for (const fn of REENTRANT_FUNCTIONS) { it(`${fn.name}()`, async () => { const inputs = createFunctionInputs(fn.inputs); - const callData = (testerContract as any)[fn.name].getABIEncodedTransactionData(...inputs); - const isReentrant = await testerContract.isReentrant.callAsync(callData); + const callData = (testerContract as any)[fn.name](...inputs).getABIEncodedTransactionData(); + const isReentrant = await testerContract.isReentrant(callData).callAsync(); expect(isReentrant).to.be.true(); }); } diff --git a/contracts/exchange/test/signature_validator.ts b/contracts/exchange/test/signature_validator.ts index ef0f2ff195..d2fbf277ff 100644 --- a/contracts/exchange/test/signature_validator.ts +++ b/contracts/exchange/test/signature_validator.ts @@ -58,16 +58,14 @@ blockchainTests.resets('MixinSignatureValidator', env => { {}, signatureValidator.address, ); - validatorWalletRevertReason = await validatorWallet.REVERT_REASON.callAsync(); + validatorWalletRevertReason = await validatorWallet.REVERT_REASON().callAsync(); // Approve the validator for both signers. await Promise.all( [signerAddress, notSignerAddress].map(async (addr: string) => { - return signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - true, - { from: addr }, - ); + return signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, true) + .awaitTransactionSuccessAsync({ from: addr }); }), ); @@ -299,7 +297,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should return true when SignatureType=Presigned and signer has presigned hash', async () => { const hashHex = getCurrentHashHex(); // Presign the hash - await signatureValidator.preSign.awaitTransactionSuccessAsync(hashHex, { from: signerAddress }); + await signatureValidator.preSign(hashHex).awaitTransactionSuccessAsync({ from: signerAddress }); // Validate presigned signature const signatureHex = hexConcat(SignatureType.PreSigned); const isValidSignature = await validateAsync(hashHex, signerAddress, signatureHex); @@ -333,13 +331,11 @@ blockchainTests.resets('MixinSignatureValidator', env => { ? constants.NULL_BYTES : hashBytes(validatorExpectedSignatureHex); if (validatorAction !== undefined) { - await validatorWallet.prepare.awaitTransactionSuccessAsync( - _hashHex, - validatorAction, - expectedSignatureHashHex, - ); + await validatorWallet + .prepare(_hashHex, validatorAction, expectedSignatureHashHex) + .awaitTransactionSuccessAsync(); } - return signatureValidator.isValidHashSignature.callAsync(_hashHex, _signerAddress, signatureHex); + return signatureValidator.isValidHashSignature(_hashHex, _signerAddress, signatureHex).callAsync(); }; it('should revert when signerAddress == 0', async () => { @@ -388,11 +384,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { const trezorSignatureType = ethUtil.toBuffer(`0x${SignatureType.EthSign}`); const signature = Buffer.concat([v, r, s, trezorSignatureType]); const signatureHex = ethUtil.bufferToHex(signature); - const isValidSignature = await signatureValidator.isValidHashSignature.callAsync( - messageHash, - signer, - signatureHex, - ); + const isValidSignature = await signatureValidator + .isValidHashSignature(messageHash, signer, signatureHex) + .callAsync(); expect(isValidSignature).to.be.true(); }); @@ -406,11 +400,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { const trezorSignatureType = ethUtil.toBuffer(`0x${SignatureType.EthSign}`); const signature = Buffer.concat([v, r, s, trezorSignatureType]); const signatureHex = ethUtil.bufferToHex(signature); - const isValidSignature = await signatureValidator.isValidHashSignature.callAsync( - messageHash, - signer, - signatureHex, - ); + const isValidSignature = await signatureValidator + .isValidHashSignature(messageHash, signer, signatureHex) + .callAsync(); expect(isValidSignature).to.be.true(); }); @@ -427,10 +419,10 @@ blockchainTests.resets('MixinSignatureValidator', env => { ...constants.STATIC_ORDER_PARAMS, makerAddress, feeRecipientAddress: randomAddress(), - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(randomAddress()), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(randomAddress()), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(randomAddress()), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(randomAddress()), + makerAssetData: await devUtils.encodeERC20AssetData(randomAddress()).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(randomAddress()).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(randomAddress()).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(randomAddress()).callAsync(), makerFee: constants.ZERO_AMOUNT, takerFee: constants.ZERO_AMOUNT, exchangeAddress: signatureValidator.address, @@ -455,13 +447,11 @@ blockchainTests.resets('MixinSignatureValidator', env => { ? constants.NULL_BYTES : hashBytes(validatorExpectedSignatureHex); if (validatorAction !== undefined) { - await validatorWallet.prepare.awaitTransactionSuccessAsync( - orderHashHex, - validatorAction, - expectedSignatureHashHex, - ); + await validatorWallet + .prepare(orderHashHex, validatorAction, expectedSignatureHashHex) + .awaitTransactionSuccessAsync(); } - return signatureValidator.isValidOrderSignature.callAsync(order, signatureHex); + return signatureValidator.isValidOrderSignature(order, signatureHex).callAsync(); }; it('should revert when signerAddress == 0', async () => { @@ -477,7 +467,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { constants.NULL_ADDRESS, signatureHex, ); - const tx = signatureValidator.isValidOrderSignature.callAsync(nullMakerOrder, signatureHex); + const tx = signatureValidator.isValidOrderSignature(nullMakerOrder, signatureHex).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -526,7 +516,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, validatorWallet.address, SignatureType.Validator); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -543,7 +533,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, validatorWallet.address, SignatureType.Validator); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -560,7 +550,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, validatorWallet.address, SignatureType.Validator); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -573,11 +563,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should revert when SignatureType=Validator and signature is shorter than 21 bytes', async () => { // Set approval of signature validator to false - await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - false, - { from: signedOrder.makerAddress }, - ); + await signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, false) + .awaitTransactionSuccessAsync({ from: signedOrder.makerAddress }); // Doesn't have to contain a real signature since our wallet contract // just does a hash comparison. const signatureHex = hexConcat(SignatureType.Validator); @@ -594,11 +582,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should revert when SignatureType=Validator, signature is valid and validator is not approved', async () => { // Set approval of signature validator to false - await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - false, - { from: signedOrder.makerAddress }, - ); + await signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, false) + .awaitTransactionSuccessAsync({ from: signedOrder.makerAddress }); // Doesn't have to contain a real signature since our wallet contract // just does a hash comparison. const signatureDataHex = generateRandomSignature(); @@ -663,7 +649,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, SignatureType.EIP1271Wallet); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -680,7 +666,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { // just does a hash comparison. const signatureHex = hexConcat(generateRandomSignature(), SignatureType.EIP1271Wallet); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -695,7 +681,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { signedOrder.makerAddress = validatorWallet.address; const signatureHex = hexConcat(SignatureType.EIP1271Wallet); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -710,21 +696,21 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureHex = hexConcat(SignatureType.EIP1271Wallet); signedOrder.makerAddress = notSignerAddress; const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( notSignerAddress, data, signatureHex, constants.NULL_BYTES, ); - const tx = signatureValidator.isValidOrderSignature.callAsync(signedOrder, signatureHex); + const tx = signatureValidator.isValidOrderSignature(signedOrder, signatureHex).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('should revert when signer is an EOA and SignatureType=Validator', async () => { const signatureHex = hexConcat(notSignerAddress, SignatureType.Validator); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); - const data = eip1271Data.OrderWithHash.getABIEncodedTransactionData(signedOrder, orderHashHex); + const data = eip1271Data.OrderWithHash(signedOrder, orderHashHex).getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( notSignerAddress, data, @@ -732,12 +718,10 @@ blockchainTests.resets('MixinSignatureValidator', env => { constants.NULL_BYTES, ); // Register an EOA as a validator. - await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - notSignerAddress, - true, - { from: signerAddress }, - ); - const tx = signatureValidator.isValidOrderSignature.callAsync(signedOrder, signatureHex); + await signatureValidator + .setSignatureValidatorApproval(notSignerAddress, true) + .awaitTransactionSuccessAsync({ from: signerAddress }); + const tx = signatureValidator.isValidOrderSignature(signedOrder, signatureHex).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -787,13 +771,11 @@ blockchainTests.resets('MixinSignatureValidator', env => { ? constants.NULL_BYTES : hashBytes(validatorExpectedSignatureHex); if (validatorAction !== undefined) { - await validatorWallet.prepare.awaitTransactionSuccessAsync( - transactionHashHex, - validatorAction, - expectedSignatureHashHex, - ); + await validatorWallet + .prepare(transactionHashHex, validatorAction, expectedSignatureHashHex) + .awaitTransactionSuccessAsync(); } - return signatureValidator.isValidTransactionSignature.callAsync(transaction, signatureHex); + return signatureValidator.isValidTransactionSignature(transaction, signatureHex).callAsync(); }; it('should revert when signerAddress == 0', async () => { @@ -809,7 +791,7 @@ blockchainTests.resets('MixinSignatureValidator', env => { constants.NULL_ADDRESS, signatureHex, ); - const tx = signatureValidator.isValidTransactionSignature.callAsync(nullSignerTransaction, signatureHex); + const tx = signatureValidator.isValidTransactionSignature(nullSignerTransaction, signatureHex).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -856,11 +838,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should revert when SignatureType=Validator and signature is shorter than 21 bytes', async () => { // Set approval of signature validator to false - await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - false, - { from: signedTransaction.signerAddress }, - ); + await signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, false) + .awaitTransactionSuccessAsync({ from: signedTransaction.signerAddress }); // Doesn't have to contain a real signature since our wallet contract // just does a hash comparison. const signatureHex = hexConcat(SignatureType.Validator); @@ -879,10 +859,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, validatorWallet.address, SignatureType.Validator); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -904,10 +883,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, validatorWallet.address, SignatureType.Validator); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -924,10 +902,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, validatorWallet.address, SignatureType.Validator); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -940,11 +917,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should revert when SignatureType=Validator, signature is valid and validator is not approved', async () => { // Set approval of signature validator to false - await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - false, - { from: signedTransaction.signerAddress }, - ); + await signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, false) + .awaitTransactionSuccessAsync({ from: signedTransaction.signerAddress }); // Doesn't have to contain a real signature since our wallet contract // just does a hash comparison. const signatureDataHex = generateRandomSignature(); @@ -1009,10 +984,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { const signatureDataHex = generateRandomSignature(); const signatureHex = hexConcat(signatureDataHex, SignatureType.EIP1271Wallet); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -1034,10 +1008,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { // just does a hash comparison. const signatureHex = hexConcat(generateRandomSignature(), SignatureType.EIP1271Wallet); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -1054,10 +1027,9 @@ blockchainTests.resets('MixinSignatureValidator', env => { // just does a hash comparison. const signatureHex = hexConcat(generateRandomSignature(), SignatureType.EIP1271Wallet); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( validatorWallet.address, data, @@ -1071,27 +1043,25 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should revert when signer is an EOA and SignatureType=EIP1271Wallet', async () => { const signatureHex = hexConcat(SignatureType.EIP1271Wallet); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( signedTransaction.signerAddress, data, signatureHex, constants.NULL_BYTES, ); - const tx = signatureValidator.isValidTransactionSignature.callAsync(signedTransaction, signatureHex); + const tx = signatureValidator.isValidTransactionSignature(signedTransaction, signatureHex).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('should revert when signer is an EOA and SignatureType=Validator', async () => { const signatureHex = hexConcat(notSignerAddress, SignatureType.Validator); const transactionHashHex = transactionHashUtils.getTransactionHashHex(signedTransaction); - const data = eip1271Data.ZeroExTransactionWithHash.getABIEncodedTransactionData( - signedTransaction, - transactionHashHex, - ); + const data = eip1271Data + .ZeroExTransactionWithHash(signedTransaction, transactionHashHex) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.EIP1271SignatureError( notSignerAddress, data, @@ -1099,12 +1069,10 @@ blockchainTests.resets('MixinSignatureValidator', env => { constants.NULL_BYTES, ); // Register an EOA as a validator. - await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - notSignerAddress, - true, - { from: signerAddress }, - ); - const tx = signatureValidator.isValidTransactionSignature.callAsync(signedTransaction, signatureHex); + await signatureValidator + .setSignatureValidatorApproval(notSignerAddress, true) + .awaitTransactionSuccessAsync({ from: signerAddress }); + const tx = signatureValidator.isValidTransactionSignature(signedTransaction, signatureHex).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -1134,13 +1102,11 @@ blockchainTests.resets('MixinSignatureValidator', env => { it('should emit a SignatureValidatorApprovalSet with correct args when a validator is approved', async () => { const approval = true; - const res = await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - approval, - { + const res = await signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, approval) + .awaitTransactionSuccessAsync({ from: signerAddress, - }, - ); + }); expect(res.logs.length).to.equal(1); const log = signatureValidatorLogDecoder.decodeLogOrThrow(res.logs[0]) as LogWithDecodedArgs< TestSignatureValidatorSignatureValidatorApprovalEventArgs @@ -1152,13 +1118,11 @@ blockchainTests.resets('MixinSignatureValidator', env => { }); it('should emit a SignatureValidatorApprovalSet with correct args when a validator is disapproved', async () => { const approval = false; - const res = await signatureValidator.setSignatureValidatorApproval.awaitTransactionSuccessAsync( - validatorWallet.address, - approval, - { + const res = await signatureValidator + .setSignatureValidatorApproval(validatorWallet.address, approval) + .awaitTransactionSuccessAsync({ from: signerAddress, - }, - ); + }); expect(res.logs.length).to.equal(1); const log = signatureValidatorLogDecoder.decodeLogOrThrow(res.logs[0]) as LogWithDecodedArgs< TestSignatureValidatorSignatureValidatorApprovalEventArgs diff --git a/contracts/exchange/test/transactions.ts b/contracts/exchange/test/transactions.ts index 5ecff45135..475a15d4ff 100644 --- a/contracts/exchange/test/transactions.ts +++ b/contracts/exchange/test/transactions.ts @@ -101,7 +101,7 @@ blockchainTests.resets('Exchange transactions', env => { exchangeWrapper = new ExchangeWrapper(exchangeInstance); await exchangeWrapper.registerAssetProxyAsync(erc20Proxy.address, owner); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeInstance.address, { from: owner }); + await erc20Proxy.addAuthorizedAddress(exchangeInstance.address).awaitTransactionSuccessAsync({ from: owner }); defaultMakerTokenAddress = erc20TokenA.address; defaultTakerTokenAddress = erc20TokenB.address; @@ -112,10 +112,10 @@ blockchainTests.resets('Exchange transactions', env => { ...constants.STATIC_ORDER_PARAMS, makerAddress, feeRecipientAddress, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerTokenAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerTokenAddress), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerFeeTokenAddress), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerFeeTokenAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerTokenAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerTokenAddress).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultMakerFeeTokenAddress).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultTakerFeeTokenAddress).callAsync(), exchangeAddress: exchangeInstance.address, chainId, }; @@ -179,11 +179,9 @@ blockchainTests.resets('Exchange transactions', env => { actualGasPrice, transaction.gasPrice, ); - const tx = exchangeInstance.executeTransaction.sendTransactionAsync( - transaction, - transaction.signature, - { gasPrice: actualGasPrice, from: senderAddress }, - ); + const tx = exchangeInstance + .executeTransaction(transaction, transaction.signature) + .sendTransactionAsync({ gasPrice: actualGasPrice, from: senderAddress }); return expect(tx).to.revertWith(expectedError); }); it('should revert if the actual gasPrice is less than expected', async () => { @@ -200,11 +198,9 @@ blockchainTests.resets('Exchange transactions', env => { actualGasPrice, transaction.gasPrice, ); - const tx = exchangeInstance.executeTransaction.sendTransactionAsync( - transaction, - transaction.signature, - { gasPrice: actualGasPrice, from: senderAddress }, - ); + const tx = exchangeInstance + .executeTransaction(transaction, transaction.signature) + .sendTransactionAsync({ gasPrice: actualGasPrice, from: senderAddress }); return expect(tx).to.revertWith(expectedError); }); }); @@ -288,13 +284,11 @@ blockchainTests.resets('Exchange transactions', env => { const orders = [order]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); - const returnData = await exchangeInstance.executeTransaction.callAsync( - transaction, - transaction.signature, - { + const returnData = await exchangeInstance + .executeTransaction(transaction, transaction.signature) + .callAsync({ from: senderAddress, - }, - ); + }); const abi = artifacts.Exchange.compilerOutput.abi; const methodAbi = abi.filter(abiItem => (abiItem as MethodAbi).name === fnName)[0] as MethodAbi; const abiEncoder = new AbiEncoder.Method(methodAbi); @@ -328,10 +322,9 @@ blockchainTests.resets('Exchange transactions', env => { const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); const transactionHashHex = transactionHashUtils.getTransactionHashHex(transaction); - const recursiveData = exchangeInstance.executeTransaction.getABIEncodedTransactionData( - transaction, - transaction.signature, - ); + const recursiveData = exchangeInstance + .executeTransaction(transaction, transaction.signature) + .getABIEncodedTransactionData(); const recursiveTransaction = await takerTransactionFactory.newSignedTransactionAsync({ data: recursiveData, }); @@ -353,10 +346,9 @@ blockchainTests.resets('Exchange transactions', env => { const orders = [await orderFactory.newSignedOrderAsync()]; const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); - const recursiveData = exchangeInstance.executeTransaction.getABIEncodedTransactionData( - transaction, - constants.NULL_BYTES, - ); + const recursiveData = exchangeInstance + .executeTransaction(transaction, constants.NULL_BYTES) + .getABIEncodedTransactionData(); const recursiveTransaction = await takerTransactionFactory.newSignedTransactionAsync({ data: recursiveData, }); @@ -539,7 +531,7 @@ blockchainTests.resets('Exchange transactions', env => { describe('cancelOrdersUpTo', () => { it('should be successful if signed by maker and called by sender', async () => { const targetEpoch = constants.ZERO_AMOUNT; - const data = exchangeInstance.cancelOrdersUpTo.getABIEncodedTransactionData(targetEpoch); + const data = exchangeInstance.cancelOrdersUpTo(targetEpoch).getABIEncodedTransactionData(); const transaction = await makerTransactionFactory.newSignedTransactionAsync({ data }); const transactionReceipt = await exchangeWrapper.executeTransactionAsync(transaction, senderAddress); const cancelLogs = transactionReceipt.logs.filter( @@ -553,7 +545,7 @@ blockchainTests.resets('Exchange transactions', env => { }); it('should be successful if called by maker without a signature', async () => { const targetEpoch = constants.ZERO_AMOUNT; - const data = exchangeInstance.cancelOrdersUpTo.getABIEncodedTransactionData(targetEpoch); + const data = exchangeInstance.cancelOrdersUpTo(targetEpoch).getABIEncodedTransactionData(); const transaction = await makerTransactionFactory.newSignedTransactionAsync({ data }); const transactionReceipt = await exchangeWrapper.executeTransactionAsync(transaction, makerAddress); const cancelLogs = transactionReceipt.logs.filter( @@ -570,34 +562,33 @@ blockchainTests.resets('Exchange transactions', env => { it('should preSign a hash for the signer', async () => { const order = await orderFactory.newSignedOrderAsync(); const orderHash = orderHashUtils.getOrderHashHex(order); - const data = exchangeInstance.preSign.getABIEncodedTransactionData(orderHash); + const data = exchangeInstance.preSign(orderHash).getABIEncodedTransactionData(); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); - let isPreSigned = await exchangeInstance.preSigned.callAsync(orderHash, takerAddress); + let isPreSigned = await exchangeInstance.preSigned(orderHash, takerAddress).callAsync(); expect(isPreSigned).to.be.eq(false); await exchangeWrapper.executeTransactionAsync(transaction, senderAddress); - isPreSigned = await exchangeInstance.preSigned.callAsync(orderHash, takerAddress); + isPreSigned = await exchangeInstance.preSigned(orderHash, takerAddress).callAsync(); expect(isPreSigned).to.be.eq(true); }); it('should preSign a hash for the caller if called without a signature', async () => { const order = await orderFactory.newSignedOrderAsync(); const orderHash = orderHashUtils.getOrderHashHex(order); - const data = exchangeInstance.preSign.getABIEncodedTransactionData(orderHash); + const data = exchangeInstance.preSign(orderHash).getABIEncodedTransactionData(); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); transaction.signature = constants.NULL_BYTES; - let isPreSigned = await exchangeInstance.preSigned.callAsync(orderHash, takerAddress); + let isPreSigned = await exchangeInstance.preSigned(orderHash, takerAddress).callAsync(); expect(isPreSigned).to.be.eq(false); await exchangeWrapper.executeTransactionAsync(transaction, takerAddress); - isPreSigned = await exchangeInstance.preSigned.callAsync(orderHash, takerAddress); + isPreSigned = await exchangeInstance.preSigned(orderHash, takerAddress).callAsync(); expect(isPreSigned).to.be.eq(true); }); }); describe('setSignatureValidatorApproval', () => { it('should approve a validator for the signer', async () => { const shouldApprove = true; - const data = exchangeInstance.setSignatureValidatorApproval.getABIEncodedTransactionData( - validatorAddress, - shouldApprove, - ); + const data = exchangeInstance + .setSignatureValidatorApproval(validatorAddress, shouldApprove) + .getABIEncodedTransactionData(); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); const transactionReceipt = await exchangeWrapper.executeTransactionAsync(transaction, senderAddress); const validatorApprovalLogs = transactionReceipt.logs.filter( @@ -615,10 +606,9 @@ blockchainTests.resets('Exchange transactions', env => { }); it('should approve a validator for the caller if called with no signature', async () => { const shouldApprove = true; - const data = exchangeInstance.setSignatureValidatorApproval.getABIEncodedTransactionData( - validatorAddress, - shouldApprove, - ); + const data = exchangeInstance + .setSignatureValidatorApproval(validatorAddress, shouldApprove) + .getABIEncodedTransactionData(); const transaction = await takerTransactionFactory.newSignedTransactionAsync({ data }); transaction.signature = constants.NULL_BYTES; const transactionReceipt = await exchangeWrapper.executeTransactionAsync(transaction, takerAddress); @@ -839,11 +829,12 @@ blockchainTests.resets('Exchange transactions', env => { const data2 = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.FillOrder, [order2]); const transaction1 = await takerTransactionFactory.newSignedTransactionAsync({ data: data1 }); const transaction2 = await taker2TransactionFactory.newSignedTransactionAsync({ data: data2 }); - const returnData = await exchangeInstance.batchExecuteTransactions.callAsync( - [transaction1, transaction2], - [transaction1.signature, transaction2.signature], - { from: senderAddress }, - ); + const returnData = await exchangeInstance + .batchExecuteTransactions( + [transaction1, transaction2], + [transaction1.signature, transaction2.signature], + ) + .callAsync({ from: senderAddress }); const abi = artifacts.Exchange.compilerOutput.abi; const methodAbi = abi.filter( abiItem => (abiItem as MethodAbi).name === ExchangeFunctionName.FillOrder, @@ -945,11 +936,12 @@ blockchainTests.resets('Exchange transactions', env => { ]); const transaction1 = await takerTransactionFactory.newSignedTransactionAsync({ data: data1 }); const transaction2 = await makerTransactionFactory.newSignedTransactionAsync({ data: data2 }); - const returnData = await exchangeInstance.batchExecuteTransactions.callAsync( - [transaction1, transaction2], - [transaction1.signature, transaction2.signature], - { from: senderAddress }, - ); + const returnData = await exchangeInstance + .batchExecuteTransactions( + [transaction1, transaction2], + [transaction1.signature, transaction2.signature], + ) + .callAsync({ from: senderAddress }); const abi = artifacts.Exchange.compilerOutput.abi; const methodAbi = abi.filter( abiItem => (abiItem as MethodAbi).name === ExchangeFunctionName.FillOrder, diff --git a/contracts/exchange/test/transactions_unit_tests.ts b/contracts/exchange/test/transactions_unit_tests.ts index 35e5aec284..37ffd6be33 100644 --- a/contracts/exchange/test/transactions_unit_tests.ts +++ b/contracts/exchange/test/transactions_unit_tests.ts @@ -1,4 +1,4 @@ -import { blockchainTests, constants, describe, expect, hexRandom, TransactionHelper } from '@0x/contracts-test-utils'; +import { blockchainTests, constants, describe, expect, hexRandom } from '@0x/contracts-test-utils'; import { ExchangeRevertErrors, transactionHashUtils } from '@0x/order-utils'; import { EIP712DomainWithDefaultSchema, ZeroExTransaction } from '@0x/types'; import { BigNumber, StringRevertError } from '@0x/utils'; @@ -30,8 +30,6 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef const DEADBEEF_RETURN_DATA = '0xdeadbeef'; const INVALID_SIGNATURE = '0x0000'; - const transactionHelper = new TransactionHelper(web3Wrapper, artifacts); - before(async () => { // A list of available addresses to use during testing. accounts = await web3Wrapper.getAvailableAddressesAsync(); @@ -55,11 +53,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef * Generates calldata for a call to `executable()` in the `TestTransactions` contract. */ function getExecutableCallData(shouldSucceed: boolean, callData: string, returnData: string): string { - return (transactionsContract as any).executable.getABIEncodedTransactionData( - shouldSucceed, - callData, - returnData, - ); + return (transactionsContract as any) + .executable(shouldSucceed, callData, returnData) + .getABIEncodedTransactionData(); } interface GenerateZeroExTransactionParams { @@ -110,10 +106,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ); // Call the `batchExecuteTransactions()` function and ensure that it reverts with the expected revert error. - const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - [transaction], - [randomSignature()], - ); + const tx = transactionsContract + .batchExecuteTransactions([transaction], [randomSignature()]) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -133,10 +128,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ); // Call the `batchExecuteTransactions()` function and ensure that it reverts with the expected revert error. - const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - [transaction1, transaction2], - [randomSignature(), randomSignature()], - ); + const tx = transactionsContract + .batchExecuteTransactions([transaction1, transaction2], [randomSignature(), randomSignature()]) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -156,10 +150,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ); // Call the `batchExecuteTransactions()` function and ensure that it reverts with the expected revert error. - const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - [transaction1, transaction2], - [randomSignature(), randomSignature()], - ); + const tx = transactionsContract + .batchExecuteTransactions([transaction1, transaction2], [randomSignature(), randomSignature()]) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -177,13 +170,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ExchangeRevertErrors.TransactionErrorCode.AlreadyExecuted, transactionHash2, ); - const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - [transaction1, transaction2], - [randomSignature(), randomSignature()], - { + const tx = transactionsContract + .batchExecuteTransactions([transaction1, transaction2], [randomSignature(), randomSignature()]) + .awaitTransactionSuccessAsync({ from: accounts[0], - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); @@ -196,15 +187,12 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); const validSignature = randomSignature(); - const [result, receipt] = await transactionHelper.getResultAndReceiptAsync( - transactionsContract.batchExecuteTransactions, - [transaction], - [validSignature], - { from: accounts[0] }, - ); + const contractFn = transactionsContract.batchExecuteTransactions([transaction], [validSignature]); + const result = await contractFn.callAsync({ from: accounts[0] }); + const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] }); expect(result.length).to.be.eq(1); - const returnData = transactionsContract.executeTransaction.getABIDecodedReturnData(result[0]); + const returnData = transactionsContract.getABIDecodedReturnData('executeTransaction', result[0]); expect(returnData).to.equal(DEADBEEF_RETURN_DATA); // Ensure that the correct number of events were logged. @@ -234,18 +222,18 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef const transactionHash1 = transactionHashUtils.getTransactionHashHex(transaction1); const transactionHash2 = transactionHashUtils.getTransactionHashHex(transaction2); - const [result, receipt] = await transactionHelper.getResultAndReceiptAsync( - transactionsContract.batchExecuteTransactions, + const contractFn = transactionsContract.batchExecuteTransactions( [transaction1, transaction2], [randomSignature(), randomSignature()], - { from: accounts[0] }, ); + const result = await contractFn.callAsync({ from: accounts[0] }); + const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] }); expect(result.length).to.be.eq(2); - expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result[0])).to.equal( + expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result[0])).to.equal( DEADBEEF_RETURN_DATA, ); - expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result[1])).to.equal(returnData2); + expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result[1])).to.equal(returnData2); // Verify that the correct number of events were logged. const logs = receipt.logs as Array>; @@ -270,17 +258,18 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef const innerTransaction2 = await generateZeroExTransactionAsync({ signerAddress: accounts[1] }); const innerBatchExecuteTransaction = await generateZeroExTransactionAsync({ signerAddress: accounts[2], - callData: transactionsContract.batchExecuteTransactions.getABIEncodedTransactionData( - [innerTransaction1, innerTransaction2], - [randomSignature(), randomSignature()], - ), + callData: transactionsContract + .batchExecuteTransactions( + [innerTransaction1, innerTransaction2], + [randomSignature(), randomSignature()], + ) + .getABIEncodedTransactionData(), }); const outerExecuteTransaction = await generateZeroExTransactionAsync({ signerAddress: accounts[1], - callData: transactionsContract.executeTransaction.getABIEncodedTransactionData( - innerBatchExecuteTransaction, - randomSignature(), - ), + callData: transactionsContract + .executeTransaction(innerBatchExecuteTransaction, randomSignature()) + .getABIEncodedTransactionData(), }); const innerBatchExecuteTransactionHash = transactionHashUtils.getTransactionHashHex( innerBatchExecuteTransaction, @@ -294,11 +283,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef outerExecuteTransactionHash, innerExpectedError.encode(), ); - const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - [outerExecuteTransaction], - [randomSignature()], - { from: accounts[2] }, - ); + const tx = transactionsContract + .batchExecuteTransactions([outerExecuteTransaction], [randomSignature()]) + .awaitTransactionSuccessAsync({ from: accounts[2] }); return expect(tx).to.revertWith(outerExpectedError); }); it('should allow recursion as long as currentContextAddress is not set', async () => { @@ -307,34 +294,32 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef // From this point on, all transactions and calls will have the same sender, which does not change currentContextAddress when called const innerBatchExecuteTransaction = await generateZeroExTransactionAsync({ signerAddress: accounts[2], - callData: transactionsContract.batchExecuteTransactions.getABIEncodedTransactionData( - [innerTransaction1, innerTransaction2], - [randomSignature(), randomSignature()], - ), + callData: transactionsContract + .batchExecuteTransactions( + [innerTransaction1, innerTransaction2], + [randomSignature(), randomSignature()], + ) + .getABIEncodedTransactionData(), }); const outerExecuteTransaction = await generateZeroExTransactionAsync({ signerAddress: accounts[2], - callData: transactionsContract.executeTransaction.getABIEncodedTransactionData( - innerBatchExecuteTransaction, - randomSignature(), - ), + callData: transactionsContract + .executeTransaction(innerBatchExecuteTransaction, randomSignature()) + .getABIEncodedTransactionData(), }); return expect( - transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - [outerExecuteTransaction], - [randomSignature()], - { from: accounts[2] }, - ), + transactionsContract + .batchExecuteTransactions([outerExecuteTransaction], [randomSignature()]) + .awaitTransactionSuccessAsync({ from: accounts[2] }), ).to.be.fulfilled(''); }); }); describe('executeTransaction', () => { function getExecuteTransactionCallData(transaction: ZeroExTransaction, signature: string): string { - return (transactionsContract as any).executeTransaction.getABIEncodedTransactionData( - transaction, - signature, - ); + return (transactionsContract as any) + .executeTransaction(transaction, signature) + .getABIEncodedTransactionData(); } it('should revert if the current time is past the expiration time', async () => { const transaction = await generateZeroExTransactionAsync({ @@ -345,10 +330,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ExchangeRevertErrors.TransactionErrorCode.Expired, transactionHash, ); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - transaction, - randomSignature(), - ); + const tx = transactionsContract + .executeTransaction(transaction, randomSignature()) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); it('should revert if the transaction is submitted with a gasPrice that does not equal the required gasPrice', async () => { @@ -360,13 +344,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef actualGasPrice, transaction.gasPrice, ); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - transaction, - randomSignature(), - { + const tx = transactionsContract + .executeTransaction(transaction, randomSignature()) + .awaitTransactionSuccessAsync({ gasPrice: actualGasPrice, - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); it('should revert if reentrancy occurs in the middle of an executeTransaction call and msg.sender != signer for both calls', async () => { @@ -384,13 +366,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef accounts[0], ).encode(); const expectedError = new ExchangeRevertErrors.TransactionExecutionError(outerTransactionHash, errorData); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - outerTransaction, - validSignature, - { + const tx = transactionsContract + .executeTransaction(outerTransaction, validSignature) + .awaitTransactionSuccessAsync({ from: accounts[1], // Different then the signing addresses - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); it('should revert if reentrancy occurs in the middle of an executeTransaction call and msg.sender != signer and then msg.sender == signer', async () => { @@ -408,13 +388,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef accounts[0], ).encode(); const expectedError = new ExchangeRevertErrors.TransactionExecutionError(outerTransactionHash, errorData); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - outerTransaction, - validSignature, - { + const tx = transactionsContract + .executeTransaction(outerTransaction, validSignature) + .awaitTransactionSuccessAsync({ from: accounts[1], // Different then the signing addresses - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); it('should allow reentrancy in the middle of an executeTransaction call if msg.sender == signer for both calls', async () => { @@ -426,7 +404,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef returnData: DEADBEEF_RETURN_DATA, }); return expect( - transactionsContract.executeTransaction.awaitTransactionSuccessAsync(outerTransaction, validSignature, { + transactionsContract.executeTransaction(outerTransaction, validSignature).awaitTransactionSuccessAsync({ from: accounts[0], }), ).to.be.fulfilled(''); @@ -440,7 +418,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef returnData: DEADBEEF_RETURN_DATA, }); return expect( - transactionsContract.executeTransaction.awaitTransactionSuccessAsync(outerTransaction, validSignature, { + transactionsContract.executeTransaction(outerTransaction, validSignature).awaitTransactionSuccessAsync({ from: accounts[0], }), ).to.be.fulfilled(''); @@ -451,17 +429,16 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); // Use the transaction in execute transaction. await expect( - transactionsContract.executeTransaction.awaitTransactionSuccessAsync(transaction, validSignature), + transactionsContract.executeTransaction(transaction, validSignature).awaitTransactionSuccessAsync(), ).to.be.fulfilled(''); // Use the same transaction to make another call const expectedError = new ExchangeRevertErrors.TransactionError( ExchangeRevertErrors.TransactionErrorCode.AlreadyExecuted, transactionHash, ); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - transaction, - validSignature, - ); + const tx = transactionsContract + .executeTransaction(transaction, validSignature) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); it('should revert if the signer != msg.sender and the signature is not valid', async () => { @@ -473,13 +450,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef accounts[1], INVALID_SIGNATURE, ); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - transaction, - INVALID_SIGNATURE, - { + const tx = transactionsContract + .executeTransaction(transaction, INVALID_SIGNATURE) + .awaitTransactionSuccessAsync({ from: accounts[0], - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); it('should revert if the signer == msg.sender but the delegatecall fails', async () => { @@ -494,13 +469,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef transactionHash, executableError.encode(), ); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - transaction, - randomSignature(), - { + const tx = transactionsContract + .executeTransaction(transaction, randomSignature()) + .awaitTransactionSuccessAsync({ from: accounts[1], - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); it('should revert if the signer != msg.sender and the signature is valid but the delegatecall fails', async () => { @@ -516,13 +489,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef transactionHash, executableError.encode(), ); - const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync( - transaction, - validSignature, - { + const tx = transactionsContract + .executeTransaction(transaction, validSignature) + .awaitTransactionSuccessAsync({ from: accounts[0], - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); it('should succeed with the correct return hash and event emitted when msg.sender != signer', async () => { @@ -534,14 +505,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const [result, receipt] = await transactionHelper.getResultAndReceiptAsync( - transactionsContract.executeTransaction, - transaction, - validSignature, - { from: accounts[0] }, - ); + const contractFn = transactionsContract.executeTransaction(transaction, validSignature); + const result = await contractFn.callAsync({ from: accounts[0] }); - expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result)).to.equal( + const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] }); + expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result)).to.equal( DEADBEEF_RETURN_DATA, ); @@ -565,14 +533,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef }); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const [result, receipt] = await transactionHelper.getResultAndReceiptAsync( - transactionsContract.executeTransaction, - transaction, - validSignature, - { from: accounts[0] }, - ); + const contractFn = transactionsContract.executeTransaction(transaction, validSignature); + const result = await contractFn.callAsync({ from: accounts[0] }); - expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result)).to.equal( + const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] }); + expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result)).to.equal( DEADBEEF_RETURN_DATA, ); @@ -600,7 +565,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef transactionHash, ); expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature()), + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync(), ).to.revertWith(expectedError); }); it('should revert if the gasPrice is less than required', async () => { @@ -613,7 +578,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef transaction.gasPrice, ); expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), { + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({ gasPrice: actualGasPrice, }), ).to.revertWith(expectedError); @@ -628,30 +593,30 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef transaction.gasPrice, ); expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), { + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({ gasPrice: actualGasPrice, }), ).to.revertWith(expectedError); }); it('should revert if currentContextAddress is non-zero', async () => { - await transactionsContract.setCurrentContextAddress.awaitTransactionSuccessAsync(accounts[0]); + await transactionsContract.setCurrentContextAddress(accounts[0]).awaitTransactionSuccessAsync(); const transaction = await generateZeroExTransactionAsync(); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); const expectedError = new ExchangeRevertErrors.TransactionInvalidContextError(transactionHash, accounts[0]); expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature()), + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync(), ).to.revertWith(expectedError); }); it('should revert if the transaction has already been executed', async () => { const transaction = await generateZeroExTransactionAsync(); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - await transactionsContract.setTransactionExecuted.awaitTransactionSuccessAsync(transactionHash); + await transactionsContract.setTransactionExecuted(transactionHash).awaitTransactionSuccessAsync(); const expectedError = new ExchangeRevertErrors.TransactionError( ExchangeRevertErrors.TransactionErrorCode.AlreadyExecuted, transactionHash, ); expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature()), + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync(), ).to.revertWith(expectedError); }); it('should revert if signer != msg.sender and the signature is invalid', async () => { @@ -664,7 +629,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef INVALID_SIGNATURE, ); expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, INVALID_SIGNATURE, { + transactionsContract.assertExecutableTransaction(transaction, INVALID_SIGNATURE).callAsync({ from: accounts[1], }), ).to.revertWith(expectedError); @@ -672,7 +637,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef it('should be successful if signer == msg.sender and the signature is invalid', async () => { const transaction = await generateZeroExTransactionAsync({ signerAddress: accounts[0] }); return expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, INVALID_SIGNATURE, { + transactionsContract.assertExecutableTransaction(transaction, INVALID_SIGNATURE).callAsync({ from: accounts[0], }), ).to.be.fulfilled(''); @@ -680,7 +645,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef it('should be successful if signer == msg.sender and the signature is valid', async () => { const transaction = await generateZeroExTransactionAsync({ signerAddress: accounts[0] }); return expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), { + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({ from: accounts[0], }), ).to.be.fulfilled(''); @@ -688,7 +653,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef it('should be successful if not expired, the gasPrice is correct, the tx has not been executed, currentContextAddress has not been set, signer != msg.sender, and the signature is valid', async () => { const transaction = await generateZeroExTransactionAsync({ signerAddress: accounts[0] }); return expect( - transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), { + transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({ from: accounts[1], }), ).to.be.fulfilled(''); @@ -698,30 +663,27 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef describe('setCurrentContextAddressIfRequired', () => { it('should set the currentContextAddress if signer not equal to sender', async () => { const randomAddress = hexRandom(20); - await transactionsContract.setCurrentContextAddressIfRequired.awaitTransactionSuccessAsync( - randomAddress, - randomAddress, - ); - const currentContextAddress = await transactionsContract.currentContextAddress.callAsync(); + await transactionsContract + .setCurrentContextAddressIfRequired(randomAddress, randomAddress) + .awaitTransactionSuccessAsync(); + const currentContextAddress = await transactionsContract.currentContextAddress().callAsync(); expect(currentContextAddress).to.eq(randomAddress); }); it('should not set the currentContextAddress if signer equal to sender', async () => { const randomAddress = hexRandom(20); - await transactionsContract.setCurrentContextAddressIfRequired.awaitTransactionSuccessAsync( - accounts[0], - randomAddress, - { + await transactionsContract + .setCurrentContextAddressIfRequired(accounts[0], randomAddress) + .awaitTransactionSuccessAsync({ from: accounts[0], - }, - ); - const currentContextAddress = await transactionsContract.currentContextAddress.callAsync(); + }); + const currentContextAddress = await transactionsContract.currentContextAddress().callAsync(); expect(currentContextAddress).to.eq(constants.NULL_ADDRESS); }); }); describe('getCurrentContext', () => { it('should return the sender address when there is not a saved context address', async () => { - const currentContextAddress = await transactionsContract.getCurrentContextAddress.callAsync({ + const currentContextAddress = await transactionsContract.getCurrentContextAddress().callAsync({ from: accounts[0], }); expect(currentContextAddress).to.be.eq(accounts[0]); @@ -729,10 +691,10 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef it('should return the sender address when there is a saved context address', async () => { // Set the current context address to the taker address - await transactionsContract.setCurrentContextAddress.awaitTransactionSuccessAsync(accounts[1]); + await transactionsContract.setCurrentContextAddress(accounts[1]).awaitTransactionSuccessAsync(); // Ensure that the queried current context address is the same as the address that was set. - const currentContextAddress = await transactionsContract.getCurrentContextAddress.callAsync({ + const currentContextAddress = await transactionsContract.getCurrentContextAddress().callAsync({ from: accounts[0], }); expect(currentContextAddress).to.be.eq(accounts[1]); diff --git a/contracts/exchange/test/utils/asset_balance_and_proxy_allowance_fetcher.ts b/contracts/exchange/test/utils/asset_balance_and_proxy_allowance_fetcher.ts index 84419dac4f..302d6b0dab 100644 --- a/contracts/exchange/test/utils/asset_balance_and_proxy_allowance_fetcher.ts +++ b/contracts/exchange/test/utils/asset_balance_and_proxy_allowance_fetcher.ts @@ -10,11 +10,11 @@ export class AssetBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndP this._devUtilsContract = devUtilsContract; } public async getBalanceAsync(assetData: string, userAddress: string): Promise { - const balance = await this._devUtilsContract.getBalance.callAsync(userAddress, assetData); + const balance = await this._devUtilsContract.getBalance(userAddress, assetData).callAsync(); return balance; } public async getProxyAllowanceAsync(assetData: string, userAddress: string): Promise { - const proxyAllowance = await this._devUtilsContract.getAssetProxyAllowance.callAsync(userAddress, assetData); + const proxyAllowance = await this._devUtilsContract.getAssetProxyAllowance(userAddress, assetData).callAsync(); return proxyAllowance; } } diff --git a/contracts/exchange/test/utils/asset_wrapper.ts b/contracts/exchange/test/utils/asset_wrapper.ts index fe1ffd8739..a04575213f 100644 --- a/contracts/exchange/test/utils/asset_wrapper.ts +++ b/contracts/exchange/test/utils/asset_wrapper.ts @@ -32,7 +32,7 @@ export class AssetWrapper { }); } public async getBalanceAsync(userAddress: string, assetData: string): Promise { - const proxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const proxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (proxyId) { case AssetProxyId.ERC20: { // tslint:disable-next-line:no-unnecessary-type-assertion @@ -44,9 +44,9 @@ export class AssetWrapper { // tslint:disable-next-line:no-unnecessary-type-assertion const assetWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper; // tslint:disable-next-line:no-unused-variable - const [assetProxyId, tokenAddress, tokenId] = await this._devUtils.decodeERC721AssetData.callAsync( - assetData, - ); + const [assetProxyId, tokenAddress, tokenId] = await this._devUtils + .decodeERC721AssetData(assetData) + .callAsync(); const isOwner = await assetWrapper.isOwnerAsync(userAddress, tokenAddress, tokenId); const balance = isOwner ? ONE_NFT_UNIT : ZERO_NFT_UNIT; return balance; @@ -59,7 +59,7 @@ export class AssetWrapper { assetProxyAddress, tokenAddress, tokenIds, - ] = await this._devUtils.decodeERC1155AssetData.callAsync(assetData); + ] = await this._devUtils.decodeERC1155AssetData(assetData).callAsync(); const assetWrapper = assetProxyWrapper.getContractWrapper(tokenAddress); const balances = await Promise.all( _.map(tokenIds).map(tokenId => assetWrapper.getBalanceAsync(userAddress, tokenId)), @@ -68,9 +68,9 @@ export class AssetWrapper { } case AssetProxyId.MultiAsset: { // tslint:disable-next-line:no-unused-variable - const [assetProxyId, amounts, nestedAssetData] = await this._devUtils.decodeMultiAssetData.callAsync( - assetData, - ); + const [assetProxyId, amounts, nestedAssetData] = await this._devUtils + .decodeMultiAssetData(assetData) + .callAsync(); const nestedBalances = await Promise.all( nestedAssetData.map(async _nestedAssetData => this.getBalanceAsync(userAddress, _nestedAssetData)), ); @@ -84,7 +84,7 @@ export class AssetWrapper { } } public async setBalanceAsync(userAddress: string, assetData: string, desiredBalance: BigNumber): Promise { - const proxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const proxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (proxyId) { case AssetProxyId.ERC20: { // tslint:disable-next-line:no-unnecessary-type-assertion @@ -100,9 +100,9 @@ export class AssetWrapper { // tslint:disable-next-line:no-unnecessary-type-assertion const erc721Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper; // tslint:disable-next-line:no-unused-variable - const [assetProxyId, tokenAddress, tokenId] = await this._devUtils.decodeERC721AssetData.callAsync( - assetData, - ); + const [assetProxyId, tokenAddress, tokenId] = await this._devUtils + .decodeERC721AssetData(assetData) + .callAsync(); const doesTokenExist = erc721Wrapper.doesTokenExistAsync(tokenAddress, tokenId); if (!doesTokenExist && desiredBalance.gte(1)) { await erc721Wrapper.mintAsync(tokenAddress, tokenId, userAddress); @@ -134,7 +134,7 @@ export class AssetWrapper { tokenAddress, tokenIds, tokenValues, - ] = await this._devUtils.decodeERC1155AssetData.callAsync(assetData); + ] = await this._devUtils.decodeERC1155AssetData(assetData).callAsync(); const assetWrapper = assetProxyWrapper.getContractWrapper(tokenAddress); const tokenValuesSum = BigNumber.sum(...tokenValues); let tokenValueRatios = tokenValues; @@ -197,9 +197,9 @@ export class AssetWrapper { } case AssetProxyId.MultiAsset: { // tslint:disable-next-line:no-unused-variable - const [assetProxyId, amounts, nestedAssetData] = await this._devUtils.decodeMultiAssetData.callAsync( - assetData, - ); + const [assetProxyId, amounts, nestedAssetData] = await this._devUtils + .decodeMultiAssetData(assetData) + .callAsync(); const amountsSum = BigNumber.sum(...amounts); let assetAmountRatios = amounts; if (!amountsSum.eq(0)) { @@ -220,7 +220,7 @@ export class AssetWrapper { assetData: string, desiredBalance: BigNumber, ): Promise { - const proxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const proxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (proxyId) { case AssetProxyId.ERC20: case AssetProxyId.ERC721: @@ -235,7 +235,7 @@ export class AssetWrapper { } } public async getProxyAllowanceAsync(userAddress: string, assetData: string): Promise { - const proxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const proxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (proxyId) { case AssetProxyId.ERC20: { // tslint:disable-next-line:no-unnecessary-type-assertion @@ -247,9 +247,9 @@ export class AssetWrapper { // tslint:disable-next-line:no-unnecessary-type-assertion const assetWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper; // tslint:disable-next-line:no-unused-variable - const [assetProxyId, tokenAddress, tokenId] = await this._devUtils.decodeERC721AssetData.callAsync( - assetData, - ); + const [assetProxyId, tokenAddress, tokenId] = await this._devUtils + .decodeERC721AssetData(assetData) + .callAsync(); const isProxyApprovedForAll = await assetWrapper.isProxyApprovedForAllAsync(userAddress, tokenAddress); if (isProxyApprovedForAll) { return constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS; @@ -263,9 +263,9 @@ export class AssetWrapper { // tslint:disable-next-line:no-unnecessary-type-assertion const assetProxyWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC1155ProxyWrapper; // tslint:disable-next-line:no-unused-variable - const [assetProxyAddress, tokenAddress] = await this._devUtils.decodeERC1155AssetData.callAsync( - assetData, - ); + const [assetProxyAddress, tokenAddress] = await this._devUtils + .decodeERC1155AssetData(assetData) + .callAsync(); const isApprovedForAll = await assetProxyWrapper.isProxyApprovedForAllAsync(userAddress, tokenAddress); if (!isApprovedForAll) { // ERC1155 is all or nothing. @@ -275,9 +275,9 @@ export class AssetWrapper { } case AssetProxyId.MultiAsset: { // tslint:disable-next-line:no-unused-variable - const [assetProxyId, amounts, nestedAssetData] = await this._devUtils.decodeMultiAssetData.callAsync( - assetData, - ); + const [assetProxyId, amounts, nestedAssetData] = await this._devUtils + .decodeMultiAssetData(assetData) + .callAsync(); const allowances = await Promise.all( nestedAssetData.map(async _nestedAssetData => this.getProxyAllowanceAsync(userAddress, _nestedAssetData), @@ -294,7 +294,7 @@ export class AssetWrapper { assetData: string, desiredAllowance: BigNumber, ): Promise { - const proxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const proxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (proxyId) { case AssetProxyId.ERC20: { // tslint:disable-next-line:no-unnecessary-type-assertion @@ -315,9 +315,9 @@ export class AssetWrapper { // tslint:disable-next-line:no-unnecessary-type-assertion const erc721Wrapper = this._proxyIdToAssetWrappers[proxyId] as ERC721Wrapper; // tslint:disable-next-line:no-unused-variable - const [assetProxyId, tokenAddress, tokenId] = await this._devUtils.decodeERC721AssetData.callAsync( - assetData, - ); + const [assetProxyId, tokenAddress, tokenId] = await this._devUtils + .decodeERC721AssetData(assetData) + .callAsync(); const doesTokenExist = await erc721Wrapper.doesTokenExistAsync(tokenAddress, tokenId); if (!doesTokenExist) { @@ -352,9 +352,9 @@ export class AssetWrapper { // tslint:disable-next-line:no-unnecessary-type-assertion const assetProxyWrapper = this._proxyIdToAssetWrappers[proxyId] as ERC1155ProxyWrapper; // tslint:disable-next-line:no-unused-variable - const [assetProxyAddress, tokenAddress] = await this._devUtils.decodeERC1155AssetData.callAsync( - assetData, - ); + const [assetProxyAddress, tokenAddress] = await this._devUtils + .decodeERC1155AssetData(assetData) + .callAsync(); // ERC1155 allowances are all or nothing. const shouldApprovedForAll = desiredAllowance.gt(0); const currentAllowance = await this.getProxyAllowanceAsync(userAddress, assetData); @@ -369,9 +369,9 @@ export class AssetWrapper { } case AssetProxyId.MultiAsset: { // tslint:disable-next-line:no-unused-variable - const [assetProxyId, amounts, nestedAssetData] = await this._devUtils.decodeMultiAssetData.callAsync( - assetData, - ); + const [assetProxyId, amounts, nestedAssetData] = await this._devUtils + .decodeMultiAssetData(assetData) + .callAsync(); await Promise.all( nestedAssetData.map(async _nestedAssetData => this.setProxyAllowanceAsync(userAddress, _nestedAssetData, desiredAllowance), diff --git a/contracts/exchange/test/utils/exchange_transfer_simulator.ts b/contracts/exchange/test/utils/exchange_transfer_simulator.ts index 8b2a49bb8c..03130c0bfb 100644 --- a/contracts/exchange/test/utils/exchange_transfer_simulator.ts +++ b/contracts/exchange/test/utils/exchange_transfer_simulator.ts @@ -77,7 +77,7 @@ export class ExchangeTransferSimulator { tradeSide: TradeSide, transferType: TransferType, ): Promise { - const assetProxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData); + const assetProxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync(); switch (assetProxyId) { case AssetProxyId.ERC1155: case AssetProxyId.ERC20: @@ -110,7 +110,7 @@ export class ExchangeTransferSimulator { break; } case AssetProxyId.MultiAsset: { - const decodedAssetData = await this._devUtils.decodeMultiAssetData.callAsync(assetData); + const decodedAssetData = await this._devUtils.decodeMultiAssetData(assetData).callAsync(); await this._decreaseBalanceAsync(assetData, from, amountInBaseUnits); await this._increaseBalanceAsync(assetData, to, amountInBaseUnits); for (const [index, nestedAssetDataElement] of decodedAssetData[2].entries()) { diff --git a/contracts/exchange/test/utils/exchange_wrapper.ts b/contracts/exchange/test/utils/exchange_wrapper.ts index 615467c431..f11ffed1cb 100644 --- a/contracts/exchange/test/utils/exchange_wrapper.ts +++ b/contracts/exchange/test/utils/exchange_wrapper.ts @@ -24,17 +24,14 @@ export class ExchangeWrapper { opts: { takerAssetFillAmount?: BigNumber } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const txReceipt = await this.exchangeContract.fillOrder.awaitTransactionSuccessAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from }, - ); + const txReceipt = await this.exchangeContract + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .awaitTransactionSuccessAsync({ from }); return txReceipt; } public async cancelOrderAsync(signedOrder: SignedOrder, from: string): Promise { const params = orderUtils.createCancel(signedOrder); - const txReceipt = await this.exchangeContract.cancelOrder.awaitTransactionSuccessAsync(params.order, { from }); + const txReceipt = await this.exchangeContract.cancelOrder(params.order).awaitTransactionSuccessAsync({ from }); return txReceipt; } public async fillOrKillOrderAsync( @@ -43,12 +40,9 @@ export class ExchangeWrapper { opts: { takerAssetFillAmount?: BigNumber; gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const txReceipt = await this.exchangeContract.fillOrKillOrder.awaitTransactionSuccessAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from, gasPrice: opts.gasPrice }, - ); + const txReceipt = await this.exchangeContract + .fillOrKillOrder(params.order, params.takerAssetFillAmount, params.signature) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); return txReceipt; } public async batchFillOrdersAsync( @@ -56,111 +50,113 @@ export class ExchangeWrapper { from: string, opts: { takerAssetFillAmounts?: BigNumber[]; gasPrice?: BigNumber } = {}, ): Promise { - return this.exchangeContract.batchFillOrders.awaitTransactionSuccessAsync( - orders, - opts.takerAssetFillAmounts === undefined - ? orders.map(signedOrder => signedOrder.takerAssetAmount) - : opts.takerAssetFillAmounts, - orders.map(signedOrder => signedOrder.signature), - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchFillOrders( + orders, + opts.takerAssetFillAmounts === undefined + ? orders.map(signedOrder => signedOrder.takerAssetAmount) + : opts.takerAssetFillAmounts, + orders.map(signedOrder => signedOrder.signature), + ) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async batchFillOrKillOrdersAsync( orders: SignedOrder[], from: string, opts: { takerAssetFillAmounts?: BigNumber[]; gasPrice?: BigNumber } = {}, ): Promise { - return this.exchangeContract.batchFillOrKillOrders.awaitTransactionSuccessAsync( - orders, - opts.takerAssetFillAmounts === undefined - ? orders.map(signedOrder => signedOrder.takerAssetAmount) - : opts.takerAssetFillAmounts, - orders.map(signedOrder => signedOrder.signature), - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchFillOrKillOrders( + orders, + opts.takerAssetFillAmounts === undefined + ? orders.map(signedOrder => signedOrder.takerAssetAmount) + : opts.takerAssetFillAmounts, + orders.map(signedOrder => signedOrder.signature), + ) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async batchFillOrdersNoThrowAsync( orders: SignedOrder[], from: string, opts: { takerAssetFillAmounts?: BigNumber[]; gas?: number; gasPrice?: BigNumber } = {}, ): Promise { - return this.exchangeContract.batchFillOrdersNoThrow.awaitTransactionSuccessAsync( - orders, - opts.takerAssetFillAmounts === undefined - ? orders.map(signedOrder => signedOrder.takerAssetAmount) - : opts.takerAssetFillAmounts, - orders.map(signedOrder => signedOrder.signature), - { from, gas: opts.gas, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchFillOrdersNoThrow( + orders, + opts.takerAssetFillAmounts === undefined + ? orders.map(signedOrder => signedOrder.takerAssetAmount) + : opts.takerAssetFillAmounts, + orders.map(signedOrder => signedOrder.signature), + ) + .awaitTransactionSuccessAsync({ from, gas: opts.gas, gasPrice: opts.gasPrice }); } public async marketSellOrdersNoThrowAsync( orders: SignedOrder[], from: string, opts: { takerAssetFillAmount: BigNumber; gas?: number; gasPrice?: BigNumber }, ): Promise { - return this.exchangeContract.marketSellOrdersNoThrow.awaitTransactionSuccessAsync( - orders, - opts.takerAssetFillAmount, - orders.map(signedOrder => signedOrder.signature), - { from, gas: opts.gas, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .marketSellOrdersNoThrow( + orders, + opts.takerAssetFillAmount, + orders.map(signedOrder => signedOrder.signature), + ) + .awaitTransactionSuccessAsync({ from, gas: opts.gas, gasPrice: opts.gasPrice }); } public async marketBuyOrdersNoThrowAsync( orders: SignedOrder[], from: string, opts: { makerAssetFillAmount: BigNumber; gas?: number; gasPrice?: BigNumber }, ): Promise { - return this.exchangeContract.marketBuyOrdersNoThrow.awaitTransactionSuccessAsync( - orders, - opts.makerAssetFillAmount, - orders.map(signedOrder => signedOrder.signature), - { from, gas: opts.gas }, - ); + return this.exchangeContract + .marketBuyOrdersNoThrow(orders, opts.makerAssetFillAmount, orders.map(signedOrder => signedOrder.signature)) + .awaitTransactionSuccessAsync({ from, gas: opts.gas }); } public async marketSellOrdersFillOrKillAsync( orders: SignedOrder[], from: string, opts: { takerAssetFillAmount: BigNumber; gas?: number }, ): Promise { - return this.exchangeContract.marketSellOrdersFillOrKill.awaitTransactionSuccessAsync( - orders, - opts.takerAssetFillAmount, - orders.map(signedOrder => signedOrder.signature), - { from, gas: opts.gas }, - ); + return this.exchangeContract + .marketSellOrdersFillOrKill( + orders, + opts.takerAssetFillAmount, + orders.map(signedOrder => signedOrder.signature), + ) + .awaitTransactionSuccessAsync({ from, gas: opts.gas }); } public async marketBuyOrdersFillOrKillAsync( orders: SignedOrder[], from: string, opts: { makerAssetFillAmount: BigNumber; gas?: number }, ): Promise { - return this.exchangeContract.marketBuyOrdersFillOrKill.awaitTransactionSuccessAsync( - orders, - opts.makerAssetFillAmount, - orders.map(signedOrder => signedOrder.signature), - { from, gas: opts.gas }, - ); + return this.exchangeContract + .marketBuyOrdersFillOrKill( + orders, + opts.makerAssetFillAmount, + orders.map(signedOrder => signedOrder.signature), + ) + .awaitTransactionSuccessAsync({ from, gas: opts.gas }); } public async batchCancelOrdersAsync( orders: SignedOrder[], from: string, ): Promise { - return this.exchangeContract.batchCancelOrders.awaitTransactionSuccessAsync(orders, { from }); + return this.exchangeContract.batchCancelOrders(orders).awaitTransactionSuccessAsync({ from }); } public async cancelOrdersUpToAsync(salt: BigNumber, from: string): Promise { - const txReceipt = await this.exchangeContract.cancelOrdersUpTo.awaitTransactionSuccessAsync(salt, { from }); + const txReceipt = await this.exchangeContract.cancelOrdersUpTo(salt).awaitTransactionSuccessAsync({ from }); return txReceipt; } public async registerAssetProxyAsync( assetProxyAddress: string, from: string, ): Promise { - const txReceipt = await this.exchangeContract.registerAssetProxy.awaitTransactionSuccessAsync( - assetProxyAddress, - { + const txReceipt = await this.exchangeContract + .registerAssetProxy(assetProxyAddress) + .awaitTransactionSuccessAsync({ from, - }, - ); + }); return txReceipt; } public async executeTransactionAsync( @@ -168,11 +164,9 @@ export class ExchangeWrapper { from: string, opts: { gasPrice?: BigNumber } = {}, ): Promise { - return this.exchangeContract.executeTransaction.awaitTransactionSuccessAsync( - signedTransaction, - signedTransaction.signature, - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .executeTransaction(signedTransaction, signedTransaction.signature) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async batchExecuteTransactionsAsync( signedTransactions: SignedZeroExTransaction[], @@ -180,29 +174,27 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const signatures = signedTransactions.map(signedTransaction => signedTransaction.signature); - return this.exchangeContract.batchExecuteTransactions.awaitTransactionSuccessAsync( - signedTransactions, - signatures, - { + return this.exchangeContract + .batchExecuteTransactions(signedTransactions, signatures) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice, - }, - ); + }); } public async getTakerAssetFilledAmountAsync(orderHashHex: string): Promise { - const filledAmount = await this.exchangeContract.filled.callAsync(orderHashHex); + const filledAmount = await this.exchangeContract.filled(orderHashHex).callAsync(); return filledAmount; } public async isCancelledAsync(orderHashHex: string): Promise { - const isCancelled = await this.exchangeContract.cancelled.callAsync(orderHashHex); + const isCancelled = await this.exchangeContract.cancelled(orderHashHex).callAsync(); return isCancelled; } public async getOrderEpochAsync(makerAddress: string, senderAddress: string): Promise { - const orderEpoch = await this.exchangeContract.orderEpoch.callAsync(makerAddress, senderAddress); + const orderEpoch = await this.exchangeContract.orderEpoch(makerAddress, senderAddress).callAsync(); return orderEpoch; } public async getOrderInfoAsync(signedOrder: SignedOrder): Promise { - const orderInfo = await this.exchangeContract.getOrderInfo.callAsync(signedOrder); + const orderInfo = await this.exchangeContract.getOrderInfo(signedOrder).callAsync(); return orderInfo; } public async batchMatchOrdersAsync( @@ -212,26 +204,18 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createBatchMatchOrders(signedOrdersLeft, signedOrdersRight); - return this.exchangeContract.batchMatchOrders.awaitTransactionSuccessAsync( - params.leftOrders, - params.rightOrders, - params.leftSignatures, - params.rightSignatures, - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchMatchOrders(params.leftOrders, params.rightOrders, params.leftSignatures, params.rightSignatures) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async batchMatchOrdersRawAsync( params: BatchMatchOrder, from: string, opts: { gasPrice?: BigNumber } = {}, ): Promise { - return this.exchangeContract.batchMatchOrders.awaitTransactionSuccessAsync( - params.leftOrders, - params.rightOrders, - params.leftSignatures, - params.rightSignatures, - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchMatchOrders(params.leftOrders, params.rightOrders, params.leftSignatures, params.rightSignatures) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async getBatchMatchOrdersResultsAsync( signedOrdersLeft: SignedOrder[], @@ -240,13 +224,9 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createBatchMatchOrders(signedOrdersLeft, signedOrdersRight); - const batchMatchedFillResults = await this.exchangeContract.batchMatchOrders.callAsync( - params.leftOrders, - params.rightOrders, - params.leftSignatures, - params.rightSignatures, - { from, gasPrice: opts.gasPrice }, - ); + const batchMatchedFillResults = await this.exchangeContract + .batchMatchOrders(params.leftOrders, params.rightOrders, params.leftSignatures, params.rightSignatures) + .callAsync({ from, gasPrice: opts.gasPrice }); return batchMatchedFillResults; } public async batchMatchOrdersWithMaximalFillAsync( @@ -256,26 +236,28 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createBatchMatchOrders(signedOrdersLeft, signedOrdersRight); - return this.exchangeContract.batchMatchOrdersWithMaximalFill.awaitTransactionSuccessAsync( - params.leftOrders, - params.rightOrders, - params.leftSignatures, - params.rightSignatures, - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchMatchOrdersWithMaximalFill( + params.leftOrders, + params.rightOrders, + params.leftSignatures, + params.rightSignatures, + ) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async batchMatchOrdersWithMaximalFillRawAsync( params: BatchMatchOrder, from: string, opts: { gasPrice?: BigNumber } = {}, ): Promise { - return this.exchangeContract.batchMatchOrdersWithMaximalFill.awaitTransactionSuccessAsync( - params.leftOrders, - params.rightOrders, - params.leftSignatures, - params.rightSignatures, - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .batchMatchOrdersWithMaximalFill( + params.leftOrders, + params.rightOrders, + params.leftSignatures, + params.rightSignatures, + ) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async getBatchMatchOrdersWithMaximalFillResultsAsync( signedOrdersLeft: SignedOrder[], @@ -284,13 +266,14 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createBatchMatchOrders(signedOrdersLeft, signedOrdersRight); - const batchMatchedFillResults = await this.exchangeContract.batchMatchOrdersWithMaximalFill.callAsync( - params.leftOrders, - params.rightOrders, - params.leftSignatures, - params.rightSignatures, - { from, gasPrice: opts.gasPrice }, - ); + const batchMatchedFillResults = await this.exchangeContract + .batchMatchOrdersWithMaximalFill( + params.leftOrders, + params.rightOrders, + params.leftSignatures, + params.rightSignatures, + ) + .callAsync({ from, gasPrice: opts.gasPrice }); return batchMatchedFillResults; } public async matchOrdersAsync( @@ -300,13 +283,9 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight); - const txReceipt = await this.exchangeContract.matchOrders.awaitTransactionSuccessAsync( - params.left, - params.right, - params.leftSignature, - params.rightSignature, - { from, gasPrice: opts.gasPrice }, - ); + const txReceipt = await this.exchangeContract + .matchOrders(params.left, params.right, params.leftSignature, params.rightSignature) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); return txReceipt; } public async getMatchOrdersResultsAsync( @@ -316,13 +295,9 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight); - const matchedFillResults = await this.exchangeContract.matchOrders.callAsync( - params.left, - params.right, - params.leftSignature, - params.rightSignature, - { from, gasPrice: opts.gasPrice }, - ); + const matchedFillResults = await this.exchangeContract + .matchOrders(params.left, params.right, params.leftSignature, params.rightSignature) + .callAsync({ from, gasPrice: opts.gasPrice }); return matchedFillResults; } public async matchOrdersWithMaximalFillAsync( @@ -332,13 +307,9 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight); - return this.exchangeContract.matchOrdersWithMaximalFill.awaitTransactionSuccessAsync( - params.left, - params.right, - params.leftSignature, - params.rightSignature, - { from, gasPrice: opts.gasPrice }, - ); + return this.exchangeContract + .matchOrdersWithMaximalFill(params.left, params.right, params.leftSignature, params.rightSignature) + .awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice }); } public async getMatchOrdersWithMaximalFillResultsAsync( signedOrderLeft: SignedOrder, @@ -347,13 +318,9 @@ export class ExchangeWrapper { opts: { gasPrice?: BigNumber }, ): Promise { const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight); - const matchedFillResults = await this.exchangeContract.matchOrdersWithMaximalFill.callAsync( - params.left, - params.right, - params.leftSignature, - params.rightSignature, - { from, gasPrice: opts.gasPrice }, - ); + const matchedFillResults = await this.exchangeContract + .matchOrdersWithMaximalFill(params.left, params.right, params.leftSignature, params.rightSignature) + .callAsync({ from, gasPrice: opts.gasPrice }); return matchedFillResults; } public async getFillOrderResultsAsync( @@ -362,21 +329,16 @@ export class ExchangeWrapper { opts: { takerAssetFillAmount?: BigNumber; gasPrice?: BigNumber } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const fillResults = await this.exchangeContract.fillOrder.callAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from, gasPrice: opts.gasPrice }, - ); + const fillResults = await this.exchangeContract + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .callAsync({ from, gasPrice: opts.gasPrice }); return fillResults; } public abiEncodeFillOrder(signedOrder: SignedOrder, opts: { takerAssetFillAmount?: BigNumber } = {}): string { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const data = this.exchangeContract.fillOrder.getABIEncodedTransactionData( - params.order, - params.takerAssetFillAmount, - params.signature, - ); + const data = this.exchangeContract + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .getABIEncodedTransactionData(); return data; } public abiDecodeFillOrder(data: string): AbiDecodedFillOrderData { diff --git a/contracts/exchange/test/utils/fill_order_combinatorial_utils.ts b/contracts/exchange/test/utils/fill_order_combinatorial_utils.ts index 3fa9f6ccd1..53382e7eee 100644 --- a/contracts/exchange/test/utils/fill_order_combinatorial_utils.ts +++ b/contracts/exchange/test/utils/fill_order_combinatorial_utils.ts @@ -128,37 +128,37 @@ export async function fillOrderCombinatorialUtilsFactoryAsync( await exchangeWrapper.registerAssetProxyAsync(erc1155Proxy.address, ownerAddress); await exchangeWrapper.registerAssetProxyAsync(multiAssetProxy.address, ownerAddress); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, { + await erc20Proxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({ from: ownerAddress, }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, { + await erc721Proxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({ from: ownerAddress, }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, { + await erc1155Proxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({ from: ownerAddress, }); - await multiAssetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, { + await multiAssetProxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({ from: ownerAddress, }); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: ownerAddress }); + await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: ownerAddress }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { + await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: ownerAddress, }); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { + await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: ownerAddress, }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { from: ownerAddress }); + await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: ownerAddress }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { from: ownerAddress }); + await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: ownerAddress }); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, { from: ownerAddress }); + await multiAssetProxy.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: ownerAddress }); const orderFactory = new OrderFactoryFromScenario( devUtils, diff --git a/contracts/exchange/test/utils/isolated_exchange_wrapper.ts b/contracts/exchange/test/utils/isolated_exchange_wrapper.ts index 0b94a9af97..0085bea334 100644 --- a/contracts/exchange/test/utils/isolated_exchange_wrapper.ts +++ b/contracts/exchange/test/utils/isolated_exchange_wrapper.ts @@ -1,10 +1,4 @@ -import { - constants, - filterLogsToArguments, - MutatorContractFunction, - TransactionHelper, - txDefaults as testTxDefaults, -} from '@0x/contracts-test-utils'; +import { constants, filterLogsToArguments, txDefaults as testTxDefaults } from '@0x/contracts-test-utils'; import { orderHashUtils } from '@0x/order-utils'; import { FillResults, Order, OrderInfo, SignatureType } from '@0x/types'; import { BigNumber } from '@0x/utils'; @@ -41,7 +35,6 @@ export const DEFAULT_BAD_SIGNATURE = createBadSignature(); export class IsolatedExchangeWrapper { public static readonly CHAIN_ID = 1337; public readonly instance: IsolatedExchangeContract; - public readonly txHelper: TransactionHelper; public lastTxEvents: IsolatedExchangeEvents = createEmptyEvents(); public lastTxBalanceChanges: AssetBalances = {}; @@ -71,19 +64,18 @@ export class IsolatedExchangeWrapper { public constructor(web3Wrapper: Web3Wrapper, instance: IsolatedExchangeContract) { this.instance = instance; - this.txHelper = new TransactionHelper(web3Wrapper, artifacts); } public async getTakerAssetFilledAmountAsync(order: Order): Promise { - return this.instance.filled.callAsync(this.getOrderHash(order)); + return this.instance.filled(this.getOrderHash(order)).callAsync(); } public async cancelOrderAsync(order: Order, txOpts?: TxData): Promise { - await this.instance.cancelOrder.awaitTransactionSuccessAsync(order, txOpts); + await this.instance.cancelOrder(order).awaitTransactionSuccessAsync(txOpts); } public async cancelOrdersUpToAsync(epoch: BigNumber, txOpts?: TxData): Promise { - await this.instance.cancelOrdersUpTo.awaitTransactionSuccessAsync(epoch, txOpts); + await this.instance.cancelOrdersUpTo(epoch).awaitTransactionSuccessAsync(txOpts); } public async fillOrderAsync( @@ -92,13 +84,14 @@ export class IsolatedExchangeWrapper { signature: string = DEFAULT_GOOD_SIGNATURE, txOpts?: TxData, ): Promise { - return this._runFillContractFunctionAsync( - this.instance.fillOrder, - order, - new BigNumber(takerAssetFillAmount), - signature, - txOpts, - ); + this.lastTxEvents = createEmptyEvents(); + this.lastTxBalanceChanges = {}; + const fillOrderFn = this.instance.fillOrder(order, new BigNumber(takerAssetFillAmount), signature); + const result = await fillOrderFn.callAsync(); + const receipt = await fillOrderFn.awaitTransactionSuccessAsync(txOpts); + this.lastTxEvents = extractEvents(receipt.logs); + this.lastTxBalanceChanges = getBalanceChangesFromTransferFromCalls(this.lastTxEvents.transferFromCalls); + return result; } public getOrderHash(order: Order): string { @@ -110,7 +103,7 @@ export class IsolatedExchangeWrapper { } public async getOrderInfoAsync(order: Order): Promise { - return this.instance.getOrderInfo.callAsync(order); + return this.instance.getOrderInfo(order).callAsync(); } public getBalanceChange(assetData: string, address: string): BigNumber { @@ -122,23 +115,6 @@ export class IsolatedExchangeWrapper { } return constants.ZERO_AMOUNT; } - - protected async _runFillContractFunctionAsync< - TCallAsyncArgs extends any[], - TAwaitTransactionSuccessAsyncArgs extends any[], - TResult - >( - contractFunction: MutatorContractFunction, - // tslint:disable-next-line: trailing-comma - ...args: TAwaitTransactionSuccessAsyncArgs - ): Promise { - this.lastTxEvents = createEmptyEvents(); - this.lastTxBalanceChanges = {}; - const [result, receipt] = await this.txHelper.getResultAndReceiptAsync(contractFunction, ...args); - this.lastTxEvents = extractEvents(receipt.logs); - this.lastTxBalanceChanges = getBalanceChangesFromTransferFromCalls(this.lastTxEvents.transferFromCalls); - return result; - } } /** diff --git a/contracts/exchange/test/utils/match_order_tester.ts b/contracts/exchange/test/utils/match_order_tester.ts index 3fe9ff906a..e8ec9a42b0 100644 --- a/contracts/exchange/test/utils/match_order_tester.ts +++ b/contracts/exchange/test/utils/match_order_tester.ts @@ -631,11 +631,11 @@ async function transferAssetAsync( matchResults: MatchResults, devUtils: DevUtilsContract, ): Promise { - const assetProxyId = await devUtils.decodeAssetProxyId.callAsync(assetData); + const assetProxyId = await devUtils.decodeAssetProxyId(assetData).callAsync(); switch (assetProxyId) { case AssetProxyId.ERC20: { // tslint:disable-next-line:no-unused-variable - const [proxyId, assetAddress] = await devUtils.decodeERC20AssetData.callAsync(assetData); // tslint:disable-line-no-unused-variable + const [proxyId, assetAddress] = await devUtils.decodeERC20AssetData(assetData).callAsync(); // tslint:disable-line-no-unused-variable const fromBalances = matchResults.balances.erc20[fromAddress]; const toBalances = matchResults.balances.erc20[toAddress]; fromBalances[assetAddress] = fromBalances[assetAddress].minus(amount); @@ -644,7 +644,7 @@ async function transferAssetAsync( } case AssetProxyId.ERC721: { // tslint:disable-next-line:no-unused-variable - const [proxyId, assetAddress, tokenId] = await devUtils.decodeERC721AssetData.callAsync(assetData); // tslint:disable-line-no-unused-variable + const [proxyId, assetAddress, tokenId] = await devUtils.decodeERC721AssetData(assetData).callAsync(); // tslint:disable-line-no-unused-variable const fromTokens = matchResults.balances.erc721[fromAddress][assetAddress]; const toTokens = matchResults.balances.erc721[toAddress][assetAddress]; if (amount.gte(1)) { @@ -658,9 +658,9 @@ async function transferAssetAsync( } case AssetProxyId.ERC1155: { // tslint:disable-next-line:no-unused-variable - const [proxyId, assetAddress, tokenIds, tokenValues] = await devUtils.decodeERC1155AssetData.callAsync( - assetData, - ); + const [proxyId, assetAddress, tokenIds, tokenValues] = await devUtils + .decodeERC1155AssetData(assetData) + .callAsync(); const fromBalances = matchResults.balances.erc1155[fromAddress][assetAddress]; const toBalances = matchResults.balances.erc1155[toAddress][assetAddress]; for (const i of _.times(tokenIds.length)) { @@ -685,7 +685,7 @@ async function transferAssetAsync( } case AssetProxyId.MultiAsset: { // tslint:disable-next-line:no-unused-variable - const [proxyId, amounts, nestedAssetData] = await devUtils.decodeMultiAssetData.callAsync(assetData); // tslint:disable-line-no-unused-variable + const [proxyId, amounts, nestedAssetData] = await devUtils.decodeMultiAssetData(assetData).callAsync(); // tslint:disable-line-no-unused-variable for (const i of _.times(amounts.length)) { const nestedAmount = amount.times(amounts[i]); const _nestedAssetData = nestedAssetData[i]; diff --git a/contracts/exchange/test/utils/order_factory_from_scenario.ts b/contracts/exchange/test/utils/order_factory_from_scenario.ts index b25a5a85ab..9b0f510f25 100644 --- a/contracts/exchange/test/utils/order_factory_from_scenario.ts +++ b/contracts/exchange/test/utils/order_factory_from_scenario.ts @@ -96,52 +96,59 @@ export class OrderFactoryFromScenario { switch (orderScenario.makerAssetDataScenario) { case AssetDataScenario.ERC20EighteenDecimals: - makerAssetData = await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20EighteenDecimalTokenAddresses[0], - ); + makerAssetData = await this._devUtils + .encodeERC20AssetData(this._erc20EighteenDecimalTokenAddresses[0]) + .callAsync(); break; case AssetDataScenario.ERC20FiveDecimals: - makerAssetData = await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20FiveDecimalTokenAddresses[0], - ); + makerAssetData = await this._devUtils + .encodeERC20AssetData(this._erc20FiveDecimalTokenAddresses[0]) + .callAsync(); break; case AssetDataScenario.ERC721: - makerAssetData = await this._devUtils.encodeERC721AssetData.callAsync( - this._erc721TokenAddress, - erc721MakerAssetIds[0], - ); + makerAssetData = await this._devUtils + .encodeERC721AssetData(this._erc721TokenAddress, erc721MakerAssetIds[0]) + .callAsync(); break; case AssetDataScenario.ERC20ZeroDecimals: - makerAssetData = await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20ZeroDecimalTokenAddresses[0], - ); + makerAssetData = await this._devUtils + .encodeERC20AssetData(this._erc20ZeroDecimalTokenAddresses[0]) + .callAsync(); break; case AssetDataScenario.ERC1155Fungible: - makerAssetData = await this._devUtils.encodeERC1155AssetData.callAsync( - this._erc1155TokenAddress, - [erc1155FungibleMakerTokenIds[0]], - [ONE_UNITS_ZERO_DECIMALS], - erc1155CallbackData, - ); + makerAssetData = await this._devUtils + .encodeERC1155AssetData( + this._erc1155TokenAddress, + [erc1155FungibleMakerTokenIds[0]], + [ONE_UNITS_ZERO_DECIMALS], + erc1155CallbackData, + ) + .callAsync(); break; case AssetDataScenario.ERC1155NonFungible: - makerAssetData = await this._devUtils.encodeERC1155AssetData.callAsync( - this._erc1155TokenAddress, - [erc1155NonFungibleMakerTokenIds[0]], - [ONE_UNITS_ZERO_DECIMALS], - erc1155CallbackData, - ); + makerAssetData = await this._devUtils + .encodeERC1155AssetData( + this._erc1155TokenAddress, + [erc1155NonFungibleMakerTokenIds[0]], + [ONE_UNITS_ZERO_DECIMALS], + erc1155CallbackData, + ) + .callAsync(); break; case AssetDataScenario.MultiAssetERC20: - makerAssetData = await this._devUtils.encodeMultiAssetData.callAsync( - [ONE_UNITS_EIGHTEEN_DECIMALS, ONE_UNITS_FIVE_DECIMALS], - [ - await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20EighteenDecimalTokenAddresses[0], - ), - await this._devUtils.encodeERC20AssetData.callAsync(this._erc20FiveDecimalTokenAddresses[0]), - ], - ); + makerAssetData = await this._devUtils + .encodeMultiAssetData( + [ONE_UNITS_EIGHTEEN_DECIMALS, ONE_UNITS_FIVE_DECIMALS], + [ + await this._devUtils + .encodeERC20AssetData(this._erc20EighteenDecimalTokenAddresses[0]) + .callAsync(), + await this._devUtils + .encodeERC20AssetData(this._erc20FiveDecimalTokenAddresses[0]) + .callAsync(), + ], + ) + .callAsync(); break; default: throw errorUtils.spawnSwitchErr('AssetDataScenario', orderScenario.makerAssetDataScenario); @@ -149,52 +156,59 @@ export class OrderFactoryFromScenario { switch (orderScenario.takerAssetDataScenario) { case AssetDataScenario.ERC20EighteenDecimals: - takerAssetData = await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20EighteenDecimalTokenAddresses[1], - ); + takerAssetData = await this._devUtils + .encodeERC20AssetData(this._erc20EighteenDecimalTokenAddresses[1]) + .callAsync(); break; case AssetDataScenario.ERC20FiveDecimals: - takerAssetData = await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20FiveDecimalTokenAddresses[1], - ); + takerAssetData = await this._devUtils + .encodeERC20AssetData(this._erc20FiveDecimalTokenAddresses[1]) + .callAsync(); break; case AssetDataScenario.ERC721: - takerAssetData = await this._devUtils.encodeERC721AssetData.callAsync( - this._erc721TokenAddress, - erc721TakerAssetIds[0], - ); + takerAssetData = await this._devUtils + .encodeERC721AssetData(this._erc721TokenAddress, erc721TakerAssetIds[0]) + .callAsync(); break; case AssetDataScenario.ERC20ZeroDecimals: - takerAssetData = await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20ZeroDecimalTokenAddresses[1], - ); + takerAssetData = await this._devUtils + .encodeERC20AssetData(this._erc20ZeroDecimalTokenAddresses[1]) + .callAsync(); break; case AssetDataScenario.ERC1155Fungible: - takerAssetData = await this._devUtils.encodeERC1155AssetData.callAsync( - this._erc1155TokenAddress, - [erc1155FungibleTakerTokenIds[1]], - [ONE_UNITS_ZERO_DECIMALS], - erc1155CallbackData, - ); + takerAssetData = await this._devUtils + .encodeERC1155AssetData( + this._erc1155TokenAddress, + [erc1155FungibleTakerTokenIds[1]], + [ONE_UNITS_ZERO_DECIMALS], + erc1155CallbackData, + ) + .callAsync(); break; case AssetDataScenario.ERC1155NonFungible: - takerAssetData = await this._devUtils.encodeERC1155AssetData.callAsync( - this._erc1155TokenAddress, - [erc1155NonFungibleTakerTokenIds[0]], - [ONE_UNITS_ZERO_DECIMALS], - erc1155CallbackData, - ); + takerAssetData = await this._devUtils + .encodeERC1155AssetData( + this._erc1155TokenAddress, + [erc1155NonFungibleTakerTokenIds[0]], + [ONE_UNITS_ZERO_DECIMALS], + erc1155CallbackData, + ) + .callAsync(); break; case AssetDataScenario.MultiAssetERC20: - takerAssetData = await this._devUtils.encodeMultiAssetData.callAsync( - [ONE_UNITS_EIGHTEEN_DECIMALS, ONE_UNITS_FIVE_DECIMALS], - [ - await this._devUtils.encodeERC20AssetData.callAsync( - this._erc20EighteenDecimalTokenAddresses[1], - ), - await this._devUtils.encodeERC20AssetData.callAsync(this._erc20FiveDecimalTokenAddresses[1]), - ], - ); + takerAssetData = await this._devUtils + .encodeMultiAssetData( + [ONE_UNITS_EIGHTEEN_DECIMALS, ONE_UNITS_FIVE_DECIMALS], + [ + await this._devUtils + .encodeERC20AssetData(this._erc20EighteenDecimalTokenAddresses[1]) + .callAsync(), + await this._devUtils + .encodeERC20AssetData(this._erc20FiveDecimalTokenAddresses[1]) + .callAsync(), + ], + ) + .callAsync(); break; default: throw errorUtils.spawnSwitchErr('AssetDataScenario', orderScenario.takerAssetDataScenario); @@ -327,53 +341,61 @@ export class OrderFactoryFromScenario { case FeeAssetDataScenario.ERC20EighteenDecimals: return [ feeAmount, - await this._devUtils.encodeERC20AssetData.callAsync(erc20EighteenDecimalTokenAddress), + await this._devUtils.encodeERC20AssetData(erc20EighteenDecimalTokenAddress).callAsync(), ]; case FeeAssetDataScenario.ERC20FiveDecimals: return [ feeAmount, - await this._devUtils.encodeERC20AssetData.callAsync(erc20FiveDecimalTokenAddress), + await this._devUtils.encodeERC20AssetData(erc20FiveDecimalTokenAddress).callAsync(), ]; case FeeAssetDataScenario.ERC20ZeroDecimals: return [ feeAmount, - await this._devUtils.encodeERC20AssetData.callAsync(erc20ZeroDecimalTokenAddress), + await this._devUtils.encodeERC20AssetData(erc20ZeroDecimalTokenAddress).callAsync(), ]; case FeeAssetDataScenario.ERC721: return [ feeAmount, - await this._devUtils.encodeERC721AssetData.callAsync(this._erc721TokenAddress, erc721AssetId), + await this._devUtils.encodeERC721AssetData(this._erc721TokenAddress, erc721AssetId).callAsync(), ]; case FeeAssetDataScenario.ERC1155Fungible: return [ feeAmount, - await this._devUtils.encodeERC1155AssetData.callAsync( - this._erc1155TokenAddress, - [erc1155FungibleTokenId], - [ONE_UNITS_ZERO_DECIMALS], - erc1155CallbackData, - ), + await this._devUtils + .encodeERC1155AssetData( + this._erc1155TokenAddress, + [erc1155FungibleTokenId], + [ONE_UNITS_ZERO_DECIMALS], + erc1155CallbackData, + ) + .callAsync(), ]; case FeeAssetDataScenario.ERC1155NonFungible: return [ feeAmount, - await this._devUtils.encodeERC1155AssetData.callAsync( - this._erc1155TokenAddress, - [erc1155NonFungibleAssetId], - [ONE_UNITS_ZERO_DECIMALS], - erc1155CallbackData, - ), + await this._devUtils + .encodeERC1155AssetData( + this._erc1155TokenAddress, + [erc1155NonFungibleAssetId], + [ONE_UNITS_ZERO_DECIMALS], + erc1155CallbackData, + ) + .callAsync(), ]; case FeeAssetDataScenario.MultiAssetERC20: return [ feeAmount, - await this._devUtils.encodeMultiAssetData.callAsync( - [POINT_ZERO_FIVE_UNITS_EIGHTEEN_DECIMALS, POINT_ZERO_FIVE_UNITS_FIVE_DECIMALS], - [ - await this._devUtils.encodeERC20AssetData.callAsync(erc20EighteenDecimalTokenAddress), - await this._devUtils.encodeERC20AssetData.callAsync(erc20FiveDecimalTokenAddress), - ], - ), + await this._devUtils + .encodeMultiAssetData( + [POINT_ZERO_FIVE_UNITS_EIGHTEEN_DECIMALS, POINT_ZERO_FIVE_UNITS_FIVE_DECIMALS], + [ + await this._devUtils + .encodeERC20AssetData(erc20EighteenDecimalTokenAddress) + .callAsync(), + await this._devUtils.encodeERC20AssetData(erc20FiveDecimalTokenAddress).callAsync(), + ], + ) + .callAsync(), ]; default: throw errorUtils.spawnSwitchErr('FeeAssetDataScenario', feeAssetDataScenario); diff --git a/contracts/exchange/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts b/contracts/exchange/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts index c85d117919..172e8d0203 100644 --- a/contracts/exchange/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts +++ b/contracts/exchange/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts @@ -13,13 +13,15 @@ export class SimpleERC20BalanceAndProxyAllowanceFetcher implements AbstractBalan public async getBalanceAsync(_assetData: string, userAddress: string): Promise { // HACK: We cheat and don't pass in the assetData since it's always the same token used // in our tests. - const balance = await this._erc20TokenContract.balanceOf.callAsync(userAddress); + const balance = await this._erc20TokenContract.balanceOf(userAddress).callAsync(); return balance; } public async getProxyAllowanceAsync(_assetData: string, userAddress: string): Promise { // HACK: We cheat and don't pass in the assetData since it's always the same token used // in our tests. - const proxyAllowance = await this._erc20TokenContract.allowance.callAsync(userAddress, this._erc20ProxyAddress); + const proxyAllowance = await this._erc20TokenContract + .allowance(userAddress, this._erc20ProxyAddress) + .callAsync(); return proxyAllowance; } } diff --git a/contracts/exchange/test/wrapper_unit_tests.ts b/contracts/exchange/test/wrapper_unit_tests.ts index 3d903edca5..8476baa048 100644 --- a/contracts/exchange/test/wrapper_unit_tests.ts +++ b/contracts/exchange/test/wrapper_unit_tests.ts @@ -1,13 +1,6 @@ +import { ContractTxFunctionObj } from '@0x/base-contract'; import { ReferenceFunctions as LibReferenceFunctions } from '@0x/contracts-exchange-libs'; -import { - blockchainTests, - constants, - describe, - expect, - hexRandom, - MutatorContractFunction, - TransactionHelper, -} from '@0x/contracts-test-utils'; +import { blockchainTests, constants, describe, expect, hexRandom } from '@0x/contracts-test-utils'; import { ReferenceFunctions as UtilReferenceFunctions } from '@0x/contracts-utils'; import { ExchangeRevertErrors, orderHashUtils } from '@0x/order-utils'; import { FillResults, Order } from '@0x/types'; @@ -44,13 +37,11 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { protocolFeePaid: constants.ZERO_AMOUNT, }; let testContract: TestWrapperFunctionsContract; - let txHelper: TransactionHelper; let owner: string; let senderAddress: string; before(async () => { [owner, senderAddress] = await env.getAccountAddressesAsync(); - txHelper = new TransactionHelper(env.web3Wrapper, artifacts); testContract = await TestWrapperFunctionsContract.deployFrom0xArtifactAsync( artifacts.TestWrapperFunctions, env.provider, @@ -62,7 +53,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); // Set the protocol fee multiplier. - await testContract.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(protocolFeeMultiplier, { + await testContract.setProtocolFeeMultiplier(protocolFeeMultiplier).awaitTransactionSuccessAsync({ from: owner, }); }); @@ -152,12 +143,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signature = createOrderSignature(order); const expectedResult = getExpectedFillResults(order, signature); const expectedCalls = [[order, fillAmount, signature]]; - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.fillOrKillOrder, - order, - fillAmount, - signature, - ); + const contractFn = testContract.fillOrKillOrder(order, fillAmount, signature); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -175,7 +163,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { fillAmount, fillAmount.minus(1), ); - const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature); + const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -192,7 +180,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { fillAmount, fillAmount.plus(1), ); - const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature); + const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -203,7 +191,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { }); const signature = createOrderSignature(order); const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR; - const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature); + const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -215,12 +203,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signature = createOrderSignature(order); const expectedResult = getExpectedFillResults(order, signature); const expectedCalls = [[order, fillAmount, signature]]; - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.fillOrderNoThrow, - order, - fillAmount, - signature, - ); + const contractFn = testContract.fillOrderNoThrow(order, fillAmount, signature); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -232,12 +217,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { }); const signature = createOrderSignature(order); const expectedResult = EMPTY_FILL_RESULTS; - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.fillOrderNoThrow, - order, - fillAmount, - signature, - ); + const contractFn = testContract.fillOrderNoThrow(order, fillAmount, signature); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, []); }); @@ -245,12 +227,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { describe('batchFillOrders', () => { it('works with no fills', async () => { - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrders, - [], - [], - [], - ); + const contractFn = testContract.batchFillOrders([], [], []); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq([]); assertFillOrderCallsFromLogs(receipt.logs, []); }); @@ -262,12 +241,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrders, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrders(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -279,12 +255,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrders, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrders(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -298,12 +271,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrders, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrders(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -314,7 +284,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const fillAmounts = _.times(COUNT - 1, i => orders[i].takerAssetAmount); const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedError = new AnyRevertError(); // Just a generic revert. - const tx = txHelper.getResultAndReceiptAsync(testContract.batchFillOrders, orders, fillAmounts, signatures); + const tx = testContract.batchFillOrders(orders, fillAmounts, signatures).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -324,19 +294,16 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); const signatures = _.times(COUNT - 1, i => createOrderSignature(orders[i])); const expectedError = new AnyRevertError(); // Just a generic revert. - const tx = txHelper.getResultAndReceiptAsync(testContract.batchFillOrders, orders, fillAmounts, signatures); + const tx = testContract.batchFillOrders(orders, fillAmounts, signatures).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); describe('batchFillOrKillOrders', () => { it('works with no fills', async () => { - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - [], - [], - [], - ); + const contractFn = testContract.batchFillOrKillOrders([], [], []); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq([]); assertFillOrderCallsFromLogs(receipt.logs, []); }); @@ -348,12 +315,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrKillOrders(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -365,12 +329,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrKillOrders(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -384,12 +345,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrKillOrders(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -410,12 +368,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { failingAmount, failingAmount.minus(1), ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const tx = testContract + .batchFillOrKillOrders(orders, fillAmounts, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -435,12 +390,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { failingAmount, failingAmount.plus(1), ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const tx = testContract + .batchFillOrKillOrders(orders, fillAmounts, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -450,12 +402,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const fillAmounts = _.times(COUNT - 1, i => orders[i].takerAssetAmount); const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedError = new AnyRevertError(); // Just a generic revert. - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const tx = testContract + .batchFillOrKillOrders(orders, fillAmounts, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -465,24 +414,18 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); const signatures = _.times(COUNT - 1, i => createOrderSignature(orders[i])); const expectedError = new AnyRevertError(); // Just a generic revert. - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); + const tx = testContract + .batchFillOrKillOrders(orders, fillAmounts, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); describe('batchFillOrdersNoThrow', () => { it('works with no fills', async () => { - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - [], - [], - [], - ); + const contractFn = testContract.batchFillOrdersNoThrow([], [], []); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq([]); assertFillOrderCallsFromLogs(receipt.logs, []); }); @@ -494,12 +437,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -511,12 +451,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -530,12 +467,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -551,12 +485,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i])); const expectedCalls = _.zip(orders, fillAmounts, signatures); expectedCalls.splice(FAILING_ORDER_INDEX, 1); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - orders, - fillAmounts, - signatures, - ); + const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); }); @@ -567,12 +498,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const fillAmounts = _.times(COUNT - 1, i => orders[i].takerAssetAmount); const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); const expectedError = new AnyRevertError(); // Just a generic revert. - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - orders, - fillAmounts, - signatures, - ); + const tx = testContract + .batchFillOrdersNoThrow(orders, fillAmounts, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -582,24 +510,21 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); const signatures = _.times(COUNT - 1, i => createOrderSignature(orders[i])); const expectedError = new AnyRevertError(); // Just a generic revert. - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - orders, - fillAmounts, - signatures, - ); + const tx = testContract + .batchFillOrdersNoThrow(orders, fillAmounts, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); type ExpectedFillOrderCallArgs = [Order, BigNumber, string]; type MarketSellBuyArgs = [Order[], BigNumber, string[], ...any[]]; - type MarketSellBuyContractFunction = MutatorContractFunction; + type MarketSellBuyContractFn = (...args: MarketSellBuyArgs) => ContractTxFunctionObj; type MarketSellBuySimulator = (...args: MarketSellBuyArgs) => [FillResults, ExpectedFillOrderCallArgs[]]; describe('marketSell*', () => { function defineCommonMarketSellOrdersTests( - getContractFn: () => MarketSellBuyContractFunction, + getContractFn: () => MarketSellBuyContractFn, simulator: MarketSellBuySimulator, ): void { it('works with one order', async () => { @@ -613,12 +538,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -634,12 +556,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -657,12 +576,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -680,12 +596,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); // It should stop filling after the penultimate order. expect(expectedCalls.length).to.eq(COUNT - 1); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -706,12 +619,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); // It should stop filling after first order. expect(expectedCalls.length).to.eq(1); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -727,20 +637,16 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { orders[0].takerAssetAmount, orders[1].takerAssetAmount, ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, takerAssetFillAmount, signatures); + const tx = getContractFn()(orders, takerAssetFillAmount, signatures).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); it('returns empty fill results with no orders', async () => { const [expectedResult, expectedCalls] = simulator([], constants.ZERO_AMOUNT, []); expect(expectedCalls.length).to.eq(0); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - [], - constants.ZERO_AMOUNT, - [], - ); - + const fnWithArgs = getContractFn()([], constants.ZERO_AMOUNT, []); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -767,7 +673,10 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { } describe('marketSellOrdersNoThrow', () => { - defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders); + defineCommonMarketSellOrdersTests( + () => testContract.marketSellOrdersNoThrow.bind(testContract), + simulateMarketSellOrders, + ); it('works when any fills revert', async () => { const COUNT = 4; @@ -789,12 +698,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { signatures, ); expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersNoThrow, - orders, - takerAssetFillAmount, - signatures, - ); + const contractFn = testContract.marketSellOrdersNoThrow(orders, takerAssetFillAmount, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -814,19 +720,19 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { signatures, ); expect(expectedCalls.length).to.eq(0); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersNoThrow, - orders, - takerAssetFillAmount, - signatures, - ); + const contractFn = testContract.marketSellOrdersNoThrow(orders, takerAssetFillAmount, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); }); describe('marketSellOrdersFillOrKill', () => { - defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders); + defineCommonMarketSellOrdersTests( + () => testContract.marketSellOrdersNoThrow.bind(testContract), + simulateMarketSellOrders, + ); it('reverts when filled < `takerAssetFillAmount`', async () => { const COUNT = 4; @@ -842,12 +748,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { takerAssetFillAmount, takerAssetFillAmount.minus(1), ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersFillOrKill, - orders, - takerAssetFillAmount, - signatures, - ); + const tx = testContract + .marketSellOrdersFillOrKill(orders, takerAssetFillAmount, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -871,12 +774,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { signatures, ); expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersFillOrKill, - orders, - takerAssetFillAmount, - signatures, - ); + const contractFn = testContract.marketSellOrdersFillOrKill(orders, takerAssetFillAmount, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -907,12 +807,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { takerAssetFillAmount, takerAssetFillAmount.minus(1), ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersFillOrKill, - orders, - takerAssetFillAmount, - signatures, - ); + const tx = testContract + .marketSellOrdersFillOrKill(orders, takerAssetFillAmount, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -920,7 +817,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { describe('marketBuy*', () => { function defineCommonMarketBuyOrdersTests( - getContractFn: () => MarketSellBuyContractFunction, + getContractFn: () => MarketSellBuyContractFn, simulator: MarketSellBuySimulator, ): void { it('works with one order', async () => { @@ -934,12 +831,10 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); + expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -955,12 +850,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -978,12 +870,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { ); const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1001,12 +890,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); // It should stop filling after the penultimate order. expect(expectedCalls.length).to.eq(COUNT - 1); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1027,12 +913,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); // It should stop filling after first order. expect(expectedCalls.length).to.eq(1); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); + const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1046,7 +929,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { orders[0].takerAssetAmount, makerAssetFillAmount, ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); + const tx = getContractFn()(orders, makerAssetFillAmount, signatures).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -1059,7 +942,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { orders[0].takerAssetAmount.times(makerAssetFillAmount), orders[0].makerAssetAmount, ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); + const tx = getContractFn()(orders, makerAssetFillAmount, signatures).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -1081,20 +964,16 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { orders[0].makerAssetAmount, orders[1].makerAssetAmount, ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); + const tx = getContractFn()(orders, makerAssetFillAmount, signatures).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); it('returns empty fill results with no orders', async () => { const [expectedResult, expectedCalls] = simulator([], constants.ZERO_AMOUNT, []); expect(expectedCalls.length).to.eq(0); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - [], - constants.ZERO_AMOUNT, - [], - ); - + const fnWithArgs = getContractFn()([], constants.ZERO_AMOUNT, []); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1126,7 +1005,10 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { } describe('marketBuyOrdersNoThrow', () => { - defineCommonMarketBuyOrdersTests(() => testContract.marketBuyOrdersNoThrow, simulateMarketBuyOrdersNoThrow); + defineCommonMarketBuyOrdersTests( + () => testContract.marketBuyOrdersNoThrow.bind(testContract), + simulateMarketBuyOrdersNoThrow, + ); it('works when any fills revert', async () => { const COUNT = 4; @@ -1148,12 +1030,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { signatures, ); expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersNoThrow, - orders, - makerAssetFillAmount, - signatures, - ); + const contractFn = testContract.marketBuyOrdersNoThrow(orders, makerAssetFillAmount, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1173,12 +1052,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { signatures, ); expect(expectedCalls.length).to.eq(0); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersNoThrow, - orders, - makerAssetFillAmount, - signatures, - ); + const contractFn = testContract.marketBuyOrdersNoThrow(orders, makerAssetFillAmount, signatures); + const actualResult = await contractFn.callAsync(); + const receipt = await contractFn.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1186,7 +1062,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { describe('marketBuyOrdersFillOrKill', () => { defineCommonMarketBuyOrdersTests( - () => testContract.marketBuyOrdersFillOrKill, + () => testContract.marketBuyOrdersFillOrKill.bind(testContract), simulateMarketBuyOrdersNoThrow, ); @@ -1204,12 +1080,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { makerAssetFillAmount, makerAssetFillAmount.minus(1), ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersFillOrKill, - orders, - makerAssetFillAmount, - signatures, - ); + const tx = testContract + .marketBuyOrdersFillOrKill(orders, makerAssetFillAmount, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -1233,12 +1106,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { signatures, ); expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersFillOrKill, - orders, - makerAssetFillAmount, - signatures, - ); + const fnWithArgs = testContract.marketBuyOrdersFillOrKill(orders, makerAssetFillAmount, signatures); + const actualResult = await fnWithArgs.callAsync(); + const receipt = await fnWithArgs.awaitTransactionSuccessAsync(); expect(actualResult).to.deep.eq(expectedResult); assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); }); @@ -1269,12 +1139,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { makerAssetFillAmount, makerAssetFillAmount.minus(1), ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersFillOrKill, - orders, - makerAssetFillAmount, - signatures, - ); + const tx = testContract + .marketBuyOrdersFillOrKill(orders, makerAssetFillAmount, signatures) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -1294,15 +1161,15 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { } it('works with no orders', async () => { - const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, []); - assertCancelOrderCallsFromLogs(receipt.logs, []); + const { logs } = await testContract.batchCancelOrders([]).awaitTransactionSuccessAsync(); + assertCancelOrderCallsFromLogs(logs, []); }); it('works with many orders', async () => { const COUNT = 8; const orders = _.times(COUNT, () => randomOrder({ makerAddress: senderAddress })); - const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders); - assertCancelOrderCallsFromLogs(receipt.logs, orders); + const { logs } = await testContract.batchCancelOrders(orders).awaitTransactionSuccessAsync(); + assertCancelOrderCallsFromLogs(logs, orders); }); it('works with duplicate orders', async () => { @@ -1310,8 +1177,8 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const COUNT = 6; const uniqueOrders = _.times(UNIQUE_ORDERS, () => randomOrder({ makerAddress: senderAddress })); const orders = _.shuffle(_.flatten(_.times(COUNT / UNIQUE_ORDERS, () => uniqueOrders))); - const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders); - assertCancelOrderCallsFromLogs(receipt.logs, orders); + const { logs } = await testContract.batchCancelOrders(orders).awaitTransactionSuccessAsync(); + assertCancelOrderCallsFromLogs(logs, orders); }); it('reverts if one `_cancelOrder()` reverts', async () => { @@ -1321,7 +1188,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => { const failingOrder = orders[FAILING_ORDER_INDEX]; failingOrder.salt = ALWAYS_FAILING_SALT; const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR; - const tx = txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders); + const tx = testContract.batchCancelOrders(orders).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(expectedError); }); }); diff --git a/contracts/extensions/test/balance_threshold_filter.ts b/contracts/extensions/test/balance_threshold_filter.ts index 311a746076..033c2d732d 100644 --- a/contracts/extensions/test/balance_threshold_filter.ts +++ b/contracts/extensions/test/balance_threshold_filter.ts @@ -129,7 +129,7 @@ describe(ContractName.BalanceThresholdFilter, () => { ); defaultMakerAssetAddress = erc20TokenA.address; defaultTakerAssetAddress = erc20TokenB.address; - zrxAssetData = await devUtils.encodeERC20AssetData.callAsync(zrxToken.address); + zrxAssetData = await devUtils.encodeERC20AssetData(zrxToken.address).callAsync(); // Create proxies const erc20Proxy = await erc20Wrapper.deployProxyAsync(); await erc20Wrapper.setBalancesAndAllowancesAsync(); @@ -143,10 +143,10 @@ describe(ContractName.BalanceThresholdFilter, () => { new BigNumber(chainId), ); // Register proxies - await exchangeInstance.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await exchangeInstance.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, { + await erc20Proxy.addAuthorizedAddress(exchangeInstance.address).awaitTransactionSuccessAsync({ from: owner, }); // Deploy Balance Threshold Filters @@ -177,8 +177,8 @@ describe(ContractName.BalanceThresholdFilter, () => { // Default order parameters defaultOrderParams = { feeRecipientAddress, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(), makerAssetAmount, takerAssetAmount, makerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), DECIMALS_DEFAULT), @@ -300,12 +300,9 @@ describe(ContractName.BalanceThresholdFilter, () => { const badSelectorHex = '0x00000000'; const signatureHex = '0x'; // Call valid forwarder - const tx = erc721BalanceThresholdFilterInstance.executeTransaction.sendTransactionAsync( - salt, - validTakerAddress, - badSelectorHex, - signatureHex, - ); + const tx = erc721BalanceThresholdFilterInstance + .executeTransaction(salt, validTakerAddress, badSelectorHex, signatureHex) + .sendTransactionAsync(); return expect(tx).to.revertWith(RevertReason.InvalidOrBlockedExchangeSelector); }); it('should revert if senderAddress is not set to the valid forwarding contract', async () => { @@ -1243,8 +1240,8 @@ describe(ContractName.BalanceThresholdFilter, () => { feeRecipientAddress, }); const signedOrderRight = await orderFactory2.newSignedOrderAsync({ - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(75), 0), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(13), 0), makerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), 18), diff --git a/contracts/extensions/test/dutch_auction.ts b/contracts/extensions/test/dutch_auction.ts index ab9598147f..1893799188 100644 --- a/contracts/extensions/test/dutch_auction.ts +++ b/contracts/extensions/test/dutch_auction.ts @@ -91,7 +91,7 @@ describe(ContractName.DutchAuction, () => { wethContract = await WETH9Contract.deployFrom0xArtifactAsync(artifacts.WETH9, provider, txDefaults, artifacts); erc20Wrapper.addDummyTokenContract(wethContract as any); - const zrxAssetData = await devUtils.encodeERC20AssetData.callAsync(zrxToken.address); + const zrxAssetData = await devUtils.encodeERC20AssetData(zrxToken.address).callAsync(); const exchangeInstance = await ExchangeContract.deployFrom0xArtifactAsync( artifacts.Exchange, provider, @@ -107,10 +107,10 @@ describe(ContractName.DutchAuction, () => { from: owner, }); - await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, { + await erc20Proxy.addAuthorizedAddress(exchangeInstance.address).sendTransactionAsync({ from: owner, }); - await erc721Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, { + await erc721Proxy.addAuthorizedAddress(exchangeInstance.address).sendTransactionAsync({ from: owner, }); @@ -135,11 +135,9 @@ describe(ContractName.DutchAuction, () => { }), ); await web3Wrapper.awaitTransactionSuccessAsync( - await wethContract.approve.sendTransactionAsync( - erc20Proxy.address, - constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - { from: takerAddress }, - ), + await wethContract + .approve(erc20Proxy.address, constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS) + .sendTransactionAsync({ from: takerAddress }), ); web3Wrapper.abiDecoder.addABI(exchangeInstance.abi); web3Wrapper.abiDecoder.addABI(zrxToken.abi); @@ -161,11 +159,11 @@ describe(ContractName.DutchAuction, () => { // taker address or sender address should be set to the ducth auction contract takerAddress: dutchAuctionContract.address, makerAssetData: assetDataUtils.encodeDutchAuctionAssetData( - await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), + await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), auctionBeginTimeSeconds, auctionBeginAmount, ), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress), + takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(), makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), DECIMALS_DEFAULT), takerAssetAmount: auctionEndAmount, expirationTimeSeconds: auctionEndTimeSeconds, @@ -187,7 +185,7 @@ describe(ContractName.DutchAuction, () => { const takerPrivateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(takerAddress)]; sellerOrderFactory = new OrderFactory(makerPrivateKey, sellerDefaultOrderParams); buyerOrderFactory = new OrderFactory(takerPrivateKey, buyerDefaultOrderParams); - defaultERC20MakerAssetData = await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress); + defaultERC20MakerAssetData = await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(); }); after(async () => { await blockchainLifecycle.revertAsync(); @@ -326,7 +324,7 @@ describe(ContractName.DutchAuction, () => { }); it('asset data contains auction parameters', async () => { sellOrder = await sellerOrderFactory.newSignedOrderAsync({ - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress), + makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), }); const tx = dutchAuctionTestWrapper.matchOrdersAsync(buyOrder, sellOrder, takerAddress); return expect(tx).to.revertWith(RevertReason.InvalidAssetData); @@ -335,10 +333,9 @@ describe(ContractName.DutchAuction, () => { describe('ERC721', () => { it('should match orders when ERC721', async () => { const makerAssetId = erc721MakerAssetIds[0]; - const erc721MakerAssetData = await devUtils.encodeERC721AssetData.callAsync( - erc721Token.address, - makerAssetId, - ); + const erc721MakerAssetData = await devUtils + .encodeERC721AssetData(erc721Token.address, makerAssetId) + .callAsync(); const makerAssetData = assetDataUtils.encodeDutchAuctionAssetData( erc721MakerAssetData, auctionBeginTimeSeconds, @@ -361,7 +358,7 @@ describe(ContractName.DutchAuction, () => { expect(newBalances[makerAddress][wethContract.address]).to.be.bignumber.gte( erc20Balances[makerAddress][wethContract.address].plus(afterAuctionDetails.currentAmount), ); - const newOwner = await erc721Token.ownerOf.callAsync(makerAssetId); + const newOwner = await erc721Token.ownerOf(makerAssetId).callAsync(); expect(newOwner).to.be.bignumber.equal(takerAddress); }); }); diff --git a/contracts/extensions/test/order_matcher.ts b/contracts/extensions/test/order_matcher.ts index 561435373b..005b367110 100644 --- a/contracts/extensions/test/order_matcher.ts +++ b/contracts/extensions/test/order_matcher.ts @@ -116,17 +116,17 @@ describe('OrderMatcher', () => { provider, txDefaults, artifacts, - await devUtils.encodeERC20AssetData.callAsync(zrxToken.address), + await devUtils.encodeERC20AssetData(zrxToken.address).callAsync(), new BigNumber(chainId), ); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { + await exchange.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { + await exchange.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner, }); // Authorize ERC20 trades by exchange await web3Wrapper.awaitTransactionSuccessAsync( - await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchange.address, { + await erc20Proxy.addAuthorizedAddress(exchange.address).sendTransactionAsync({ from: owner, }), constants.AWAIT_TRANSACTION_MINED_MS, @@ -142,35 +142,24 @@ describe('OrderMatcher', () => { // Set default addresses defaultERC20MakerAssetAddress = erc20TokenA.address; defaultERC20TakerAssetAddress = erc20TokenB.address; - leftMakerAssetData = await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress); - leftTakerAssetData = await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress); + leftMakerAssetData = await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(); + leftTakerAssetData = await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(); // Set OrderMatcher balances and allowances - await web3Wrapper.awaitTransactionSuccessAsync( - await erc20TokenA.setBalance.sendTransactionAsync(orderMatcher.address, constants.INITIAL_ERC20_BALANCE, { - from: owner, - }), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - await web3Wrapper.awaitTransactionSuccessAsync( - await erc20TokenB.setBalance.sendTransactionAsync(orderMatcher.address, constants.INITIAL_ERC20_BALANCE, { - from: owner, - }), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.approveAssetProxy.sendTransactionAsync( - leftMakerAssetData, - constants.INITIAL_ERC20_ALLOWANCE, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); - await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.approveAssetProxy.sendTransactionAsync( - leftTakerAssetData, - constants.INITIAL_ERC20_ALLOWANCE, - ), - constants.AWAIT_TRANSACTION_MINED_MS, - ); + await erc20TokenA + .setBalance(orderMatcher.address, constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync({ from: owner }, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }); + + await erc20TokenB + .setBalance(orderMatcher.address, constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync({ from: owner }, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }); + + await orderMatcher + .approveAssetProxy(leftMakerAssetData, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync({}, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }); + + await orderMatcher + .approveAssetProxy(leftTakerAssetData, constants.INITIAL_ERC20_ALLOWANCE) + .awaitTransactionSuccessAsync({}, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }); // Create default order parameters const defaultOrderParamsLeft = { @@ -242,12 +231,9 @@ describe('OrderMatcher', () => { makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(2), 18), }); - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); const tx = web3Wrapper.sendTransactionAsync({ data, to: orderMatcher.address, @@ -277,13 +263,10 @@ describe('OrderMatcher', () => { // Taker leftMakerAssetSpreadAmount: signedOrderLeft.makerAssetAmount.minus(signedOrderRight.takerAssetAmount), }; - const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ data, @@ -293,7 +276,7 @@ describe('OrderMatcher', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); + const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); const newErc20Balances = await erc20Wrapper.getBalancesAsync(); expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal( erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus( @@ -338,13 +321,10 @@ describe('OrderMatcher', () => { amountSoldByRightMaker: signedOrderRight.makerAssetAmount, amountBoughtByRightMaker: signedOrderRight.takerAssetAmount, }; - const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ data, @@ -354,7 +334,7 @@ describe('OrderMatcher', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); + const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); const newErc20Balances = await erc20Wrapper.getBalancesAsync(); expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal( erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus( @@ -400,15 +380,12 @@ describe('OrderMatcher', () => { leftMakerAssetSpreadAmount: signedOrderLeft.makerAssetAmount.minus(signedOrderRight.takerAssetAmount), leftTakerAssetSpreadAmount: signedOrderRight.makerAssetAmount.minus(signedOrderLeft.takerAssetAmount), }; - const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address); + const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync(); // Match signedOrderLeft with signedOrderRight - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ data, @@ -418,8 +395,8 @@ describe('OrderMatcher', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address); + const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync(); const newErc20Balances = await erc20Wrapper.getBalancesAsync(); expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal( erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus( @@ -458,12 +435,9 @@ describe('OrderMatcher', () => { makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), 18), takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(2), 18), }); - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); const logDecoder = new LogDecoder(web3Wrapper, artifacts); const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( await web3Wrapper.sendTransactionAsync({ @@ -491,25 +465,16 @@ describe('OrderMatcher', () => { takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(2), 18), }); let params = orderUtils.createFill(signedOrderLeft, signedOrderLeft.takerAssetAmount.dividedToIntegerBy(5)); - await exchange.fillOrder.awaitTransactionSuccessAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from: takerAddress }, - ); + await exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .awaitTransactionSuccessAsync({ from: takerAddress }); params = orderUtils.createFill(signedOrderRight, signedOrderRight.takerAssetAmount.dividedToIntegerBy(5)); - await exchange.fillOrder.awaitTransactionSuccessAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from: takerAddress }, - ); - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + await exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .awaitTransactionSuccessAsync({ from: takerAddress }); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); const logDecoder = new LogDecoder(web3Wrapper, artifacts); const txReceipt = await logDecoder.getTxWithDecodedLogsAsync( await web3Wrapper.sendTransactionAsync({ @@ -552,15 +517,12 @@ describe('OrderMatcher', () => { leftMakerAssetSpreadAmount: constants.ZERO_AMOUNT, leftTakerAssetSpreadAmount, }; - const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address); + const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync(); // Match signedOrderLeft with signedOrderRight - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ data, @@ -570,8 +532,8 @@ describe('OrderMatcher', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address); + const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync(); const newErc20Balances = await erc20Wrapper.getBalancesAsync(); expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal( erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus( @@ -622,17 +584,14 @@ describe('OrderMatcher', () => { leftMakerAssetSpreadAmount: signedOrderLeft.makerAssetAmount.minus(signedOrderRight.takerAssetAmount), leftTakerAssetSpreadAmount: signedOrderRight.makerAssetAmount.minus(signedOrderLeft.takerAssetAmount), }; - const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address); + const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync(); // Match signedOrderLeft with signedOrderRight signedOrderRight.makerAssetData = constants.NULL_BYTES; signedOrderRight.takerAssetData = constants.NULL_BYTES; - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); await web3Wrapper.awaitTransactionSuccessAsync( await web3Wrapper.sendTransactionAsync({ data, @@ -642,8 +601,8 @@ describe('OrderMatcher', () => { }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); - const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address); + const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); + const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync(); const newErc20Balances = await erc20Wrapper.getBalancesAsync(); expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal( erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus( @@ -683,12 +642,9 @@ describe('OrderMatcher', () => { takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(5), 18), }); signedOrderRight.signature = `0xff${signedOrderRight.signature.slice(4)}`; - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.SignatureError(); const tx = web3Wrapper.sendTransactionAsync({ data, @@ -710,17 +666,14 @@ describe('OrderMatcher', () => { }); // Matcher will not have enough allowance to fill rightOrder await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.approveAssetProxy.sendTransactionAsync(leftMakerAssetData, constants.ZERO_AMOUNT, { + await orderMatcher.approveAssetProxy(leftMakerAssetData, constants.ZERO_AMOUNT).sendTransactionAsync({ from: owner, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const data = exchange.matchOrders.getABIEncodedTransactionData( - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + const data = exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); const expectedError = new ExchangeRevertErrors.AssetProxyTransferError(); const tx = web3Wrapper.sendTransactionAsync({ data, @@ -733,14 +686,14 @@ describe('OrderMatcher', () => { }); describe('withdrawAsset', () => { it('should allow owner to withdraw ERC20 tokens', async () => { - const erc20AWithdrawAmount = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); + const erc20AWithdrawAmount = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); expect(erc20AWithdrawAmount).to.be.bignumber.gt(constants.ZERO_AMOUNT); await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.withdrawAsset.sendTransactionAsync(leftMakerAssetData, erc20AWithdrawAmount, { + await orderMatcher.withdrawAsset(leftMakerAssetData, erc20AWithdrawAmount).sendTransactionAsync({ from: owner, }), ); - const newBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); + const newBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); expect(newBalance).to.be.bignumber.equal(constants.ZERO_AMOUNT); }); it('should allow owner to withdraw ERC721 tokens', async () => { @@ -754,22 +707,22 @@ describe('OrderMatcher', () => { ); const tokenId = new BigNumber(1); await web3Wrapper.awaitTransactionSuccessAsync( - await erc721Token.mint.sendTransactionAsync(orderMatcher.address, tokenId, { from: owner }), + await erc721Token.mint(orderMatcher.address, tokenId).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const assetData = await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, tokenId); + const assetData = await devUtils.encodeERC721AssetData(erc721Token.address, tokenId).callAsync(); const withdrawAmount = new BigNumber(1); await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.withdrawAsset.sendTransactionAsync(assetData, withdrawAmount, { from: owner }), + await orderMatcher.withdrawAsset(assetData, withdrawAmount).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const erc721Owner = await erc721Token.ownerOf.callAsync(tokenId); + const erc721Owner = await erc721Token.ownerOf(tokenId).callAsync(); expect(erc721Owner).to.be.equal(owner); }); it('should revert if not called by owner', async () => { - const erc20AWithdrawAmount = await erc20TokenA.balanceOf.callAsync(orderMatcher.address); + const erc20AWithdrawAmount = await erc20TokenA.balanceOf(orderMatcher.address).callAsync(); expect(erc20AWithdrawAmount).to.be.bignumber.gt(constants.ZERO_AMOUNT); - const tx = orderMatcher.withdrawAsset.sendTransactionAsync(leftMakerAssetData, erc20AWithdrawAmount, { + const tx = orderMatcher.withdrawAsset(leftMakerAssetData, erc20AWithdrawAmount).sendTransactionAsync({ from: takerAddress, }); return expect(tx).to.revertWith(RevertReason.OnlyContractOwner); @@ -779,12 +732,12 @@ describe('OrderMatcher', () => { it('should be able to set an allowance for ERC20 tokens', async () => { const allowance = new BigNumber(55465465426546); await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.approveAssetProxy.sendTransactionAsync(leftMakerAssetData, allowance, { + await orderMatcher.approveAssetProxy(leftMakerAssetData, allowance).sendTransactionAsync({ from: owner, }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const newAllowance = await erc20TokenA.allowance.callAsync(orderMatcher.address, erc20Proxy.address); + const newAllowance = await erc20TokenA.allowance(orderMatcher.address, erc20Proxy.address).callAsync(); expect(newAllowance).to.be.bignumber.equal(allowance); }); it('should be able to approve an ERC721 token by passing in allowance = 1', async () => { @@ -796,16 +749,17 @@ describe('OrderMatcher', () => { constants.DUMMY_TOKEN_NAME, constants.DUMMY_TOKEN_SYMBOL, ); - const assetData = await devUtils.encodeERC721AssetData.callAsync( - erc721Token.address, - constants.ZERO_AMOUNT, - ); + const assetData = await devUtils + .encodeERC721AssetData(erc721Token.address, constants.ZERO_AMOUNT) + .callAsync(); const allowance = new BigNumber(1); await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.approveAssetProxy.sendTransactionAsync(assetData, allowance, { from: owner }), + await orderMatcher.approveAssetProxy(assetData, allowance).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const isApproved = await erc721Token.isApprovedForAll.callAsync(orderMatcher.address, erc721Proxy.address); + const isApproved = await erc721Token + .isApprovedForAll(orderMatcher.address, erc721Proxy.address) + .callAsync(); expect(isApproved).to.be.equal(true); }); it('should be able to approve an ERC721 token by passing in allowance > 1', async () => { @@ -817,21 +771,22 @@ describe('OrderMatcher', () => { constants.DUMMY_TOKEN_NAME, constants.DUMMY_TOKEN_SYMBOL, ); - const assetData = await devUtils.encodeERC721AssetData.callAsync( - erc721Token.address, - constants.ZERO_AMOUNT, - ); + const assetData = await devUtils + .encodeERC721AssetData(erc721Token.address, constants.ZERO_AMOUNT) + .callAsync(); const allowance = new BigNumber(2); await web3Wrapper.awaitTransactionSuccessAsync( - await orderMatcher.approveAssetProxy.sendTransactionAsync(assetData, allowance, { from: owner }), + await orderMatcher.approveAssetProxy(assetData, allowance).sendTransactionAsync({ from: owner }), constants.AWAIT_TRANSACTION_MINED_MS, ); - const isApproved = await erc721Token.isApprovedForAll.callAsync(orderMatcher.address, erc721Proxy.address); + const isApproved = await erc721Token + .isApprovedForAll(orderMatcher.address, erc721Proxy.address) + .callAsync(); expect(isApproved).to.be.equal(true); }); it('should revert if not called by owner', async () => { const approval = new BigNumber(1); - const tx = orderMatcher.approveAssetProxy.sendTransactionAsync(leftMakerAssetData, approval, { + const tx = orderMatcher.approveAssetProxy(leftMakerAssetData, approval).sendTransactionAsync({ from: takerAddress, }); return expect(tx).to.revertWith(RevertReason.OnlyContractOwner); diff --git a/contracts/extensions/test/utils/balance_threshold_wrapper.ts b/contracts/extensions/test/utils/balance_threshold_wrapper.ts index 627e7c1a30..6305bec56c 100644 --- a/contracts/extensions/test/utils/balance_threshold_wrapper.ts +++ b/contracts/extensions/test/utils/balance_threshold_wrapper.ts @@ -41,11 +41,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmount?: BigNumber } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const data = this._exchange.fillOrder.getABIEncodedTransactionData( - params.order, - params.takerAssetFillAmount, - params.signature, - ); + const data = this._exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -55,11 +53,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmount?: BigNumber } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const data = this._exchange.fillOrKillOrder.getABIEncodedTransactionData( - params.order, - params.takerAssetFillAmount, - params.signature, - ); + const data = this._exchange + .fillOrKillOrder(params.order, params.takerAssetFillAmount, params.signature) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -69,11 +65,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmount?: BigNumber; gas?: number } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const data = this._exchange.fillOrderNoThrow.getABIEncodedTransactionData( - params.order, - params.takerAssetFillAmount, - params.signature, - ); + const data = this._exchange + .fillOrderNoThrow(params.order, params.takerAssetFillAmount, params.signature) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from, opts.gas); return txReceipt; } @@ -83,11 +77,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmounts?: BigNumber[] } = {}, ): Promise { const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts); - const data = this._exchange.batchFillOrders.getABIEncodedTransactionData( - params.orders, - params.takerAssetFillAmounts, - params.signatures, - ); + const data = this._exchange + .batchFillOrders(params.orders, params.takerAssetFillAmounts, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -97,11 +89,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmounts?: BigNumber[] } = {}, ): Promise { const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts); - const data = this._exchange.batchFillOrKillOrders.getABIEncodedTransactionData( - params.orders, - params.takerAssetFillAmounts, - params.signatures, - ); + const data = this._exchange + .batchFillOrKillOrders(params.orders, params.takerAssetFillAmounts, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -111,11 +101,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmounts?: BigNumber[]; gas?: number } = {}, ): Promise { const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts); - const data = this._exchange.batchFillOrKillOrders.getABIEncodedTransactionData( - params.orders, - params.takerAssetFillAmounts, - params.signatures, - ); + const data = this._exchange + .batchFillOrKillOrders(params.orders, params.takerAssetFillAmounts, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from, opts.gas); return txReceipt; } @@ -125,11 +113,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmount: BigNumber }, ): Promise { const params = formatters.createMarketSellOrders(orders, opts.takerAssetFillAmount); - const data = this._exchange.marketSellOrders.getABIEncodedTransactionData( - params.orders, - params.takerAssetFillAmount, - params.signatures, - ); + const data = this._exchange + .marketSellOrders(params.orders, params.takerAssetFillAmount, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -139,11 +125,9 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmount: BigNumber; gas?: number }, ): Promise { const params = formatters.createMarketSellOrders(orders, opts.takerAssetFillAmount); - const data = this._exchange.marketSellOrdersNoThrow.getABIEncodedTransactionData( - params.orders, - params.takerAssetFillAmount, - params.signatures, - ); + const data = this._exchange + .marketSellOrdersNoThrow(params.orders, params.takerAssetFillAmount, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from, opts.gas); return txReceipt; } @@ -153,11 +137,9 @@ export class BalanceThresholdWrapper { opts: { makerAssetFillAmount: BigNumber }, ): Promise { const params = formatters.createMarketBuyOrders(orders, opts.makerAssetFillAmount); - const data = this._exchange.marketBuyOrders.getABIEncodedTransactionData( - params.orders, - params.makerAssetFillAmount, - params.signatures, - ); + const data = this._exchange + .marketBuyOrders(params.orders, params.makerAssetFillAmount, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -167,17 +149,15 @@ export class BalanceThresholdWrapper { opts: { makerAssetFillAmount: BigNumber; gas?: number }, ): Promise { const params = formatters.createMarketBuyOrders(orders, opts.makerAssetFillAmount); - const data = this._exchange.marketBuyOrdersNoThrow.getABIEncodedTransactionData( - params.orders, - params.makerAssetFillAmount, - params.signatures, - ); + const data = this._exchange + .marketBuyOrdersNoThrow(params.orders, params.makerAssetFillAmount, params.signatures) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from, opts.gas); return txReceipt; } public async cancelOrderAsync(signedOrder: SignedOrder, from: string): Promise { const params = orderUtils.createCancel(signedOrder); - const data = this._exchange.cancelOrder.getABIEncodedTransactionData(params.order); + const data = this._exchange.cancelOrder(params.order).getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -186,33 +166,33 @@ export class BalanceThresholdWrapper { from: string, ): Promise { const params = formatters.createBatchCancel(orders); - const data = this._exchange.batchCancelOrders.getABIEncodedTransactionData(params.orders); + const data = this._exchange.batchCancelOrders(params.orders).getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } public async cancelOrdersUpToAsync(salt: BigNumber, from: string): Promise { - const data = this._exchange.cancelOrdersUpTo.getABIEncodedTransactionData(salt); + const data = this._exchange.cancelOrdersUpTo(salt).getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } public async getTakerAssetFilledAmountAsync(orderHashHex: string): Promise { - const filledAmount = await this._exchange.filled.callAsync(orderHashHex); + const filledAmount = await this._exchange.filled(orderHashHex).callAsync(); return filledAmount; } public async isCancelledAsync(orderHashHex: string): Promise { - const isCancelled = await this._exchange.cancelled.callAsync(orderHashHex); + const isCancelled = await this._exchange.cancelled(orderHashHex).callAsync(); return isCancelled; } public async getOrderEpochAsync(makerAddress: string, senderAddress: string): Promise { - const orderEpoch = await this._exchange.orderEpoch.callAsync(makerAddress, senderAddress); + const orderEpoch = await this._exchange.orderEpoch(makerAddress, senderAddress).callAsync(); return orderEpoch; } public async getOrderInfoAsync(signedOrder: SignedOrder): Promise { - const orderInfo = await this._exchange.getOrderInfo.callAsync(signedOrder); + const orderInfo = await this._exchange.getOrderInfo(signedOrder).callAsync(); return orderInfo; } public async getOrdersInfoAsync(signedOrders: SignedOrder[]): Promise { - const ordersInfo = (await this._exchange.getOrdersInfo.callAsync(signedOrders)) as OrderInfo[]; + const ordersInfo = (await this._exchange.getOrdersInfo(signedOrders)).callAsync() as OrderInfo[]; return ordersInfo; } public async matchOrdersAsync( @@ -221,12 +201,9 @@ export class BalanceThresholdWrapper { from: string, ): Promise { const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight); - const data = this._exchange.matchOrders.getABIEncodedTransactionData( - params.left, - params.right, - params.leftSignature, - params.rightSignature, - ); + const data = this._exchange + .matchOrders(params.left, params.right, params.leftSignature, params.rightSignature) + .getABIEncodedTransactionData(); const txReceipt = this._executeTransactionAsync(data, from); return txReceipt; } @@ -236,21 +213,16 @@ export class BalanceThresholdWrapper { opts: { takerAssetFillAmount?: BigNumber } = {}, ): Promise { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const fillResults = await this._exchange.fillOrder.callAsync( - params.order, - params.takerAssetFillAmount, - params.signature, - { from }, - ); + const fillResults = await this._exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .callAsync({ from }); return fillResults; } public abiEncodeFillOrder(signedOrder: SignedOrder, opts: { takerAssetFillAmount?: BigNumber } = {}): string { const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount); - const data = this._exchange.fillOrder.getABIEncodedTransactionData( - params.order, - params.takerAssetFillAmount, - params.signature, - ); + const data = this._exchange + .fillOrder(params.order, params.takerAssetFillAmount, params.signature) + .getABIEncodedTransactionData(); return data; } public getBalanceThresholdAddress(): string { @@ -266,13 +238,15 @@ export class BalanceThresholdWrapper { ): Promise { const signedExchangeTx = this._signerTransactionFactory.newSignedTransaction(abiEncodedExchangeTxData); const txOpts = gas === undefined ? { from } : { from, gas }; - const txHash = await this._balanceThresholdFilter.executeTransaction.sendTransactionAsync( - signedExchangeTx.salt, - signedExchangeTx.signerAddress, - signedExchangeTx.data, - signedExchangeTx.signature, - txOpts, - ); + const txHash = await this._balanceThresholdFilter + .executeTransaction( + signedExchangeTx.salt, + signedExchangeTx.signerAddress, + signedExchangeTx.data, + signedExchangeTx.signature, + txOpts, + ) + .sendTransactionAsync(); const txReceipt = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return txReceipt; } diff --git a/contracts/extensions/test/utils/dutch_auction_test_wrapper.ts b/contracts/extensions/test/utils/dutch_auction_test_wrapper.ts index 193ee1cfa4..3e98c6a94a 100644 --- a/contracts/extensions/test/utils/dutch_auction_test_wrapper.ts +++ b/contracts/extensions/test/utils/dutch_auction_test_wrapper.ts @@ -38,15 +38,11 @@ export class DutchAuctionTestWrapper { sellOrder: SignedOrder, from: string, ): Promise { - const txHash = await this._dutchAuctionContract.matchOrders.sendTransactionAsync( - buyOrder, - sellOrder, - buyOrder.signature, - sellOrder.signature, - { + const txHash = await this._dutchAuctionContract + .matchOrders(buyOrder, sellOrder, buyOrder.signature, sellOrder.signature) + .sendTransactionAsync({ from, - }, - ); + }); const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return tx; } @@ -56,7 +52,7 @@ export class DutchAuctionTestWrapper { * @return The dutch auction details. */ public async getAuctionDetailsAsync(sellOrder: SignedOrder): Promise { - const auctionDetails = await this._dutchAuctionContract.getAuctionDetails.callAsync(sellOrder); + const auctionDetails = await this._dutchAuctionContract.getAuctionDetails(sellOrder).callAsync(); return auctionDetails; } } diff --git a/contracts/integrations/src/function_assertions.ts b/contracts/integrations/src/function_assertions.ts index 040ea0e26d..371ab84230 100644 --- a/contracts/integrations/src/function_assertions.ts +++ b/contracts/integrations/src/function_assertions.ts @@ -1,16 +1,10 @@ -import { PromiseWithTransactionHash } from '@0x/base-contract'; +import { ContractFunctionObj, ContractTxFunctionObj } from '@0x/base-contract'; import { TransactionReceiptWithDecodedLogs } from 'ethereum-types'; import * as _ from 'lodash'; // tslint:disable:max-classes-per-file -export interface ContractGetterFunction { - callAsync: (...args: any[]) => Promise; -} - -export interface ContractWrapperFunction extends ContractGetterFunction { - awaitTransactionSuccessAsync?: (...args: any[]) => PromiseWithTransactionHash; -} +export type GenericContractFunction = (...args: any[]) => ContractFunctionObj; export interface FunctionResult { data?: any; @@ -53,14 +47,21 @@ export interface AssertionResult { * This class implements `Assertion` and represents a "Hoare Triple" that can be * executed. */ -export class FunctionAssertion implements Assertion { +export class FunctionAssertion implements Assertion { // A condition that will be applied to `wrapperFunction`. public condition: Condition; // The wrapper function that will be wrapped in assertions. - public wrapperFunction: ContractWrapperFunction; + public wrapperFunction: ( + ...args: any[] // tslint:disable-line:trailing-comma + ) => ContractTxFunctionObj | ContractFunctionObj; - constructor(wrapperFunction: ContractWrapperFunction, condition: Partial> = {}) { + constructor( + wrapperFunction: ( + ...args: any[] // tslint:disable-line:trailing-comma + ) => ContractTxFunctionObj | ContractFunctionObj, + condition: Partial> = {}, + ) { this.condition = { before: _.noop.bind(this), after: _.noop.bind(this), @@ -83,11 +84,11 @@ export class FunctionAssertion implements Assertion { // Try to make the call to the function. If it is successful, pass the // result and receipt to the after condition. try { - callResult.data = await this.wrapperFunction.callAsync(...args); - // tslint:disable:await-promise + const functionWithArgs = this.wrapperFunction(...args) as ContractTxFunctionObj; + callResult.data = await functionWithArgs.callAsync(); callResult.receipt = - this.wrapperFunction.awaitTransactionSuccessAsync !== undefined - ? await this.wrapperFunction.awaitTransactionSuccessAsync(...args) + functionWithArgs.awaitTransactionSuccessAsync !== undefined + ? await functionWithArgs.awaitTransactionSuccessAsync() // tslint:disable-line:await-promise : undefined; // tslint:enable:await-promise } catch (error) { diff --git a/contracts/integrations/test/actors/base.ts b/contracts/integrations/test/actors/base.ts index a777230a96..5447f15dfb 100644 --- a/contracts/integrations/test/actors/base.ts +++ b/contracts/integrations/test/actors/base.ts @@ -54,22 +54,19 @@ export class Actor { amount?: BigNumber, ): Promise { if (token instanceof DummyERC20TokenContract) { - await token.setBalance.awaitTransactionSuccessAsync( - this.address, - amount || constants.INITIAL_ERC20_BALANCE, - ); + await token + .setBalance(this.address, amount || constants.INITIAL_ERC20_BALANCE) + .awaitTransactionSuccessAsync(); } else { - await token.deposit.awaitTransactionSuccessAsync({ + await token.deposit().awaitTransactionSuccessAsync({ from: this.address, value: amount || constants.ONE_ETHER, }); } - await token.approve.awaitTransactionSuccessAsync( - spender || this.deployment.assetProxies.erc20Proxy.address, - constants.MAX_UINT256, - { from: this.address }, - ); + await token + .approve(spender || this.deployment.assetProxies.erc20Proxy.address, constants.MAX_UINT256) + .awaitTransactionSuccessAsync({ from: this.address }); } /** @@ -84,19 +81,17 @@ export class Actor { const tokenIds: BigNumber[] = []; _.times(numToMint, async () => { const tokenId = getRandomInteger(constants.ZERO_AMOUNT, constants.MAX_UINT256); - await token.mint.awaitTransactionSuccessAsync(this.address, tokenId, { + await token.mint(this.address, tokenId).awaitTransactionSuccessAsync({ from: this.address, }); tokenIds.push(tokenId); }); - await token.setApprovalForAll.awaitTransactionSuccessAsync( - spender || this.deployment.assetProxies.erc721Proxy.address, - true, - { + await token + .setApprovalForAll(spender || this.deployment.assetProxies.erc721Proxy.address, true) + .awaitTransactionSuccessAsync({ from: this.address, - }, - ); + }); return tokenIds; } diff --git a/contracts/integrations/test/actors/keeper.ts b/contracts/integrations/test/actors/keeper.ts index 9389d136aa..b16182b749 100644 --- a/contracts/integrations/test/actors/keeper.ts +++ b/contracts/integrations/test/actors/keeper.ts @@ -37,14 +37,14 @@ export function KeeperMixin(Base: TBase): TBase & Con if (shouldFastForward) { // increase timestamp of next block by how many seconds we need to // get to the next epoch. - const epochEndTime = await stakingWrapper.getCurrentEpochEarliestEndTimeInSeconds.callAsync(); + const epochEndTime = await stakingWrapper.getCurrentEpochEarliestEndTimeInSeconds().callAsync(); const lastBlockTime = await web3Wrapper.getBlockTimestampAsync('latest'); const dt = Math.max(0, epochEndTime.minus(lastBlockTime).toNumber()); await web3Wrapper.increaseTimeAsync(dt); // mine next block await web3Wrapper.mineBlockAsync(); } - return stakingWrapper.endEpoch.awaitTransactionSuccessAsync({ from: this.actor.address }); + return stakingWrapper.endEpoch().awaitTransactionSuccessAsync({ from: this.actor.address }); } /** @@ -55,7 +55,7 @@ export function KeeperMixin(Base: TBase): TBase & Con const { stakingWrapper } = this.actor.deployment.staking; // If no poolIds provided, finalize all active pools from the previous epoch if (poolIds.length === 0) { - const previousEpoch = (await stakingWrapper.currentEpoch.callAsync()).minus(1); + const previousEpoch = (await stakingWrapper.currentEpoch().callAsync()).minus(1); const events = filterLogsToArguments( await stakingWrapper.getLogsAsync( TestStakingEvents.StakingPoolEarnedRewardsInEpoch, @@ -69,7 +69,7 @@ export function KeeperMixin(Base: TBase): TBase & Con return Promise.all( poolIds.map(async poolId => - stakingWrapper.finalizePool.awaitTransactionSuccessAsync(poolId, { + stakingWrapper.finalizePool(poolId).awaitTransactionSuccessAsync({ from: this.actor.address, }), ), diff --git a/contracts/integrations/test/actors/maker.ts b/contracts/integrations/test/actors/maker.ts index 8e9bcb9f79..e9ebab6006 100644 --- a/contracts/integrations/test/actors/maker.ts +++ b/contracts/integrations/test/actors/maker.ts @@ -59,7 +59,7 @@ export function MakerMixin(Base: TBase): TBase & Cons */ public async cancelOrderAsync(order: SignedOrder): Promise { const params = orderUtils.createCancel(order); - return this.actor.deployment.exchange.cancelOrder.awaitTransactionSuccessAsync(params.order, { + return this.actor.deployment.exchange.cancelOrder(params.order).awaitTransactionSuccessAsync({ from: this.actor.address, }); } @@ -70,7 +70,7 @@ export function MakerMixin(Base: TBase): TBase & Cons public async joinStakingPoolAsync(poolId: string): Promise { const stakingContract = this.actor.deployment.staking.stakingWrapper; this.makerPoolId = poolId; - return stakingContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { + return stakingContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: this.actor.address, }); } diff --git a/contracts/integrations/test/actors/pool_operator.ts b/contracts/integrations/test/actors/pool_operator.ts index a8fdcf9f3f..b6492d84bc 100644 --- a/contracts/integrations/test/actors/pool_operator.ts +++ b/contracts/integrations/test/actors/pool_operator.ts @@ -54,11 +54,9 @@ export function PoolOperatorMixin(Base: TBase): TBase addOperatorAsMaker: boolean = false, ): Promise { const stakingContract = this.actor.deployment.staking.stakingWrapper; - const txReceipt = await stakingContract.createStakingPool.awaitTransactionSuccessAsync( - operatorShare, - addOperatorAsMaker, - { from: this.actor.address }, - ); + const txReceipt = await stakingContract + .createStakingPool(operatorShare, addOperatorAsMaker) + .awaitTransactionSuccessAsync({ from: this.actor.address }); const createStakingPoolLog = txReceipt.logs[0]; const poolId = (createStakingPoolLog as any).args.poolId; @@ -73,11 +71,9 @@ export function PoolOperatorMixin(Base: TBase): TBase newOperatorShare: number, ): Promise { const stakingContract = this.actor.deployment.staking.stakingWrapper; - return stakingContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - newOperatorShare, - { from: this.actor.address }, - ); + return stakingContract + .decreaseStakingPoolOperatorShare(poolId, newOperatorShare) + .awaitTransactionSuccessAsync({ from: this.actor.address }); } private _getOperatorPoolIds(stakingPools: StakingPoolById): string[] { diff --git a/contracts/integrations/test/actors/staker.ts b/contracts/integrations/test/actors/staker.ts index 0b696c859b..5954e8dbc6 100644 --- a/contracts/integrations/test/actors/staker.ts +++ b/contracts/integrations/test/actors/staker.ts @@ -51,16 +51,17 @@ export function StakerMixin(Base: TBase): TBase & Con */ public async stakeAsync(amount: BigNumber, poolId?: string): Promise { const { stakingWrapper } = this.actor.deployment.staking; - await stakingWrapper.stake.awaitTransactionSuccessAsync(amount, { + await stakingWrapper.stake(amount).awaitTransactionSuccessAsync({ from: this.actor.address, }); if (poolId !== undefined) { - await stakingWrapper.moveStake.awaitTransactionSuccessAsync( - new StakeInfo(StakeStatus.Undelegated), - new StakeInfo(StakeStatus.Delegated, poolId), - amount, - { from: this.actor.address }, - ); + await stakingWrapper + .moveStake( + new StakeInfo(StakeStatus.Undelegated), + new StakeInfo(StakeStatus.Delegated, poolId), + amount, + ) + .awaitTransactionSuccessAsync({ from: this.actor.address }); } } @@ -84,10 +85,9 @@ export function StakerMixin(Base: TBase): TBase & Con while (true) { await balanceStore.updateErc20BalancesAsync(); - const undelegatedStake = await stakingWrapper.getOwnerStakeByStatus.callAsync( - this.actor.address, - StakeStatus.Undelegated, - ); + const undelegatedStake = await stakingWrapper + .getOwnerStakeByStatus(this.actor.address, StakeStatus.Undelegated) + .callAsync(); const withdrawableStake = BigNumber.min( undelegatedStake.currentEpochBalance, undelegatedStake.nextEpochBalance, diff --git a/contracts/integrations/test/actors/taker.ts b/contracts/integrations/test/actors/taker.ts index c591d07888..65672f9a52 100644 --- a/contracts/integrations/test/actors/taker.ts +++ b/contracts/integrations/test/actors/taker.ts @@ -41,17 +41,14 @@ export function TakerMixin(Base: TBase): TBase & Cons fillAmount: BigNumber, txData: Partial = {}, ): Promise { - return this.actor.deployment.exchange.fillOrder.awaitTransactionSuccessAsync( - order, - fillAmount, - order.signature, - { + return this.actor.deployment.exchange + .fillOrder(order, fillAmount, order.signature) + .awaitTransactionSuccessAsync({ from: this.actor.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee, ...txData, - }, - ); + }); } }; } diff --git a/contracts/integrations/test/coordinator/coordinator_test.ts b/contracts/integrations/test/coordinator/coordinator_test.ts index 7178534295..0a863591af 100644 --- a/contracts/integrations/test/coordinator/coordinator_test.ts +++ b/contracts/integrations/test/coordinator/coordinator_test.ts @@ -63,10 +63,10 @@ blockchainTests.resets('Coordinator integration tests', env => { orderConfig: { senderAddress: coordinator.address, feeRecipientAddress: feeRecipient.address, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(makerToken.address), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(takerToken.address), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(makerFeeToken.address), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(takerFeeToken.address), + makerAssetData: await devUtils.encodeERC20AssetData(makerToken.address).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(takerToken.address).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(makerFeeToken.address).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(takerFeeToken.address).callAsync(), }, }); @@ -140,7 +140,7 @@ blockchainTests.resets('Coordinator integration tests', env => { taker.address, deployment.staking.stakingProxy.address, DeploymentManager.protocolFee, - await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address), + await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(), ); } } @@ -186,13 +186,9 @@ blockchainTests.resets('Coordinator integration tests', env => { it(`${fnName} should fill the order with a signed approval`, async () => { await balanceStore.updateBalancesAsync(); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [approval.signature], - { from: taker.address, value: DeploymentManager.protocolFee }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, taker.address, transaction.signature, [approval.signature]) + .awaitTransactionSuccessAsync({ from: taker.address, value: DeploymentManager.protocolFee }); const expectedBalances = await simulateFillsAsync([order], txReceipt, DeploymentManager.protocolFee); await balanceStore.updateBalancesAsync(); @@ -201,13 +197,9 @@ blockchainTests.resets('Coordinator integration tests', env => { }); it(`${fnName} should fill the order if called by approver (eth protocol fee, no refund)`, async () => { await balanceStore.updateBalancesAsync(); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - feeRecipient.address, - transaction.signature, - [], - { from: feeRecipient.address, value: DeploymentManager.protocolFee }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, feeRecipient.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: feeRecipient.address, value: DeploymentManager.protocolFee }); const expectedBalances = await simulateFillsAsync([order], txReceipt, DeploymentManager.protocolFee); await balanceStore.updateBalancesAsync(); @@ -216,13 +208,12 @@ blockchainTests.resets('Coordinator integration tests', env => { }); it(`${fnName} should fill the order if called by approver (eth protocol fee, refund)`, async () => { await balanceStore.updateBalancesAsync(); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - feeRecipient.address, - transaction.signature, - [], - { from: feeRecipient.address, value: DeploymentManager.protocolFee.plus(1) }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, feeRecipient.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ + from: feeRecipient.address, + value: DeploymentManager.protocolFee.plus(1), + }); const expectedBalances = await simulateFillsAsync( [order], @@ -235,13 +226,9 @@ blockchainTests.resets('Coordinator integration tests', env => { }); it(`${fnName} should fill the order if called by approver (weth protocol fee, no refund)`, async () => { await balanceStore.updateBalancesAsync(); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - feeRecipient.address, - transaction.signature, - [], - { from: feeRecipient.address }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, feeRecipient.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: feeRecipient.address }); const expectedBalances = await simulateFillsAsync([order], txReceipt); await balanceStore.updateBalancesAsync(); @@ -250,13 +237,9 @@ blockchainTests.resets('Coordinator integration tests', env => { }); it(`${fnName} should fill the order if called by approver (weth protocol fee, refund)`, async () => { await balanceStore.updateBalancesAsync(); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - feeRecipient.address, - transaction.signature, - [], - { from: feeRecipient.address, value: new BigNumber(1) }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, feeRecipient.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: feeRecipient.address, value: new BigNumber(1) }); const expectedBalances = await simulateFillsAsync([order], txReceipt, new BigNumber(1)); await balanceStore.updateBalancesAsync(); @@ -265,13 +248,9 @@ blockchainTests.resets('Coordinator integration tests', env => { }); it(`${fnName} should revert with no approval signature`, async () => { const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [], - { from: taker.address, value: DeploymentManager.protocolFee }, - ); + const tx = coordinator + .executeTransaction(transaction, taker.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: taker.address, value: DeploymentManager.protocolFee }); const expectedError = new CoordinatorRevertErrors.InvalidApprovalSignatureError( transactionHash, @@ -286,13 +265,9 @@ blockchainTests.resets('Coordinator integration tests', env => { hexSlice(approval.signature, 6), ); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [approvalSignature], - { from: taker.address, value: DeploymentManager.protocolFee }, - ); + const tx = coordinator + .executeTransaction(transaction, taker.address, transaction.signature, [approvalSignature]) + .awaitTransactionSuccessAsync({ from: taker.address, value: DeploymentManager.protocolFee }); const expectedError = new CoordinatorRevertErrors.InvalidApprovalSignatureError( transactionHash, @@ -301,13 +276,9 @@ blockchainTests.resets('Coordinator integration tests', env => { return expect(tx).to.revertWith(expectedError); }); it(`${fnName} should revert if not called by tx signer or approver`, async () => { - const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [approval.signature], - { from: maker.address, value: DeploymentManager.protocolFee }, - ); + const tx = coordinator + .executeTransaction(transaction, taker.address, transaction.signature, [approval.signature]) + .awaitTransactionSuccessAsync({ from: maker.address, value: DeploymentManager.protocolFee }); const expectedError = new CoordinatorRevertErrors.InvalidOriginError(taker.address); return expect(tx).to.revertWith(expectedError); @@ -334,13 +305,9 @@ blockchainTests.resets('Coordinator integration tests', env => { it(`${fnName} should fill the orders with a signed approval`, async () => { await balanceStore.updateBalancesAsync(); const value = DeploymentManager.protocolFee.times(orders.length); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [approval.signature], - { from: taker.address, value }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, taker.address, transaction.signature, [approval.signature]) + .awaitTransactionSuccessAsync({ from: taker.address, value }); const expectedBalances = await simulateFillsAsync(orders, txReceipt, value); await balanceStore.updateBalancesAsync(); @@ -350,13 +317,9 @@ blockchainTests.resets('Coordinator integration tests', env => { it(`${fnName} should fill the orders if called by approver (eth fee, no refund)`, async () => { await balanceStore.updateBalancesAsync(); const value = DeploymentManager.protocolFee.times(orders.length); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - feeRecipient.address, - transaction.signature, - [], - { from: feeRecipient.address, value }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, feeRecipient.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: feeRecipient.address, value }); const expectedBalances = await simulateFillsAsync(orders, txReceipt, value); await balanceStore.updateBalancesAsync(); @@ -366,13 +329,9 @@ blockchainTests.resets('Coordinator integration tests', env => { it(`${fnName} should fill the orders if called by approver (mixed fees, refund)`, async () => { await balanceStore.updateBalancesAsync(); const value = DeploymentManager.protocolFee.plus(1); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - feeRecipient.address, - transaction.signature, - [], - { from: feeRecipient.address, value }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, feeRecipient.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: feeRecipient.address, value }); const expectedBalances = await simulateFillsAsync(orders, txReceipt, value); await balanceStore.updateBalancesAsync(); @@ -386,13 +345,12 @@ blockchainTests.resets('Coordinator integration tests', env => { hexSlice(approval.signature, 6), ); const transactionHash = transactionHashUtils.getTransactionHashHex(transaction); - const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [approvalSignature], - { from: taker.address, value: DeploymentManager.protocolFee.times(orders.length) }, - ); + const tx = coordinator + .executeTransaction(transaction, taker.address, transaction.signature, [approvalSignature]) + .awaitTransactionSuccessAsync({ + from: taker.address, + value: DeploymentManager.protocolFee.times(orders.length), + }); const expectedError = new CoordinatorRevertErrors.InvalidApprovalSignatureError( transactionHash, feeRecipient.address, @@ -400,13 +358,12 @@ blockchainTests.resets('Coordinator integration tests', env => { return expect(tx).to.revertWith(expectedError); }); it(`${fnName} should revert if not called by tx signer or approver`, async () => { - const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - taker.address, - transaction.signature, - [approval.signature], - { from: maker.address, value: DeploymentManager.protocolFee.times(orders.length) }, - ); + const tx = coordinator + .executeTransaction(transaction, taker.address, transaction.signature, [approval.signature]) + .awaitTransactionSuccessAsync({ + from: maker.address, + value: DeploymentManager.protocolFee.times(orders.length), + }); const expectedError = new CoordinatorRevertErrors.InvalidOriginError(taker.address); return expect(tx).to.revertWith(expectedError); }); @@ -431,13 +388,9 @@ blockchainTests.resets('Coordinator integration tests', env => { data, gasPrice: DeploymentManager.gasPrice, }); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - maker.address, - transaction.signature, - [], - { from: maker.address }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, maker.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: maker.address }); verifyEvents(txReceipt, [expectedCancelEvent(order)], ExchangeEvents.Cancel); }); @@ -448,13 +401,9 @@ blockchainTests.resets('Coordinator integration tests', env => { data, gasPrice: DeploymentManager.gasPrice, }); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - maker.address, - transaction.signature, - [], - { from: maker.address }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, maker.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: maker.address }); verifyEvents(txReceipt, orders.map(order => expectedCancelEvent(order)), ExchangeEvents.Cancel); }); @@ -464,13 +413,9 @@ blockchainTests.resets('Coordinator integration tests', env => { data, gasPrice: DeploymentManager.gasPrice, }); - const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync( - transaction, - maker.address, - transaction.signature, - [], - { from: maker.address }, - ); + const txReceipt = await coordinator + .executeTransaction(transaction, maker.address, transaction.signature, []) + .awaitTransactionSuccessAsync({ from: maker.address }); const expectedEvent: ExchangeCancelUpToEventArgs = { makerAddress: maker.address, diff --git a/contracts/integrations/test/deployment_manager.ts b/contracts/integrations/test/deployment_manager.ts index 346c11a367..1dedc5d4d8 100644 --- a/contracts/integrations/test/deployment_manager.ts +++ b/contracts/integrations/test/deployment_manager.ts @@ -38,7 +38,7 @@ async function batchAddAuthorizedAddressAsync( ): Promise { for (const authorizer of authorizers) { for (const authority of authorities) { - await authorizer.addAuthorizedAddress.awaitTransactionSuccessAsync(authority, { from: owner }); + await authorizer.addAuthorizedAddress(authority).awaitTransactionSuccessAsync({ from: owner }); } } } @@ -56,7 +56,7 @@ async function batchRegisterAssetProxyAsync( ): Promise { for (const registry of registries) { for (const proxy of proxies) { - await registry.registerAssetProxy.awaitTransactionSuccessAsync(proxy, { from: owner }); + await registry.registerAssetProxy(proxy).awaitTransactionSuccessAsync({ from: owner }); } } } @@ -73,7 +73,7 @@ async function batchTransferOwnershipAsync( ownedContracts: Ownable[], ): Promise { for (const ownedContract of ownedContracts) { - await ownedContract.transferOwnership.awaitTransactionSuccessAsync(newOwner.address, { from: owner }); + await ownedContract.transferOwnership(newOwner.address).awaitTransactionSuccessAsync({ from: owner }); } } @@ -171,16 +171,16 @@ export class DeploymentManager { await DeploymentManager._configureExchangeWithStakingAsync(exchange, staking, owner); // Authorize the asset-proxy owner in the staking proxy and in the zrx vault. - await staking.stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address, { + await staking.stakingProxy.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync({ from: owner, }); - await staking.zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address, { + await staking.zrxVault.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync({ from: owner, }); // Remove authorization for the original owner address. - await staking.stakingProxy.removeAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner }); - await staking.zrxVault.removeAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner }); + await staking.stakingProxy.removeAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner }); + await staking.zrxVault.removeAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner }); // Transfer complete ownership of the system to the asset proxy owner. await batchTransferOwnershipAsync(owner, governor, [ @@ -275,13 +275,13 @@ export class DeploymentManager { owner: string, ): Promise { // Configure the exchange for staking. - await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync(staking.stakingProxy.address, { + await exchange.setProtocolFeeCollectorAddress(staking.stakingProxy.address).awaitTransactionSuccessAsync({ from: owner, }); - await exchange.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(DeploymentManager.protocolFeeMultiplier); + await exchange.setProtocolFeeMultiplier(DeploymentManager.protocolFeeMultiplier).awaitTransactionSuccessAsync(); // Register the exchange contract in staking. - await staking.stakingWrapper.addExchangeAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); + await staking.stakingWrapper.addExchangeAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); } /** @@ -374,20 +374,20 @@ export class DeploymentManager { const stakingWrapper = new TestStakingContract(stakingProxy.address, environment.provider, txDefaults); // Add the zrx vault and the weth contract to the staking proxy. - await stakingWrapper.setWethContract.awaitTransactionSuccessAsync(tokens.weth.address, { from: owner }); - await stakingWrapper.setZrxVault.awaitTransactionSuccessAsync(zrxVault.address, { from: owner }); + await stakingWrapper.setWethContract(tokens.weth.address).awaitTransactionSuccessAsync({ from: owner }); + await stakingWrapper.setZrxVault(zrxVault.address).awaitTransactionSuccessAsync({ from: owner }); // Authorize the owner address in the staking proxy and the zrx vault. - await stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner }); - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner }); + await stakingProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner }); + await zrxVault.addAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner }); // Authorize the zrx vault in the erc20 proxy - await assetProxies.erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(zrxVault.address, { + await assetProxies.erc20Proxy.addAuthorizedAddress(zrxVault.address).awaitTransactionSuccessAsync({ from: owner, }); // Configure the zrx vault and the staking contract. - await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy.address, { from: owner }); + await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync({ from: owner }); return { stakingLogic, diff --git a/contracts/integrations/test/forwarder/forwarder_test.ts b/contracts/integrations/test/forwarder/forwarder_test.ts index c3f91abef3..9f88478dad 100644 --- a/contracts/integrations/test/forwarder/forwarder_test.ts +++ b/contracts/integrations/test/forwarder/forwarder_test.ts @@ -57,8 +57,8 @@ blockchainTests('Forwarder integration tests', env => { [makerToken, makerFeeToken, anotherErc20Token] = deployment.tokens.erc20; [erc721Token] = deployment.tokens.erc721; - wethAssetData = await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address); - makerAssetData = await devUtils.encodeERC20AssetData.callAsync(makerToken.address); + wethAssetData = await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(); + makerAssetData = await devUtils.encodeERC20AssetData(makerToken.address).callAsync(); taker = new Actor({ name: 'Taker', deployment }); orderFeeRecipient = new FeeRecipient({ @@ -79,7 +79,7 @@ blockchainTests('Forwarder integration tests', env => { makerAssetData, takerAssetData: wethAssetData, takerFee: constants.ZERO_AMOUNT, - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(makerFeeToken.address), + makerFeeAssetData: await devUtils.encodeERC20AssetData(makerFeeToken.address).callAsync(), takerFeeAssetData: wethAssetData, }, }); @@ -87,7 +87,7 @@ blockchainTests('Forwarder integration tests', env => { await maker.configureERC20TokenAsync(makerToken); await maker.configureERC20TokenAsync(makerFeeToken); await maker.configureERC20TokenAsync(anotherErc20Token); - await forwarder.approveMakerAssetProxy.awaitTransactionSuccessAsync(makerAssetData); + await forwarder.approveMakerAssetProxy(makerAssetData).awaitTransactionSuccessAsync(); [nftId] = await maker.configureERC721TokenAsync(erc721Token); const tokenOwners = { @@ -171,7 +171,7 @@ blockchainTests('Forwarder integration tests', env => { await testFactory.marketSellTestAsync(orders, 1.34); }); it('should fail to fill an order with a percentage fee if the asset proxy is not yet approved', async () => { - const unapprovedAsset = await devUtils.encodeERC20AssetData.callAsync(anotherErc20Token.address); + const unapprovedAsset = await devUtils.encodeERC20AssetData(anotherErc20Token.address).callAsync(); const order = await maker.signOrderAsync({ makerAssetData: unapprovedAsset, takerFee: toBaseUnitAmount(2), @@ -180,16 +180,17 @@ blockchainTests('Forwarder integration tests', env => { await balanceStore.updateBalancesAsync(); // Execute test case - const tx = await forwarder.marketSellOrdersWithEth.awaitTransactionSuccessAsync( - [order], - [order.signature], - constants.ZERO_AMOUNT, - forwarderFeeRecipient.address, - { + const tx = await forwarder + .marketSellOrdersWithEth( + [order], + [order.signature], + constants.ZERO_AMOUNT, + forwarderFeeRecipient.address, + ) + .awaitTransactionSuccessAsync({ value: order.takerAssetAmount.plus(DeploymentManager.protocolFee), from: taker.address, - }, - ); + }); const expectedBalances = LocalBalanceStore.create(devUtils, balanceStore); expectedBalances.burnGas(tx.from, DeploymentManager.gasPrice.times(tx.gasUsed)); @@ -223,16 +224,17 @@ blockchainTests('Forwarder integration tests', env => { const order = await maker.signOrderAsync(); const ethValue = order.takerAssetAmount.plus(DeploymentManager.protocolFee).plus(2); const takerEthBalanceBefore = await env.web3Wrapper.getBalanceInWeiAsync(taker.address); - const tx = await forwarder.marketSellOrdersWithEth.awaitTransactionSuccessAsync( - [order], - [order.signature], - constants.ZERO_AMOUNT, - forwarderFeeRecipient.address, - { + const tx = await forwarder + .marketSellOrdersWithEth( + [order], + [order.signature], + constants.ZERO_AMOUNT, + forwarderFeeRecipient.address, + ) + .awaitTransactionSuccessAsync({ value: ethValue, from: taker.address, - }, - ); + }); const takerEthBalanceAfter = await env.web3Wrapper.getBalanceInWeiAsync(taker.address); const totalEthSpent = order.takerAssetAmount .plus(DeploymentManager.protocolFee) @@ -241,16 +243,18 @@ blockchainTests('Forwarder integration tests', env => { }); it('should fill orders with different makerAssetData', async () => { const firstOrder = await maker.signOrderAsync(); - const secondOrderMakerAssetData = await devUtils.encodeERC20AssetData.callAsync(anotherErc20Token.address); + const secondOrderMakerAssetData = await devUtils + .encodeERC20AssetData(anotherErc20Token.address) + .callAsync(); const secondOrder = await maker.signOrderAsync({ makerAssetData: secondOrderMakerAssetData, }); - await forwarder.approveMakerAssetProxy.awaitTransactionSuccessAsync(secondOrderMakerAssetData); + await forwarder.approveMakerAssetProxy(secondOrderMakerAssetData).awaitTransactionSuccessAsync(); const orders = [firstOrder, secondOrder]; await testFactory.marketSellTestAsync(orders, 1.5); }); it('should fail to fill an order with a fee denominated in an asset other than makerAsset or WETH', async () => { - const takerFeeAssetData = await devUtils.encodeERC20AssetData.callAsync(anotherErc20Token.address); + const takerFeeAssetData = await devUtils.encodeERC20AssetData(anotherErc20Token.address).callAsync(); const order = await maker.signOrderAsync({ takerFeeAssetData, takerFee: toBaseUnitAmount(1), @@ -341,11 +345,13 @@ blockchainTests('Forwarder integration tests', env => { }); it('should buy exactly makerAssetBuyAmount in orders with different makerAssetData', async () => { const firstOrder = await maker.signOrderAsync(); - const secondOrderMakerAssetData = await devUtils.encodeERC20AssetData.callAsync(anotherErc20Token.address); + const secondOrderMakerAssetData = await devUtils + .encodeERC20AssetData(anotherErc20Token.address) + .callAsync(); const secondOrder = await maker.signOrderAsync({ makerAssetData: secondOrderMakerAssetData, }); - await forwarder.approveMakerAssetProxy.awaitTransactionSuccessAsync(secondOrderMakerAssetData); + await forwarder.approveMakerAssetProxy(secondOrderMakerAssetData).awaitTransactionSuccessAsync(); const orders = [firstOrder, secondOrder]; await testFactory.marketBuyTestAsync(orders, 1.5); }); @@ -390,7 +396,7 @@ blockchainTests('Forwarder integration tests', env => { it('should buy an ERC721 asset from a single order', async () => { const erc721Order = await maker.signOrderAsync({ makerAssetAmount: new BigNumber(1), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, nftId), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, nftId).callAsync(), takerFeeAssetData: wethAssetData, }); await testFactory.marketBuyTestAsync([erc721Order], 1); @@ -398,14 +404,14 @@ blockchainTests('Forwarder integration tests', env => { it('should buy an ERC721 asset and pay a WETH fee', async () => { const erc721orderWithWethFee = await maker.signOrderAsync({ makerAssetAmount: new BigNumber(1), - makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, nftId), + makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, nftId).callAsync(), takerFee: toBaseUnitAmount(1), takerFeeAssetData: wethAssetData, }); await testFactory.marketBuyTestAsync([erc721orderWithWethFee], 1); }); it('should fail to fill an order with a fee denominated in an asset other than makerAsset or WETH', async () => { - const takerFeeAssetData = await devUtils.encodeERC20AssetData.callAsync(anotherErc20Token.address); + const takerFeeAssetData = await devUtils.encodeERC20AssetData(anotherErc20Token.address).callAsync(); const order = await maker.signOrderAsync({ takerFeeAssetData, takerFee: toBaseUnitAmount(1), @@ -483,17 +489,18 @@ blockchainTests('Forwarder integration tests', env => { await balanceStore.updateBalancesAsync(); // Execute test case - const tx = await forwarder.marketBuyOrdersWithEth.awaitTransactionSuccessAsync( - [order], - desiredMakerAssetFillAmount, - [order.signature], - constants.ZERO_AMOUNT, - forwarderFeeRecipient.address, - { + const tx = await forwarder + .marketBuyOrdersWithEth( + [order], + desiredMakerAssetFillAmount, + [order.signature], + constants.ZERO_AMOUNT, + forwarderFeeRecipient.address, + ) + .awaitTransactionSuccessAsync({ value: ethValue, from: taker.address, - }, - ); + }); // Compute expected balances const expectedBalances = LocalBalanceStore.create(devUtils, balanceStore); @@ -539,17 +546,18 @@ blockchainTests('Forwarder integration tests', env => { await balanceStore.updateBalancesAsync(); // Execute test case - const tx = await forwarder.marketBuyOrdersWithEth.awaitTransactionSuccessAsync( - [order], - desiredMakerAssetFillAmount, - [order.signature], - constants.ZERO_AMOUNT, - forwarderFeeRecipient.address, - { + const tx = await forwarder + .marketBuyOrdersWithEth( + [order], + desiredMakerAssetFillAmount, + [order.signature], + constants.ZERO_AMOUNT, + forwarderFeeRecipient.address, + ) + .awaitTransactionSuccessAsync({ value: takerAssetFillAmount.plus(DeploymentManager.protocolFee), from: taker.address, - }, - ); + }); // Compute expected balances const expectedBalances = LocalBalanceStore.create(devUtils, balanceStore); diff --git a/contracts/integrations/test/forwarder/forwarder_test_factory.ts b/contracts/integrations/test/forwarder/forwarder_test_factory.ts index e8b5ec3074..a0f7dcf872 100644 --- a/contracts/integrations/test/forwarder/forwarder_test_factory.ts +++ b/contracts/integrations/test/forwarder/forwarder_test_factory.ts @@ -46,7 +46,7 @@ export class ForwarderTestFactory { const forwarderFeePercentage = options.forwarderFeePercentage || 0; const orderInfoBefore = await Promise.all( - orders.map(order => this._deployment.exchange.getOrderInfo.callAsync(order)), + orders.map(order => this._deployment.exchange.getOrderInfo(order).callAsync()), ); const expectedOrderStatuses = orderInfoBefore.map((orderInfo, i) => fractionalNumberOfOrdersToFill >= i + 1 && orderInfo.orderStatus === OrderStatus.Fillable @@ -63,17 +63,18 @@ export class ForwarderTestFactory { const ethSpentOnForwarderFee = getPercentageOfValue(wethSpentAmount, forwarderFeePercentage); const feePercentage = getPercentageOfValue(constants.PERCENTAGE_DENOMINATOR, forwarderFeePercentage); - const tx = this._forwarder.marketBuyOrdersWithEth.awaitTransactionSuccessAsync( - orders, - makerAssetAcquiredAmount, - orders.map(signedOrder => signedOrder.signature), - feePercentage, - this._forwarderFeeRecipient.address, - { + const tx = this._forwarder + .marketBuyOrdersWithEth( + orders, + makerAssetAcquiredAmount, + orders.map(signedOrder => signedOrder.signature), + feePercentage, + this._forwarderFeeRecipient.address, + ) + .awaitTransactionSuccessAsync({ value: wethSpentAmount.plus(ethSpentOnForwarderFee).plus(ethValueAdjustment), from: this._taker.address, - }, - ); + }); if (options.revertError !== undefined) { await expect(tx).to.revertWith(options.revertError); @@ -89,7 +90,7 @@ export class ForwarderTestFactory { options: Partial = {}, ): Promise { const orderInfoBefore = await Promise.all( - orders.map(order => this._deployment.exchange.getOrderInfo.callAsync(order)), + orders.map(order => this._deployment.exchange.getOrderInfo(order).callAsync()), ); const expectedOrderStatuses = orderInfoBefore.map((orderInfo, i) => fractionalNumberOfOrdersToFill >= i + 1 && orderInfo.orderStatus === OrderStatus.Fillable @@ -108,16 +109,17 @@ export class ForwarderTestFactory { const ethSpentOnForwarderFee = getPercentageOfValue(wethSpentAmount, forwarderFeePercentage); const feePercentage = getPercentageOfValue(constants.PERCENTAGE_DENOMINATOR, forwarderFeePercentage); - const tx = this._forwarder.marketSellOrdersWithEth.awaitTransactionSuccessAsync( - orders, - orders.map(signedOrder => signedOrder.signature), - feePercentage, - this._forwarderFeeRecipient.address, - { + const tx = this._forwarder + .marketSellOrdersWithEth( + orders, + orders.map(signedOrder => signedOrder.signature), + feePercentage, + this._forwarderFeeRecipient.address, + ) + .awaitTransactionSuccessAsync({ value: wethSpentAmount.plus(ethSpentOnForwarderFee), from: this._taker.address, - }, - ); + }); if (options.revertError !== undefined) { await expect(tx).to.revertWith(options.revertError); @@ -141,7 +143,7 @@ export class ForwarderTestFactory { // Get updated order info const orderInfoAfter = await Promise.all( - orders.map(order => this._deployment.exchange.getOrderInfo.callAsync(order)), + orders.map(order => this._deployment.exchange.getOrderInfo(order).callAsync()), ); // Check order statuses for (const [i, orderInfo] of orderInfoAfter.entries()) { diff --git a/contracts/integrations/test/framework-unit-tests/deployment_manager_test.ts b/contracts/integrations/test/framework-unit-tests/deployment_manager_test.ts index 953ddc2606..0b0746f412 100644 --- a/contracts/integrations/test/framework-unit-tests/deployment_manager_test.ts +++ b/contracts/integrations/test/framework-unit-tests/deployment_manager_test.ts @@ -18,20 +18,20 @@ blockchainTests('Deployment Manager', env => { authorizedContracts: Authorizable[], ): Promise { for (const authorized of authorizedContracts) { - expect(await authorized.authorized.callAsync(authorizedAddress)).to.be.true(); + expect(await authorized.authorized(authorizedAddress).callAsync()).to.be.true(); } } async function batchAssertOwnerAsync(ownerAddress: string, owners: Ownable[]): Promise { for (const ownerContract of owners) { - expect(await ownerContract.owner.callAsync()).to.be.eq(ownerAddress); + expect(await ownerContract.owner().callAsync()).to.be.eq(ownerAddress); } } describe('asset proxy owner', () => { it('should be owned by `owner`', async () => { // Ensure that the owners of the asset proxy only contain the owner. - const owners = await deploymentManager.governor.getOwners.callAsync(); + const owners = await deploymentManager.governor.getOwners().callAsync(); expect(owners).to.be.deep.eq([owner]); }); }); @@ -65,25 +65,33 @@ blockchainTests('Deployment Manager', env => { it('should have the correct authorities list', async () => { // The multi-asset proxy should only have the exchange in the authorities list. - const authorities = await deploymentManager.assetProxies.multiAssetProxy.getAuthorizedAddresses.callAsync(); + const authorities = await deploymentManager.assetProxies.multiAssetProxy + .getAuthorizedAddresses() + .callAsync(); expect(authorities).to.be.deep.eq([deploymentManager.exchange.address]); // The other asset proxies should have the exchange and the multi-asset proxy in their // authorities list. - const erc20ProxyAuthorities = await deploymentManager.assetProxies.erc20Proxy.getAuthorizedAddresses.callAsync(); + const erc20ProxyAuthorities = await deploymentManager.assetProxies.erc20Proxy + .getAuthorizedAddresses() + .callAsync(); expect(erc20ProxyAuthorities).to.deep.eq([ deploymentManager.staking.zrxVault.address, deploymentManager.assetProxies.multiAssetProxy.address, deploymentManager.exchange.address, ]); - const erc1155ProxyAuthorities = await deploymentManager.assetProxies.erc1155Proxy.getAuthorizedAddresses.callAsync(); + const erc1155ProxyAuthorities = await deploymentManager.assetProxies.erc1155Proxy + .getAuthorizedAddresses() + .callAsync(); expect(erc1155ProxyAuthorities).to.deep.eq([ deploymentManager.assetProxies.multiAssetProxy.address, deploymentManager.exchange.address, ]); - const erc721ProxyAuthorities = await deploymentManager.assetProxies.erc721Proxy.getAuthorizedAddresses.callAsync(); + const erc721ProxyAuthorities = await deploymentManager.assetProxies.erc721Proxy + .getAuthorizedAddresses() + .callAsync(); expect(erc721ProxyAuthorities).to.deep.eq([ deploymentManager.assetProxies.multiAssetProxy.address, deploymentManager.exchange.address, @@ -93,7 +101,7 @@ blockchainTests('Deployment Manager', env => { describe('exchange', () => { it('should be owned by the asset proxy owner', async () => { - const exchangeOwner = await deploymentManager.exchange.owner.callAsync(); + const exchangeOwner = await deploymentManager.exchange.owner().callAsync(); expect(exchangeOwner).to.be.eq(deploymentManager.governor.address); }); @@ -101,66 +109,66 @@ blockchainTests('Deployment Manager', env => { TODO(jalextowle): This test should be enabled once the Exchange is made an Authorizable contract. it('should have authorized the asset proxy owner', async () => { - const isAuthorized = await deploymentManager.exchange.owner.callAsync( + const isAuthorized = await deploymentManager.exchange.owner( deploymentManager.governor.address, - ); + ).callAsync(); expect(isAuthorized).to.be.true(); }); */ it('should have registered the staking proxy', async () => { - const feeCollector = await deploymentManager.exchange.protocolFeeCollector.callAsync(); + const feeCollector = await deploymentManager.exchange.protocolFeeCollector().callAsync(); expect(feeCollector).to.be.eq(deploymentManager.staking.stakingProxy.address); }); it('should have set the protocol fee multiplier', async () => { - const feeMultiplier = await deploymentManager.exchange.protocolFeeMultiplier.callAsync(); + const feeMultiplier = await deploymentManager.exchange.protocolFeeMultiplier().callAsync(); expect(feeMultiplier).bignumber.to.be.eq(DeploymentManager.protocolFeeMultiplier); }); }); describe('staking', () => { it('should be owned by the asset proxy owner', async () => { - const stakingOwner = await deploymentManager.staking.stakingProxy.owner.callAsync(); + const stakingOwner = await deploymentManager.staking.stakingProxy.owner().callAsync(); expect(stakingOwner).to.be.eq(deploymentManager.governor.address); }); it('should have authorized the asset proxy owner in the staking proxy', async () => { - const isAuthorized = await deploymentManager.staking.stakingProxy.authorized.callAsync( - deploymentManager.governor.address, - ); + const isAuthorized = await deploymentManager.staking.stakingProxy + .authorized(deploymentManager.governor.address) + .callAsync(); expect(isAuthorized).to.be.true(); }); it('should have registered the exchange in the staking proxy', async () => { - const isValid = await deploymentManager.staking.stakingProxy.validExchanges.callAsync( - deploymentManager.exchange.address, - ); + const isValid = await deploymentManager.staking.stakingProxy + .validExchanges(deploymentManager.exchange.address) + .callAsync(); expect(isValid).to.be.true(); }); it('should have registered the staking contract in the staking proxy', async () => { - const stakingContract = await deploymentManager.staking.stakingProxy.stakingContract.callAsync(); + const stakingContract = await deploymentManager.staking.stakingProxy.stakingContract().callAsync(); expect(stakingContract).to.be.eq(deploymentManager.staking.stakingLogic.address); }); it('should have registered the weth contract in the staking contract', async () => { - const weth = await deploymentManager.staking.stakingWrapper.testWethAddress.callAsync(); + const weth = await deploymentManager.staking.stakingWrapper.testWethAddress().callAsync(); expect(weth).to.be.eq(deploymentManager.tokens.weth.address); }); it('should have registered the zrx vault in the staking contract', async () => { - const zrxVault = await deploymentManager.staking.stakingWrapper.testZrxVaultAddress.callAsync(); + const zrxVault = await deploymentManager.staking.stakingWrapper.testZrxVaultAddress().callAsync(); expect(zrxVault).to.be.eq(deploymentManager.staking.zrxVault.address); }); it('should have registered the staking proxy in the zrx vault', async () => { - const stakingProxy = await deploymentManager.staking.zrxVault.stakingProxyAddress.callAsync(); + const stakingProxy = await deploymentManager.staking.zrxVault.stakingProxyAddress().callAsync(); expect(stakingProxy).to.be.eq(deploymentManager.staking.stakingProxy.address); }); it('should have correctly set the params', async () => { - const params = await deploymentManager.staking.stakingWrapper.getParams.callAsync(); + const params = await deploymentManager.staking.stakingWrapper.getParams().callAsync(); expect(params).to.be.deep.eq([ stakingConstants.DEFAULT_PARAMS.epochDurationInSeconds, stakingConstants.DEFAULT_PARAMS.rewardDelegatedStakeWeight, diff --git a/contracts/integrations/test/framework-unit-tests/function_assertion_test.ts b/contracts/integrations/test/framework-unit-tests/function_assertion_test.ts index 42c067a76b..34de637869 100644 --- a/contracts/integrations/test/framework-unit-tests/function_assertion_test.ts +++ b/contracts/integrations/test/framework-unit-tests/function_assertion_test.ts @@ -24,11 +24,14 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => { describe('executeAsync', () => { it('should call the before function with the provided arguments', async () => { let sideEffectTarget = ZERO_AMOUNT; - const assertion = new FunctionAssertion(exampleContract.returnInteger, { - before: async (_input: BigNumber) => { - sideEffectTarget = randomInput; + const assertion = new FunctionAssertion( + exampleContract.returnInteger.bind(exampleContract), + { + before: async (_input: BigNumber) => { + sideEffectTarget = randomInput; + }, }, - }); + ); const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256); await assertion.executeAsync(randomInput); expect(sideEffectTarget).bignumber.to.be.eq(randomInput); @@ -36,43 +39,52 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => { it('should call the after function with the provided arguments', async () => { let sideEffectTarget = ZERO_AMOUNT; - const assertion = new FunctionAssertion(exampleContract.returnInteger, { - after: async (_beforeInfo: any, _result: FunctionResult, input: BigNumber) => { - sideEffectTarget = input; + const assertion = new FunctionAssertion( + exampleContract.returnInteger.bind(exampleContract), + { + after: async (_beforeInfo: any, _result: FunctionResult, input: BigNumber) => { + sideEffectTarget = input; + }, }, - }); + ); const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256); await assertion.executeAsync(randomInput); expect(sideEffectTarget).bignumber.to.be.eq(randomInput); }); it('should not fail immediately if the wrapped function fails', async () => { - const assertion = new FunctionAssertion<{}>(exampleContract.emptyRevert); + const assertion = new FunctionAssertion<{}, void>(exampleContract.emptyRevert.bind(exampleContract)); await assertion.executeAsync(); }); it('should pass the return value of "before" to "after"', async () => { const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256); let sideEffectTarget = ZERO_AMOUNT; - const assertion = new FunctionAssertion(exampleContract.returnInteger, { - before: async (_input: BigNumber) => { - return randomInput; - }, - after: async (beforeInfo: any, _result: FunctionResult, _input: BigNumber) => { - sideEffectTarget = beforeInfo; + const assertion = new FunctionAssertion( + exampleContract.returnInteger.bind(exampleContract), + { + before: async (_input: BigNumber) => { + return randomInput; + }, + after: async (beforeInfo: any, _result: FunctionResult, _input: BigNumber) => { + sideEffectTarget = beforeInfo; + }, }, - }); + ); await assertion.executeAsync(randomInput); expect(sideEffectTarget).bignumber.to.be.eq(randomInput); }); it('should pass the result from the function call to "after"', async () => { let sideEffectTarget = ZERO_AMOUNT; - const assertion = new FunctionAssertion(exampleContract.returnInteger, { - after: async (_beforeInfo: any, result: FunctionResult, _input: BigNumber) => { - sideEffectTarget = result.data; + const assertion = new FunctionAssertion( + exampleContract.returnInteger.bind(exampleContract), + { + after: async (_beforeInfo: any, result: FunctionResult, _input: BigNumber) => { + sideEffectTarget = result.data; + }, }, - }); + ); const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256); await assertion.executeAsync(randomInput); expect(sideEffectTarget).bignumber.to.be.eq(randomInput); @@ -80,7 +92,7 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => { it('should pass the receipt from the function call to "after"', async () => { let sideEffectTarget: TransactionReceiptWithDecodedLogs; - const assertion = new FunctionAssertion(exampleContract.emitEvent, { + const assertion = new FunctionAssertion(exampleContract.emitEvent.bind(exampleContract), { after: async (_beforeInfo: any, result: FunctionResult, _input: string) => { if (result.receipt) { sideEffectTarget = result.receipt; @@ -101,7 +113,7 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => { it('should pass the error to "after" if the function call fails', async () => { let sideEffectTarget: Error; - const assertion = new FunctionAssertion(exampleContract.stringRevert, { + const assertion = new FunctionAssertion(exampleContract.stringRevert.bind(exampleContract), { after: async (_beforeInfo: any, result: FunctionResult, _input: string) => { sideEffectTarget = result.data; }, diff --git a/contracts/integrations/test/function-assertions/createStakingPool.ts b/contracts/integrations/test/function-assertions/createStakingPool.ts index 8338456f2c..b2cd793fe9 100644 --- a/contracts/integrations/test/function-assertions/createStakingPool.ts +++ b/contracts/integrations/test/function-assertions/createStakingPool.ts @@ -15,13 +15,13 @@ import { DeploymentManager } from '../deployment_manager'; export function validCreateStakingPoolAssertion( deployment: DeploymentManager, pools: StakingPoolById, -): FunctionAssertion { +): FunctionAssertion { const { stakingWrapper } = deployment.staking; return new FunctionAssertion(stakingWrapper.createStakingPool, { // Returns the expected ID of th created pool before: async () => { - const lastPoolId = await stakingWrapper.lastPoolId.callAsync(); + const lastPoolId = await stakingWrapper.lastPoolId().callAsync(); // Effectively the last poolId + 1, but as a bytestring return `0x${new BigNumber(lastPoolId) .plus(1) diff --git a/contracts/integrations/test/function-assertions/decreaseStakingPoolOperatorShare.ts b/contracts/integrations/test/function-assertions/decreaseStakingPoolOperatorShare.ts index 360e0ba530..f27816c59c 100644 --- a/contracts/integrations/test/function-assertions/decreaseStakingPoolOperatorShare.ts +++ b/contracts/integrations/test/function-assertions/decreaseStakingPoolOperatorShare.ts @@ -12,15 +12,15 @@ import { DeploymentManager } from '../deployment_manager'; export function validDecreaseStakingPoolOperatorShareAssertion( deployment: DeploymentManager, pools: StakingPoolById, -): FunctionAssertion<{}> { +): FunctionAssertion<{}, void> { const { stakingWrapper } = deployment.staking; - return new FunctionAssertion<{}>(stakingWrapper.decreaseStakingPoolOperatorShare, { + return new FunctionAssertion<{}, void>(stakingWrapper.decreaseStakingPoolOperatorShare, { after: async (_beforeInfo, _result: FunctionResult, poolId: string, expectedOperatorShare: number) => { logUtils.log(`decreaseStakingPoolOperatorShare(${poolId}, ${expectedOperatorShare})`); // Checks that the on-chain pool's operator share has been updated. - const { operatorShare } = await stakingWrapper.getStakingPool.callAsync(poolId); + const { operatorShare } = await stakingWrapper.getStakingPool(poolId).callAsync(); expect(operatorShare).to.bignumber.equal(expectedOperatorShare); // Updates the pool in local state. pools[poolId].operatorShare = operatorShare; diff --git a/contracts/integrations/test/function-assertions/moveStake.ts b/contracts/integrations/test/function-assertions/moveStake.ts index 38a347c27f..2404e06240 100644 --- a/contracts/integrations/test/function-assertions/moveStake.ts +++ b/contracts/integrations/test/function-assertions/moveStake.ts @@ -81,10 +81,10 @@ export function validMoveStakeAssertion( globalStake: GlobalStakeByStatus, ownerStake: OwnerStakeByStatus, pools: StakingPoolById, -): FunctionAssertion<{}> { +): FunctionAssertion<{}, void> { const { stakingWrapper } = deployment.staking; - return new FunctionAssertion<{}>(stakingWrapper.moveStake, { + return new FunctionAssertion<{}, void>(stakingWrapper.moveStake, { after: async ( _beforeInfo, _result, @@ -107,30 +107,29 @@ export function validMoveStakeAssertion( // Fetches on-chain owner stake balances and checks against local balances const ownerUndelegatedStake = { ...new StoredBalance(), - ...(await stakingWrapper.getOwnerStakeByStatus.callAsync(owner, StakeStatus.Undelegated)), + ...(await stakingWrapper.getOwnerStakeByStatus(owner, StakeStatus.Undelegated).callAsync()), }; const ownerDelegatedStake = { ...new StoredBalance(), - ...(await stakingWrapper.getOwnerStakeByStatus.callAsync(owner, StakeStatus.Delegated)), + ...(await stakingWrapper.getOwnerStakeByStatus(owner, StakeStatus.Delegated).callAsync()), }; expect(ownerUndelegatedStake).to.deep.equal(ownerStake[StakeStatus.Undelegated]); expect(ownerDelegatedStake).to.deep.equal(ownerStake[StakeStatus.Delegated].total); // Fetches on-chain global stake balances and checks against local balances - const globalUndelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync( - StakeStatus.Undelegated, - ); - const globalDelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync(StakeStatus.Delegated); + const globalUndelegatedStake = await stakingWrapper + .getGlobalStakeByStatus(StakeStatus.Undelegated) + .callAsync(); + const globalDelegatedStake = await stakingWrapper.getGlobalStakeByStatus(StakeStatus.Delegated).callAsync(); expect(globalUndelegatedStake).to.deep.equal(globalStake[StakeStatus.Undelegated]); expect(globalDelegatedStake).to.deep.equal(globalStake[StakeStatus.Delegated]); // Fetches on-chain pool stake balances and checks against local balances for (const poolId of updatedPools) { - const stakeDelegatedByOwner = await stakingWrapper.getStakeDelegatedToPoolByOwner.callAsync( - owner, - poolId, - ); - const totalStakeDelegated = await stakingWrapper.getTotalStakeDelegatedToPool.callAsync(poolId); + const stakeDelegatedByOwner = await stakingWrapper + .getStakeDelegatedToPoolByOwner(owner, poolId) + .callAsync(); + const totalStakeDelegated = await stakingWrapper.getTotalStakeDelegatedToPool(poolId).callAsync(); expect(stakeDelegatedByOwner).to.deep.equal(ownerStake[StakeStatus.Delegated][poolId]); expect(totalStakeDelegated).to.deep.equal(pools[poolId].delegatedStake); } diff --git a/contracts/integrations/test/function-assertions/stake.ts b/contracts/integrations/test/function-assertions/stake.ts index 70a8627880..f1893d82ed 100644 --- a/contracts/integrations/test/function-assertions/stake.ts +++ b/contracts/integrations/test/function-assertions/stake.ts @@ -28,7 +28,7 @@ export function validStakeAssertion( balanceStore: BlockchainBalanceStore, globalStake: GlobalStakeByStatus, ownerStake: OwnerStakeByStatus, -): FunctionAssertion { +): FunctionAssertion { const { stakingWrapper, zrxVault } = deployment.staking; return new FunctionAssertion(stakingWrapper.stake, { @@ -39,7 +39,7 @@ export function validStakeAssertion( txData.from as string, zrxVault.address, amount, - await deployment.devUtils.encodeERC20AssetData.callAsync(deployment.tokens.zrx.address), + await deployment.devUtils.encodeERC20AssetData(deployment.tokens.zrx.address).callAsync(), ); return expectedBalances; }, @@ -56,19 +56,18 @@ export function validStakeAssertion( balanceStore.assertEquals(expectedBalances); // Checks that the owner's undelegated stake has increased by the stake amount - const ownerUndelegatedStake = await stakingWrapper.getOwnerStakeByStatus.callAsync( - txData.from as string, - StakeStatus.Undelegated, - ); + const ownerUndelegatedStake = await stakingWrapper + .getOwnerStakeByStatus(txData.from as string, StakeStatus.Undelegated) + .callAsync(); const expectedOwnerUndelegatedStake = expectedUndelegatedStake(ownerStake, amount); expect(ownerUndelegatedStake, 'Owner undelegated stake').to.deep.equal(expectedOwnerUndelegatedStake); // Updates local state accordingly ownerStake[StakeStatus.Undelegated] = expectedOwnerUndelegatedStake; // Checks that the global undelegated stake has also increased by the stake amount - const globalUndelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync( - StakeStatus.Undelegated, - ); + const globalUndelegatedStake = await stakingWrapper + .getGlobalStakeByStatus(StakeStatus.Undelegated) + .callAsync(); const expectedGlobalUndelegatedStake = expectedUndelegatedStake(globalStake, amount); expect(globalUndelegatedStake, 'Global undelegated stake').to.deep.equal(expectedGlobalUndelegatedStake); // Updates local state accordingly diff --git a/contracts/integrations/test/function-assertions/unstake.ts b/contracts/integrations/test/function-assertions/unstake.ts index 90a7c1d8cb..64709cbeee 100644 --- a/contracts/integrations/test/function-assertions/unstake.ts +++ b/contracts/integrations/test/function-assertions/unstake.ts @@ -28,7 +28,7 @@ export function validUnstakeAssertion( balanceStore: BlockchainBalanceStore, globalStake: GlobalStakeByStatus, ownerStake: OwnerStakeByStatus, -): FunctionAssertion { +): FunctionAssertion { const { stakingWrapper, zrxVault } = deployment.staking; return new FunctionAssertion(stakingWrapper.unstake, { @@ -39,7 +39,7 @@ export function validUnstakeAssertion( zrxVault.address, txData.from as string, amount, - await deployment.devUtils.encodeERC20AssetData.callAsync(deployment.tokens.zrx.address), + await deployment.devUtils.encodeERC20AssetData(deployment.tokens.zrx.address).callAsync(), ); return expectedBalances; }, @@ -56,19 +56,18 @@ export function validUnstakeAssertion( balanceStore.assertEquals(expectedBalances); // Checks that the owner's undelegated stake has decreased by the stake amount - const ownerUndelegatedStake = await stakingWrapper.getOwnerStakeByStatus.callAsync( - txData.from as string, - StakeStatus.Undelegated, - ); + const ownerUndelegatedStake = await stakingWrapper + .getOwnerStakeByStatus(txData.from as string, StakeStatus.Undelegated) + .callAsync(); const expectedOwnerUndelegatedStake = expectedUndelegatedStake(ownerStake, amount); expect(ownerUndelegatedStake, 'Owner undelegated stake').to.deep.equal(expectedOwnerUndelegatedStake); // Updates local state accordingly ownerStake[StakeStatus.Undelegated] = expectedOwnerUndelegatedStake; // Checks that the global undelegated stake has also decreased by the stake amount - const globalUndelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync( - StakeStatus.Undelegated, - ); + const globalUndelegatedStake = await stakingWrapper + .getGlobalStakeByStatus(StakeStatus.Undelegated) + .callAsync(); const expectedGlobalUndelegatedStake = expectedUndelegatedStake(globalStake, amount); expect(globalUndelegatedStake, 'Global undelegated stake').to.deep.equal(expectedGlobalUndelegatedStake); // Updates local state accordingly diff --git a/contracts/integrations/test/internal-integration-tests/deployment_test.ts b/contracts/integrations/test/internal-integration-tests/deployment_test.ts index f569dac429..22d9109d39 100644 --- a/contracts/integrations/test/internal-integration-tests/deployment_test.ts +++ b/contracts/integrations/test/internal-integration-tests/deployment_test.ts @@ -115,7 +115,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { ); // Authorize owner in the staking proxy. - await stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner); + await stakingProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync(); // Deploy the asset proxy contracts. erc20Proxy = await ERC20ProxyContract.deployFrom0xArtifactAsync( @@ -163,12 +163,11 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { assetProxyId: string, ): Promise { // Register the asset proxy. - const receipt = await registrationContract.registerAssetProxy.awaitTransactionSuccessAsync( - assetProxyAddress, - { + const receipt = await registrationContract + .registerAssetProxy(assetProxyAddress) + .awaitTransactionSuccessAsync({ from: owner, - }, - ); + }); // Ensure that the correct event was logged. const logs = filterLogsToArguments( @@ -178,7 +177,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { expect(logs).to.be.deep.eq([{ id: assetProxyId, assetProxy: assetProxyAddress }]); // Ensure that the asset proxy was actually registered. - const proxyAddress = await registrationContract.getAssetProxy.callAsync(assetProxyId); + const proxyAddress = await registrationContract.getAssetProxy(assetProxyId).callAsync(); expect(proxyAddress).to.be.eq(assetProxyAddress); } @@ -188,10 +187,9 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { newAuthorityAddress: string, ): Promise { // Authorize the address. - const receipt = await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync( - newAuthorityAddress, - { from: owner }, - ); + const receipt = await authorizable + .addAuthorizedAddress(newAuthorityAddress) + .awaitTransactionSuccessAsync({ from: owner }); // Ensure that the correct log was emitted. const logs = filterLogsToArguments( @@ -201,7 +199,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { expect(logs).to.be.deep.eq([{ target: newAuthorityAddress, caller: owner }]); // Ensure that the address was actually authorized. - const wasAuthorized = await authorizable.authorized.callAsync(newAuthorityAddress); + const wasAuthorized = await authorizable.authorized(newAuthorityAddress).callAsync(); expect(wasAuthorized).to.be.true(); } @@ -261,13 +259,13 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { describe('staking specific', () => { it('should have properly configured the staking proxy with the logic contract', async () => { // Ensure that the registered staking contract is correct. - const stakingAddress = await stakingProxy.stakingContract.callAsync(); + const stakingAddress = await stakingProxy.stakingContract().callAsync(); expect(stakingAddress).to.be.eq(staking.address); }); it('should have initialized the correct parameters in the staking proxy', async () => { // Ensure that the correct parameters were set. - const params = await stakingWrapper.getParams.callAsync(); + const params = await stakingWrapper.getParams().callAsync(); expect(params).to.be.deep.eq([ stakingConstants.DEFAULT_PARAMS.epochDurationInSeconds, stakingConstants.DEFAULT_PARAMS.rewardDelegatedStakeWeight, @@ -281,7 +279,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { describe('exchange and staking integration', () => { it('should successfully register the exchange in the staking contract', async () => { // Register the exchange. - const receipt = await stakingWrapper.addExchangeAddress.awaitTransactionSuccessAsync(exchange.address, { + const receipt = await stakingWrapper.addExchangeAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner, }); @@ -293,18 +291,17 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { expect(logs).to.be.deep.eq([{ exchangeAddress: exchange.address }]); // Ensure that the exchange was registered. - const wasRegistered = await stakingWrapper.validExchanges.callAsync(exchange.address); + const wasRegistered = await stakingWrapper.validExchanges(exchange.address).callAsync(); expect(wasRegistered).to.be.true(); }); it('should successfully register the staking contract in the exchange', async () => { // Register the staking contract. - const receipt = await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync( - stakingProxy.address, - { + const receipt = await exchange + .setProtocolFeeCollectorAddress(stakingProxy.address) + .awaitTransactionSuccessAsync({ from: owner, - }, - ); + }); // Ensure that the correct events were logged. const logs = filterLogsToArguments( @@ -319,15 +316,15 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { ]); // Ensure that the staking contract was registered. - const feeCollector = await exchange.protocolFeeCollector.callAsync(); + const feeCollector = await exchange.protocolFeeCollector().callAsync(); expect(feeCollector).to.be.eq(stakingProxy.address); }); it('should successfully update the protocol fee multiplier in the staking contract', async () => { // Update the protocol fee multiplier. - const receipt = await exchange.setProtocolFeeMultiplier.awaitTransactionSuccessAsync( - protocolFeeMultiplier, - ); + const receipt = await exchange + .setProtocolFeeMultiplier(protocolFeeMultiplier) + .awaitTransactionSuccessAsync(); // Ensure that the correct events were logged. const logs = filterLogsToArguments( @@ -342,7 +339,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { ]); // Ensure that the protocol fee multiplier was set correctly. - const multiplier = await exchange.protocolFeeMultiplier.callAsync(); + const multiplier = await exchange.protocolFeeMultiplier().callAsync(); expect(multiplier).bignumber.to.be.eq(protocolFeeMultiplier); }); }); @@ -353,7 +350,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { // to the asset proxy owner. async function transferAuthorizationAndAssertSuccessAsync(contract: Authorizable): Promise { // Remove authorization from the old owner. - let receipt = await contract.removeAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner }); + let receipt = await contract.removeAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner }); // Ensure that the correct log was recorded. let logs = filterLogsToArguments( @@ -363,11 +360,11 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { expect(logs).to.be.deep.eq([{ target: owner, caller: owner }]); // Ensure that the owner was actually removed. - let isAuthorized = await contract.authorized.callAsync(owner); + let isAuthorized = await contract.authorized(owner).callAsync(); expect(isAuthorized).to.be.false(); // Authorize the asset-proxy owner. - receipt = await contract.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address, { + receipt = await contract.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync({ from: owner, }); @@ -379,17 +376,17 @@ blockchainTests('Deployment and Configuration End to End Tests', env => { expect(logs).to.be.deep.eq([{ target: governor.address, caller: owner }]); // Ensure that the asset-proxy owner was actually authorized. - isAuthorized = await contract.authorized.callAsync(governor.address); + isAuthorized = await contract.authorized(governor.address).callAsync(); expect(isAuthorized).to.be.true(); } // Transfers ownership of a contract to the asset-proxy owner, and ensures that the change was actually made. async function transferOwnershipAndAssertSuccessAsync(contract: Ownable): Promise { // Transfer ownership to the new owner. - await contract.transferOwnership.awaitTransactionSuccessAsync(governor.address, { from: owner }); + await contract.transferOwnership(governor.address).awaitTransactionSuccessAsync({ from: owner }); // Ensure that the owner address has been updated. - const ownerAddress = await contract.owner.callAsync(); + const ownerAddress = await contract.owner().callAsync(); expect(ownerAddress).to.be.eq(governor.address); } diff --git a/contracts/integrations/test/internal-integration-tests/exchange_wrapper_test.ts b/contracts/integrations/test/internal-integration-tests/exchange_wrapper_test.ts index 14df0ba1f5..ffedd80f11 100644 --- a/contracts/integrations/test/internal-integration-tests/exchange_wrapper_test.ts +++ b/contracts/integrations/test/internal-integration-tests/exchange_wrapper_test.ts @@ -1,15 +1,12 @@ -import { artifacts as assetProxyArtifacts } from '@0x/contracts-asset-proxy'; import { DevUtilsContract } from '@0x/contracts-dev-utils'; -import { artifacts as erc20Artifacts, ERC20TokenEvents, ERC20TokenTransferEventArgs } from '@0x/contracts-erc20'; +import { ERC20TokenEvents, ERC20TokenTransferEventArgs } from '@0x/contracts-erc20'; import { - artifacts as exchangeArtifacts, BlockchainBalanceStore, IExchangeEvents, IExchangeFillEventArgs, LocalBalanceStore, } from '@0x/contracts-exchange'; import { ReferenceFunctions } from '@0x/contracts-exchange-libs'; -import { artifacts as stakingArtifacts } from '@0x/contracts-staking'; import { blockchainTests, constants, @@ -19,7 +16,6 @@ import { Numberish, provider, toBaseUnitAmount, - TransactionHelper, verifyEvents, } from '@0x/contracts-test-utils'; import { ExchangeRevertErrors, orderHashUtils } from '@0x/order-utils'; @@ -55,7 +51,6 @@ blockchainTests.resets('Exchange wrappers', env => { let localBalances: LocalBalanceStore; let wethAssetData: string; - let txHelper: TransactionHelper; before(async () => { [feeRecipient] = await env.getAccountAddressesAsync(); @@ -70,10 +65,10 @@ blockchainTests.resets('Exchange wrappers', env => { name: 'market maker', deployment, orderConfig: { - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[0].address), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[1].address), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[2].address), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[2].address), + makerAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[0].address).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[1].address).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[2].address).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[2].address).callAsync(), feeRecipientAddress: feeRecipient, }, }); @@ -111,14 +106,7 @@ blockchainTests.resets('Exchange wrappers', env => { initialLocalBalances = LocalBalanceStore.create(devUtils, blockchainBalances); - wethAssetData = await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address); - - txHelper = new TransactionHelper(env.web3Wrapper, { - ...assetProxyArtifacts, - ...exchangeArtifacts, - ...stakingArtifacts, - ...erc20Artifacts, - }); + wethAssetData = await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(); }); beforeEach(async () => { @@ -323,15 +311,16 @@ blockchainTests.resets('Exchange wrappers', env => { makerAssetAmount: toBaseUnitAmount(new BigNumber(100)), takerAssetAmount: toBaseUnitAmount(new BigNumber(200)), }); - const takerAssetFilledAmount = signedOrder.takerAssetAmount.div(2); + const takerAssetFilledAmount = signedOrder.takerAssetAmount.div(5); - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( - deployment.exchange.fillOrKillOrder, + const contractFn = deployment.exchange.fillOrKillOrder( signedOrder, takerAssetFilledAmount, signedOrder.signature, - { from: taker.address, gasPrice: DeploymentManager.gasPrice, value }, ); + const callData = { from: taker.address, gasPrice: DeploymentManager.gasPrice, value }; + const fillResults = await contractFn.callAsync(callData); + const receipt = await contractFn.awaitTransactionSuccessAsync(callData); const expectedFillResults = calculateScaledFillResultsWithTaker(signedOrder, takerAssetFilledAmount); @@ -369,12 +358,13 @@ blockchainTests.resets('Exchange wrappers', env => { }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder); const expectedError = new ExchangeRevertErrors.OrderStatusError(orderHashHex, OrderStatus.Expired); - const tx = deployment.exchange.fillOrKillOrder.awaitTransactionSuccessAsync( - signedOrder, - signedOrder.takerAssetAmount, - signedOrder.signature, - { from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee }, - ); + const tx = deployment.exchange + .fillOrKillOrder(signedOrder, signedOrder.takerAssetAmount, signedOrder.signature) + .awaitTransactionSuccessAsync({ + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value: DeploymentManager.protocolFee, + }); return expect(tx).to.revertWith(expectedError); }); @@ -382,23 +372,25 @@ blockchainTests.resets('Exchange wrappers', env => { const signedOrder = await maker.signOrderAsync(); const takerAssetFillAmount = signedOrder.takerAssetAmount; - await deployment.exchange.fillOrder.awaitTransactionSuccessAsync( - signedOrder, - signedOrder.takerAssetAmount.dividedToIntegerBy(2), - signedOrder.signature, - { from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee }, - ); + await deployment.exchange + .fillOrder(signedOrder, signedOrder.takerAssetAmount.dividedToIntegerBy(2), signedOrder.signature) + .awaitTransactionSuccessAsync({ + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value: DeploymentManager.protocolFee, + }); const expectedError = new ExchangeRevertErrors.IncompleteFillError( ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, takerAssetFillAmount, takerAssetFillAmount.dividedToIntegerBy(2), ); - const tx = deployment.exchange.fillOrKillOrder.awaitTransactionSuccessAsync( - signedOrder, - signedOrder.takerAssetAmount, - signedOrder.signature, - { from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee }, - ); + const tx = deployment.exchange + .fillOrKillOrder(signedOrder, signedOrder.takerAssetAmount, signedOrder.signature) + .awaitTransactionSuccessAsync({ + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value: DeploymentManager.protocolFee, + }); return expect(tx).to.revertWith(expectedError); }); }); @@ -441,20 +433,20 @@ blockchainTests.resets('Exchange wrappers', env => { await simulateFillAsync(signedOrder, expectedFillResults, shouldPayWethFees); } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( - deployment.exchange.batchFillOrders, + const contractFn = deployment.exchange.batchFillOrders( signedOrders, takerAssetFillAmounts, signedOrders.map(signedOrder => signedOrder.signature), - { - from: taker.address, - gasPrice: DeploymentManager.gasPrice, - value, - }, ); + const callData = { + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value, + }; + const fillResults = await contractFn.callAsync(callData); + const receipt = await contractFn.awaitTransactionSuccessAsync(callData); expect(totalFillResults).to.be.deep.eq(fillResults); - await assertResultsAsync(receipt, fillTestInfo); } @@ -503,17 +495,18 @@ blockchainTests.resets('Exchange wrappers', env => { await simulateFillAsync(signedOrder, expectedFillResults, shouldPayWethFees); } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( - deployment.exchange.batchFillOrKillOrders, + const contractFn = deployment.exchange.batchFillOrKillOrders( signedOrders, takerAssetFillAmounts, signedOrders.map(order => order.signature), - { - from: taker.address, - gasPrice: DeploymentManager.gasPrice, - value, - }, ); + const callData = { + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value, + }; + const fillResults = await contractFn.callAsync(callData); + const receipt = await contractFn.awaitTransactionSuccessAsync(callData); expect(totalFillResults).to.be.deep.eq(fillResults); @@ -535,25 +528,27 @@ blockchainTests.resets('Exchange wrappers', env => { it('should revert if a single signedOrder does not fill the expected amount', async () => { const takerAssetFillAmounts = signedOrders.map(signedOrder => signedOrder.takerAssetAmount.div(2)); - await deployment.exchange.fillOrKillOrder.awaitTransactionSuccessAsync( - signedOrders[0], - signedOrders[0].takerAssetAmount, - signedOrders[0].signature, - { from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee }, - ); + await deployment.exchange + .fillOrKillOrder(signedOrders[0], signedOrders[0].takerAssetAmount, signedOrders[0].signature) + .awaitTransactionSuccessAsync({ + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value: DeploymentManager.protocolFee, + }); const orderHashHex = orderHashUtils.getOrderHashHex(signedOrders[0]); const expectedError = new ExchangeRevertErrors.OrderStatusError(orderHashHex, OrderStatus.FullyFilled); - const tx = deployment.exchange.batchFillOrKillOrders.awaitTransactionSuccessAsync( - signedOrders, - takerAssetFillAmounts, - signedOrders.map(order => order.signature), - { + const tx = deployment.exchange + .batchFillOrKillOrders( + signedOrders, + takerAssetFillAmounts, + signedOrders.map(order => order.signature), + ) + .awaitTransactionSuccessAsync({ from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee.times(signedOrders.length), - }, - ); + }); return expect(tx).to.revertWith(expectedError); }); }); @@ -597,19 +592,20 @@ blockchainTests.resets('Exchange wrappers', env => { } } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( - deployment.exchange.batchFillOrdersNoThrow, + const contractFn = deployment.exchange.batchFillOrdersNoThrow( signedOrdersWithValidity.map(signedOrderWithValidity => signedOrderWithValidity.signedOrder), takerAssetFillAmounts, signedOrdersWithValidity.map( signedOrderWithValidity => signedOrderWithValidity.signedOrder.signature, ), - { - from: taker.address, - gasPrice: DeploymentManager.gasPrice, - value, - }, ); + const callData = { + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value, + }; + const fillResults = await contractFn.callAsync(callData); + const receipt = await contractFn.awaitTransactionSuccessAsync(callData); expect(totalFillResults).to.be.deep.eq(fillResults); @@ -712,18 +708,18 @@ blockchainTests.resets('Exchange wrappers', env => { } } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( - deployment.exchange.marketSellOrdersNoThrow, + const contractFn = deployment.exchange.marketSellOrdersNoThrow( signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder), takerAssetFillAmount, signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder.signature), - { - from: taker.address, - gasPrice: DeploymentManager.gasPrice, - value, - }, ); - + const callData = { + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value, + }; + const fillResults = await contractFn.callAsync(callData); + const receipt = await contractFn.awaitTransactionSuccessAsync(callData); expect(fillResults).to.deep.equal(totalFillResults); await assertResultsAsync(receipt, fillTestInfo); @@ -782,9 +778,9 @@ blockchainTests.resets('Exchange wrappers', env => { }); it('should fill a signedOrder that does not use the same takerAssetAddress (eth protocol fee)', async () => { - const differentTakerAssetData = await devUtils.encodeERC20AssetData.callAsync( - deployment.tokens.erc20[2].address, - ); + const differentTakerAssetData = await devUtils + .encodeERC20AssetData(deployment.tokens.erc20[2].address) + .callAsync(); signedOrders = [ await maker.signOrderAsync(), @@ -805,9 +801,9 @@ blockchainTests.resets('Exchange wrappers', env => { }); it('should fill a signedOrder that does not use the same takerAssetAddress (weth protocol fee)', async () => { - const differentTakerAssetData = await devUtils.encodeERC20AssetData.callAsync( - deployment.tokens.erc20[2].address, - ); + const differentTakerAssetData = await devUtils + .encodeERC20AssetData(deployment.tokens.erc20[2].address) + .callAsync(); signedOrders = [ await maker.signOrderAsync(), @@ -910,18 +906,18 @@ blockchainTests.resets('Exchange wrappers', env => { } } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( - deployment.exchange.marketBuyOrdersNoThrow, + const contractFn = deployment.exchange.marketBuyOrdersNoThrow( signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder), makerAssetFillAmount, signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder.signature), - { - from: taker.address, - gasPrice: DeploymentManager.gasPrice, - value, - }, ); - + const callData = { + from: taker.address, + gasPrice: DeploymentManager.gasPrice, + value, + }; + const fillResults = await contractFn.callAsync(callData); + const receipt = await contractFn.awaitTransactionSuccessAsync(callData); expect(fillResults).to.deep.equal(totalFillResults); await assertResultsAsync(receipt, fillTestInfo); @@ -980,9 +976,9 @@ blockchainTests.resets('Exchange wrappers', env => { }); it('should fill a signedOrder that does not use the same makerAssetAddress (eth protocol fee)', async () => { - const differentMakerAssetData = await devUtils.encodeERC20AssetData.callAsync( - deployment.tokens.erc20[2].address, - ); + const differentMakerAssetData = await devUtils + .encodeERC20AssetData(deployment.tokens.erc20[2].address) + .callAsync(); signedOrders = [ await maker.signOrderAsync(), @@ -1004,9 +1000,9 @@ blockchainTests.resets('Exchange wrappers', env => { }); it('should fill a signedOrder that does not use the same makerAssetAddress (weth protocol fee)', async () => { - const differentMakerAssetData = await devUtils.encodeERC20AssetData.callAsync( - deployment.tokens.erc20[2].address, - ); + const differentMakerAssetData = await devUtils + .encodeERC20AssetData(deployment.tokens.erc20[2].address) + .callAsync(); signedOrders = [ await maker.signOrderAsync(), @@ -1070,7 +1066,7 @@ blockchainTests.resets('Exchange wrappers', env => { describe('batchCancelOrders', () => { it('should be able to cancel multiple signedOrders', async () => { - const receipt = await deployment.exchange.batchCancelOrders.awaitTransactionSuccessAsync(signedOrders, { + const receipt = await deployment.exchange.batchCancelOrders(signedOrders).awaitTransactionSuccessAsync({ from: maker.address, }); const expectedOrderHashes = signedOrders.map(order => orderHashUtils.getOrderHashHex(order)); @@ -1081,13 +1077,13 @@ blockchainTests.resets('Exchange wrappers', env => { }); it('should not revert if a single cancel noops', async () => { - await deployment.exchange.cancelOrder.awaitTransactionSuccessAsync(signedOrders[1], { + await deployment.exchange.cancelOrder(signedOrders[1]).awaitTransactionSuccessAsync({ from: maker.address, }); const expectedOrderHashes = [signedOrders[0], ...signedOrders.slice(2)].map(order => orderHashUtils.getOrderHashHex(order), ); - const receipt = await deployment.exchange.batchCancelOrders.awaitTransactionSuccessAsync(signedOrders, { + const receipt = await deployment.exchange.batchCancelOrders(signedOrders).awaitTransactionSuccessAsync({ from: maker.address, }); diff --git a/contracts/integrations/test/internal-integration-tests/fillorder_test.ts b/contracts/integrations/test/internal-integration-tests/fillorder_test.ts index d1abf141ea..0240c026b6 100644 --- a/contracts/integrations/test/internal-integration-tests/fillorder_test.ts +++ b/contracts/integrations/test/internal-integration-tests/fillorder_test.ts @@ -52,10 +52,10 @@ blockchainTests.resets('fillOrder integration tests', env => { }); const orderConfig = { feeRecipientAddress: feeRecipient.address, - makerAssetData: await devUtils.encodeERC20AssetData.callAsync(makerToken.address), - takerAssetData: await devUtils.encodeERC20AssetData.callAsync(takerToken.address), - makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(makerToken.address), - takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(takerToken.address), + makerAssetData: await devUtils.encodeERC20AssetData(makerToken.address).callAsync(), + takerAssetData: await devUtils.encodeERC20AssetData(takerToken.address).callAsync(), + makerFeeAssetData: await devUtils.encodeERC20AssetData(makerToken.address).callAsync(), + takerFeeAssetData: await devUtils.encodeERC20AssetData(takerToken.address).callAsync(), makerFee: constants.ZERO_AMOUNT, takerFee: constants.ZERO_AMOUNT, }; @@ -136,7 +136,7 @@ blockchainTests.resets('fillOrder integration tests', env => { taker.address, deployment.staking.stakingProxy.address, DeploymentManager.protocolFee, - await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address), + await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(), ); } @@ -227,7 +227,7 @@ blockchainTests.resets('fillOrder integration tests', env => { // now expect a `StakingPoolEarnedRewardsInEpoch` event to be emitted because the staking // pool now has enough stake in the current epoch to earn rewards. verifyFillEvents(order, receipt); - const currentEpoch = await deployment.staking.stakingWrapper.currentEpoch.callAsync(); + const currentEpoch = await deployment.staking.stakingWrapper.currentEpoch().callAsync(); verifyEvents( receipt, [ @@ -256,7 +256,7 @@ blockchainTests.resets('fillOrder integration tests', env => { // End the epoch. This should wrap the staking proxy's ETH balance. const endEpochReceipt = await delegator.endEpochAsync(); - const newEpoch = await deployment.staking.stakingWrapper.currentEpoch.callAsync(); + const newEpoch = await deployment.staking.stakingWrapper.currentEpoch().callAsync(); // Check balances expectedBalances.wrapEth( @@ -300,7 +300,7 @@ blockchainTests.resets('fillOrder integration tests', env => { deployment.staking.stakingProxy.address, operator.address, operatorReward, - await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address), + await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(), ); expectedBalances.burnGas(delegator.address, DeploymentManager.gasPrice.times(finalizePoolReceipt.gasUsed)); await balanceStore.updateBalancesAsync(); @@ -341,7 +341,7 @@ blockchainTests.resets('fillOrder integration tests', env => { await taker.fillOrderAsync(order, order.takerAssetAmount); // Check that the pool has collected fees from the above fill. - const poolStats = await deployment.staking.stakingWrapper.getStakingPoolStatsThisEpoch.callAsync(poolId); + const poolStats = await deployment.staking.stakingWrapper.getStakingPoolStatsThisEpoch(poolId).callAsync(); expect(poolStats.feesCollected).to.bignumber.equal(DeploymentManager.protocolFee); }); it('should collect WETH fees and pay out rewards', async () => { @@ -382,7 +382,7 @@ blockchainTests.resets('fillOrder integration tests', env => { deployment.staking.stakingProxy.address, operator.address, operatorReward, - await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address), + await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(), ); expectedBalances.burnGas(delegator.address, DeploymentManager.gasPrice.times(finalizePoolReceipt.gasUsed)); await balanceStore.updateBalancesAsync(); diff --git a/contracts/integrations/test/wrapper_interfaces.ts b/contracts/integrations/test/wrapper_interfaces.ts index 2c8fe219b1..983a1cbd3d 100644 --- a/contracts/integrations/test/wrapper_interfaces.ts +++ b/contracts/integrations/test/wrapper_interfaces.ts @@ -1,53 +1,21 @@ -import { PromiseWithTransactionHash } from '@0x/base-contract'; -import { AwaitTransactionSuccessOpts } from '@0x/types'; -import { BlockParam, CallData, TransactionReceiptWithDecodedLogs, TxData } from 'ethereum-types'; +import { ContractFunctionObj, ContractTxFunctionObj } from '@0x/base-contract'; +import { BlockParam, CallData } from 'ethereum-types'; +// tslint:disable:max-classes-per-file // Generated Wrapper Interfaces -export interface AssetProxyDispatcher { - registerAssetProxy: { - awaitTransactionSuccessAsync: ( - assetProxy: string, - txData?: Partial, - txOpts?: AwaitTransactionSuccessOpts, - ) => PromiseWithTransactionHash; - }; - getAssetProxy: { - callAsync(assetProxyId: string, callData?: Partial, defaultBlock?: BlockParam): Promise; - }; +export abstract class AssetProxyDispatcher { + public abstract registerAssetProxy(assetProxy: string): ContractTxFunctionObj; + public abstract getAssetProxy(assetProxyId: string): ContractFunctionObj; } -export interface Authorizable extends Ownable { - addAuthorizedAddress: { - awaitTransactionSuccessAsync: ( - target: string, - txData?: Partial, - txOpts?: AwaitTransactionSuccessOpts, - ) => PromiseWithTransactionHash; - }; - removeAuthorizedAddress: { - awaitTransactionSuccessAsync: ( - target: string, - txData?: Partial, - txOpts?: AwaitTransactionSuccessOpts, - ) => PromiseWithTransactionHash; - }; - authorized: { - callAsync(authority: string, callData?: Partial, defaultBlock?: BlockParam): Promise; - }; - getAuthorizedAddresses: { - callAsync(callData?: Partial, defaultBlock?: BlockParam): Promise; - }; -} +export abstract class Ownable { + public abstract transferOwnership(newOwner: string): ContractTxFunctionObj; -export interface Ownable { - transferOwnership: { - awaitTransactionSuccessAsync: ( - newOwner: string, - txData?: Partial, - txOpts?: AwaitTransactionSuccessOpts, - ) => PromiseWithTransactionHash; - }; - owner: { - callAsync(callData?: Partial, defaultBlock?: BlockParam): Promise; - }; + public abstract owner(callData?: Partial, defaultBlock?: BlockParam): ContractFunctionObj; +} +export abstract class Authorizable extends Ownable { + public abstract addAuthorizedAddress(target: string): ContractTxFunctionObj; + public abstract removeAuthorizedAddress(target: string): ContractTxFunctionObj; + public abstract authorized(authority: string): ContractFunctionObj; + public abstract getAuthorizedAddresses(): ContractFunctionObj; } diff --git a/contracts/multisig/test/multi_sig_with_time_lock.ts b/contracts/multisig/test/multi_sig_with_time_lock.ts index b0d0378b0b..26be78e5e3 100644 --- a/contracts/multisig/test/multi_sig_with_time_lock.ts +++ b/contracts/multisig/test/multi_sig_with_time_lock.ts @@ -126,9 +126,9 @@ describe('MultiSigWalletWithTimeLock', () => { }); it('should confirm transaction for caller but not reset the confirmation time if tx is already fully confirmed', async () => { await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); - const confirmationTimeBefore = await multiSig.confirmationTimes.callAsync(txId); + const confirmationTimeBefore = await multiSig.confirmationTimes(txId).callAsync(); const txReceipt = await multiSigWrapper.confirmTransactionAsync(txId, owners[2]); - const confirmationTimeAfter = await multiSig.confirmationTimes.callAsync(txId); + const confirmationTimeAfter = await multiSig.confirmationTimes(txId).callAsync(); expect(confirmationTimeBefore).to.bignumber.equal(confirmationTimeAfter); expect(txReceipt.logs.length).to.equal(1); const log = txReceipt.logs[0] as LogWithDecodedArgs; @@ -256,25 +256,25 @@ describe('MultiSigWalletWithTimeLock', () => { it('should revert when not called by wallet', async () => { return expectTransactionFailedWithoutReasonAsync( - multiSig.changeTimeLock.sendTransactionAsync(SECONDS_TIME_LOCKED, { from: owners[0] }), + multiSig.changeTimeLock(SECONDS_TIME_LOCKED).sendTransactionAsync({ from: owners[0] }), ); }); it('should revert without enough confirmations', async () => { const destination = multiSig.address; - const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED); + const changeTimeLockData = multiSig.changeTimeLock(SECONDS_TIME_LOCKED).getABIEncodedTransactionData(); const res = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]); const log = res.logs[0] as LogWithDecodedArgs; const txId = log.args.transactionId; return expectTransactionFailedAsync( - multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }), + multiSig.executeTransaction(txId).sendTransactionAsync({ from: owners[0] }), RevertReason.TxNotFullyConfirmed, ); }); it('should set confirmation time with enough confirmations', async () => { const destination = multiSig.address; - const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED); + const changeTimeLockData = multiSig.changeTimeLock(SECONDS_TIME_LOCKED).getABIEncodedTransactionData(); const subRes = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]); const subLog = subRes.logs[0] as LogWithDecodedArgs; const txId = subLog.args.transactionId; @@ -288,14 +288,14 @@ describe('MultiSigWalletWithTimeLock', () => { throw new Error(`Unexpectedly failed to fetch block at #${blockNum}`); } const timestamp = new BigNumber(blockInfo.timestamp); - const confirmationTimeBigNum = new BigNumber(await multiSig.confirmationTimes.callAsync(txId)); + const confirmationTimeBigNum = new BigNumber(await multiSig.confirmationTimes(txId).callAsync()); expect(timestamp).to.be.bignumber.equal(confirmationTimeBigNum); }); it('should be executable with enough confirmations and secondsTimeLocked of 0', async () => { const destination = multiSig.address; - const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED); + const changeTimeLockData = multiSig.changeTimeLock(SECONDS_TIME_LOCKED).getABIEncodedTransactionData(); const subRes = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]); const subLog = subRes.logs[0] as LogWithDecodedArgs; const txId = subLog.args.transactionId; @@ -303,7 +303,7 @@ describe('MultiSigWalletWithTimeLock', () => { await multiSigWrapper.confirmTransactionAsync(txId, owners[1]); await multiSigWrapper.executeTransactionAsync(txId, owners[1]); - const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked.callAsync()); + const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked().callAsync()); expect(secondsTimeLocked).to.be.bignumber.equal(SECONDS_TIME_LOCKED); }); }); @@ -328,7 +328,7 @@ describe('MultiSigWalletWithTimeLock', () => { ); multiSigWrapper = new MultiSigWrapper(multiSig, provider); - const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(newSecondsTimeLocked); + const changeTimeLockData = multiSig.changeTimeLock(newSecondsTimeLocked).getABIEncodedTransactionData(); const res = await multiSigWrapper.submitTransactionAsync( multiSig.address, changeTimeLockData, @@ -341,19 +341,21 @@ describe('MultiSigWalletWithTimeLock', () => { it('should revert if it has enough confirmations but is not past the time lock', async () => { return expectTransactionFailedAsync( - multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }), + multiSig.executeTransaction(txId).sendTransactionAsync({ from: owners[0] }), RevertReason.TimeLockIncomplete, ); }); it('should execute if it has enough confirmations and is past the time lock', async () => { await increaseTimeAndMineBlockAsync(SECONDS_TIME_LOCKED.toNumber()); - await web3Wrapper.awaitTransactionSuccessAsync( - await multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }), - constants.AWAIT_TRANSACTION_MINED_MS, - ); + await multiSig + .executeTransaction(txId) + .awaitTransactionSuccessAsync( + { from: owners[0] }, + { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS }, + ); - const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked.callAsync()); + const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked().callAsync()); expect(secondsTimeLocked).to.be.bignumber.equal(newSecondsTimeLocked); }); }); diff --git a/contracts/multisig/test/utils/multi_sig_wrapper.ts b/contracts/multisig/test/utils/multi_sig_wrapper.ts index bc74782000..2912b09b98 100644 --- a/contracts/multisig/test/utils/multi_sig_wrapper.ts +++ b/contracts/multisig/test/utils/multi_sig_wrapper.ts @@ -25,19 +25,19 @@ export class MultiSigWrapper { opts: { value?: BigNumber } = {}, ): Promise { const value = opts.value === undefined ? new BigNumber(0) : opts.value; - const txHash = await this._multiSig.submitTransaction.sendTransactionAsync(destination, value, data, { + const txHash = await this._multiSig.submitTransaction(destination, value, data).sendTransactionAsync({ from, }); const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return tx; } public async confirmTransactionAsync(txId: BigNumber, from: string): Promise { - const txHash = await this._multiSig.confirmTransaction.sendTransactionAsync(txId, { from }); + const txHash = await this._multiSig.confirmTransaction(txId).sendTransactionAsync({ from }); const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return tx; } public async revokeConfirmationAsync(txId: BigNumber, from: string): Promise { - const txHash = await this._multiSig.revokeConfirmation.sendTransactionAsync(txId, { from }); + const txHash = await this._multiSig.revokeConfirmation(txId).sendTransactionAsync({ from }); const tx = await this._logDecoder.getTxWithDecodedLogsAsync(txHash); return tx; } @@ -46,7 +46,7 @@ export class MultiSigWrapper { from: string, opts: { gas?: number } = {}, ): Promise { - const txHash = await this._multiSig.executeTransaction.sendTransactionAsync(txId, { + const txHash = await this._multiSig.executeTransaction(txId).sendTransactionAsync({ from, gas: opts.gas, }); diff --git a/contracts/multisig/test/utils/zero_ex_governor_wrapper.ts b/contracts/multisig/test/utils/zero_ex_governor_wrapper.ts index a7c20dd07c..04d3246b1c 100644 --- a/contracts/multisig/test/utils/zero_ex_governor_wrapper.ts +++ b/contracts/multisig/test/utils/zero_ex_governor_wrapper.ts @@ -20,12 +20,13 @@ export class ZeroExGovernorWrapper { const values = opts.values === undefined ? data.map(() => constants.ZERO_AMOUNT) : opts.values; const batchTransactionEncoder = AbiEncoder.create('(bytes[],address[],uint256[])'); const batchTransactionData = batchTransactionEncoder.encode([data, destinations, values]); - const txReceipt = await this._governor.submitTransaction.awaitTransactionSuccessAsync( - hexRandom(20), // submitTransaction will fail if this is a null address - constants.ZERO_AMOUNT, - batchTransactionData, - { from }, - ); + const txReceipt = await this._governor + .submitTransaction( + hexRandom(20), // submitTransaction will fail if this is a null address + constants.ZERO_AMOUNT, + batchTransactionData, + ) + .awaitTransactionSuccessAsync({ from }); const txId = (txReceipt.logs[0] as LogWithDecodedArgs).args.transactionId; return { txReceipt, txId }; } @@ -39,15 +40,16 @@ export class ZeroExGovernorWrapper { const submitResults = await this.submitTransactionAsync(data, destinations, signerAddresses[0], opts); const requiredSignatures = opts.requiredSignatures === undefined ? 2 : opts.requiredSignatures; for (const index of _.range(1, requiredSignatures)) { - await this._governor.confirmTransaction.awaitTransactionSuccessAsync(submitResults.txId, { + await this._governor.confirmTransaction(submitResults.txId).awaitTransactionSuccessAsync({ from: signerAddresses[index], }); } await increaseTimeAndMineBlockAsync(increaseTimeSeconds); - const executionTxReceipt = await this._governor.executeTransaction.awaitTransactionSuccessAsync( - submitResults.txId, - { from: opts.executeFromAddress === undefined ? signerAddresses[0] : opts.executeFromAddress }, - ); + const executionTxReceipt = await this._governor + .executeTransaction(submitResults.txId) + .awaitTransactionSuccessAsync({ + from: opts.executeFromAddress === undefined ? signerAddresses[0] : opts.executeFromAddress, + }); return { executionTxReceipt, txId: submitResults.txId }; } } diff --git a/contracts/multisig/test/zero_ex_governor.ts b/contracts/multisig/test/zero_ex_governor.ts index 77b5359031..e963e8a8a5 100644 --- a/contracts/multisig/test/zero_ex_governor.ts +++ b/contracts/multisig/test/zero_ex_governor.ts @@ -158,10 +158,9 @@ blockchainTests.resets('ZeroExGovernor', env => { new BigNumber(REQUIRED_SIGNERS), new BigNumber(DEFAULT_TIME_LOCK), ); - const timelock = await governorContract.functionCallTimeLocks.callAsync( - reg.functionSelectors[0], - reg.destinations[0], - ); + const timelock = await governorContract + .functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(timelock[0]).to.equal(true); expect(timelock[1]).to.bignumber.equal(reg.functionCallTimeLockSeconds[0]); }); @@ -180,10 +179,9 @@ blockchainTests.resets('ZeroExGovernor', env => { new BigNumber(DEFAULT_TIME_LOCK), ); for (const [index, selector] of reg.functionSelectors.entries()) { - const timelock = await governorContract.functionCallTimeLocks.callAsync( - selector, - reg.destinations[index], - ); + const timelock = await governorContract + .functionCallTimeLocks(selector, reg.destinations[index]) + .callAsync(); expect(timelock[0]).to.equal(true); expect(timelock[1]).to.bignumber.equal(reg.functionCallTimeLockSeconds[index]); } @@ -193,23 +191,26 @@ blockchainTests.resets('ZeroExGovernor', env => { blockchainTests.resets('registerFunctionCall', () => { it('should revert if not called by wallet', async () => { const reg = createFunctionRegistration(1, 1, 1); - const tx = governor.registerFunctionCall.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - { from: signerAddresses[0] }, - ); + const tx = governor + .registerFunctionCall( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync({ from: signerAddresses[0] }); expect(tx).to.revertWith(RevertReason.OnlyCallableByWallet); }); it('should register a function call', async () => { const reg = createFunctionRegistration(1, 1, 1); - const txReceipt = await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ); + const txReceipt = await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.eq(1); const logArgs = (txReceipt.logs[0] as LogWithDecodedArgs< ZeroExGovernorFunctionCallTimeLockRegistrationEventArgs @@ -218,53 +219,53 @@ blockchainTests.resets('ZeroExGovernor', env => { expect(logArgs.destination).to.eq(reg.destinations[0]); expect(logArgs.hasCustomTimeLock).to.eq(true); expect(logArgs.newSecondsTimeLocked).to.bignumber.eq(reg.functionCallTimeLockSeconds[0]); - const timelock = await governor.functionCallTimeLocks.callAsync( - reg.functionSelectors[0], - reg.destinations[0], - ); + const timelock = await governor + .functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(timelock[0]).to.equal(true); expect(timelock[1]).to.bignumber.equal(reg.functionCallTimeLockSeconds[0]); }); it('should be able to overwrite existing function calls', async () => { const reg = createFunctionRegistration(1, 1, 1); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ); + await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync(); const newTimeLock = reg.functionCallTimeLockSeconds[0].plus(1000); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - newTimeLock, - ); - const timelock = await governor.functionCallTimeLocks.callAsync( - reg.functionSelectors[0], - reg.destinations[0], - ); + await governor + .registerFunctionCallBypassWallet(true, reg.functionSelectors[0], reg.destinations[0], newTimeLock) + .awaitTransactionSuccessAsync(); + const timelock = await governor + .functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(timelock[0]).to.equal(true); expect(timelock[1]).to.bignumber.equal(newTimeLock); }); it('should clear the function timelock if hasCustomTimeLock is set to false', async () => { const reg = createFunctionRegistration(1, 1, 1); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - false, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ); - const timelock = await governor.functionCallTimeLocks.callAsync( - reg.functionSelectors[0], - reg.destinations[0], - ); + await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync(); + await governor + .registerFunctionCallBypassWallet( + false, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync(); + const timelock = await governor + .functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(timelock[0]).to.equal(false); expect(timelock[1]).to.bignumber.equal(constants.ZERO_AMOUNT); }); @@ -272,11 +273,9 @@ blockchainTests.resets('ZeroExGovernor', env => { describe('assertValidFunctionCall', () => { it('should revert if the data is less than 4 bytes long', async () => { - const result = governor.assertValidFunctionCall.callAsync( - constants.ZERO_AMOUNT, - constants.NULL_BYTES, - constants.NULL_ADDRESS, - ); + const result = governor + .assertValidFunctionCall(constants.ZERO_AMOUNT, constants.NULL_BYTES, constants.NULL_ADDRESS) + .callAsync(); const expectedError = new LibBytesRevertErrors.InvalidByteOperationError( LibBytesRevertErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired, constants.ZERO_AMOUNT, @@ -288,91 +287,87 @@ blockchainTests.resets('ZeroExGovernor', env => { const latestTimestamp = await getLatestBlockTimestampAsync(); const transactionConfirmationTime = new BigNumber(latestTimestamp); const reg = createFunctionRegistration(1, 1, 1); - const result = governor.assertValidFunctionCall.callAsync( - transactionConfirmationTime, - reg.functionSelectors[0], - reg.destinations[0], - ); + const result = governor + .assertValidFunctionCall(transactionConfirmationTime, reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(result).to.revertWith(RevertReason.DefaultTimeLockIncomplete); }); it('should revert if a registered function is called before the custom timelock', async () => { const reg = createFunctionRegistration(1, 1, 1); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ); + await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync(); const latestTimestamp = await getLatestBlockTimestampAsync(); const transactionConfirmationTime = new BigNumber(latestTimestamp); - const result = governor.assertValidFunctionCall.callAsync( - transactionConfirmationTime, - reg.functionSelectors[0], - reg.destinations[0], - ); + const result = governor + .assertValidFunctionCall(transactionConfirmationTime, reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(result).to.revertWith(RevertReason.CustomTimeLockIncomplete); }); it('should revert if a registered function is called before the custom timelock and after the default timelock', async () => { const reg = createFunctionRegistration(1, 1, 1); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - new BigNumber(DEFAULT_TIME_LOCK).times(2), - ); + await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + new BigNumber(DEFAULT_TIME_LOCK).times(2), + ) + .awaitTransactionSuccessAsync(); const latestTimestamp = await getLatestBlockTimestampAsync(); const transactionConfirmationTime = new BigNumber(latestTimestamp).minus(DEFAULT_TIME_LOCK); - const result = governor.assertValidFunctionCall.callAsync( - transactionConfirmationTime, - reg.functionSelectors[0], - reg.destinations[0], - ); + const result = governor + .assertValidFunctionCall(transactionConfirmationTime, reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(result).to.revertWith(RevertReason.CustomTimeLockIncomplete); }); it('should be successful if an unregistered function is called after the default timelock', async () => { const latestTimestamp = await getLatestBlockTimestampAsync(); const transactionConfirmationTime = new BigNumber(latestTimestamp).minus(DEFAULT_TIME_LOCK); const reg = createFunctionRegistration(1, 1, 1); - const result = governor.assertValidFunctionCall.callAsync( - transactionConfirmationTime, - reg.functionSelectors[0], - reg.destinations[0], - ); + const result = governor + .assertValidFunctionCall(transactionConfirmationTime, reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(result).to.be.fulfilled(''); }); it('should be successful if a registered function is called after the custom timelock', async () => { const reg = createFunctionRegistration(1, 1, 1); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ); + await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .awaitTransactionSuccessAsync(); const latestTimestamp = await getLatestBlockTimestampAsync(); const transactionConfirmationTime = new BigNumber(latestTimestamp).minus( reg.functionCallTimeLockSeconds[0], ); - const result = governor.assertValidFunctionCall.callAsync( - transactionConfirmationTime, - reg.functionSelectors[0], - reg.destinations[0], - ); + const result = governor + .assertValidFunctionCall(transactionConfirmationTime, reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(result).to.be.fulfilled(''); }); it('should allow a custom timelock to be set to 0', async () => { const reg = createFunctionRegistration(1, 1, 1); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - reg.functionSelectors[0], - reg.destinations[0], - constants.ZERO_AMOUNT, - ); + await governor + .registerFunctionCallBypassWallet( + true, + reg.functionSelectors[0], + reg.destinations[0], + constants.ZERO_AMOUNT, + ) + .awaitTransactionSuccessAsync(); const latestTimestamp = await getLatestBlockTimestampAsync(); - const result = governor.assertValidFunctionCall.callAsync( - new BigNumber(latestTimestamp), - reg.functionSelectors[0], - reg.destinations[0], - ); + const result = governor + .assertValidFunctionCall(new BigNumber(latestTimestamp), reg.functionSelectors[0], reg.destinations[0]) + .callAsync(); expect(result).to.be.fulfilled(''); }); }); @@ -402,7 +397,7 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom()]; const destinations = [receiver.address]; const results = await governorWrapper.submitTransactionAsync(data, destinations, signerAddresses[0]); - const tx = governor.executeTransaction.awaitTransactionSuccessAsync(results.txId, { + const tx = governor.executeTransaction(results.txId).awaitTransactionSuccessAsync({ from: signerAddresses[1], }); expect(tx).to.revertWith(RevertReason.TxNotFullyConfirmed); @@ -411,7 +406,7 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom()]; const destinations = [receiver.address]; const results = await governorWrapper.submitTransactionAsync(data, destinations, signerAddresses[0]); - const tx = governor.executeTransaction.awaitTransactionSuccessAsync(results.txId, { + const tx = governor.executeTransaction(results.txId).awaitTransactionSuccessAsync({ from: signerAddresses[0], }); expect(tx).to.revertWith(RevertReason.TxNotFullyConfirmed); @@ -444,12 +439,9 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom()]; const destinations = [receiver.address]; const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - data[0].slice(0, 10), - receiver.address, - newTimeLock, - ); + await governor + .registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock) + .awaitTransactionSuccessAsync(); const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync( data, destinations, @@ -462,12 +454,9 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom()]; const destinations = [receiver.address]; const newTimeLock = constants.ZERO_AMOUNT; - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - data[0].slice(0, 10), - receiver.address, - newTimeLock, - ); + await governor + .registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock) + .awaitTransactionSuccessAsync(); const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync( data, destinations, @@ -480,12 +469,9 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom()]; const destinations = [receiver.address]; const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - data[0].slice(0, 10), - receiver.address, - newTimeLock, - ); + await governor + .registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock) + .awaitTransactionSuccessAsync(); const values = [INITIAL_BALANCE]; const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync( data, @@ -530,12 +516,9 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom(), hexRandom()]; const destinations = [receiver.address, receiver.address]; const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - data[0].slice(0, 10), - receiver.address, - newTimeLock, - ); + await governor + .registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock) + .awaitTransactionSuccessAsync(); const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync( data, destinations, @@ -548,12 +531,9 @@ blockchainTests.resets('ZeroExGovernor', env => { const data = [hexRandom(), hexRandom()]; const destinations = [receiver.address, receiver.address]; const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2); - await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync( - true, - data[0].slice(0, 10), - receiver.address, - newTimeLock, - ); + await governor + .registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock) + .awaitTransactionSuccessAsync(); const tx = governorWrapper.submitConfirmAndExecuteTransactionAsync( data, destinations, @@ -630,7 +610,7 @@ blockchainTests.resets('ZeroExGovernor', env => { signerAddresses, DEFAULT_TIME_LOCK, ); - const tx = governor.executeTransaction.awaitTransactionSuccessAsync(results.txId); + const tx = governor.executeTransaction(results.txId).awaitTransactionSuccessAsync(); expect(tx).to.revertWith(RevertReason.TxAlreadyExecuted); }); it('should revert if the only call is unsuccessful', async () => { @@ -660,12 +640,14 @@ blockchainTests.resets('ZeroExGovernor', env => { it('should be able to call registerFunctionCall after the default timelock', async () => { const reg = createFunctionRegistration(1, 1, 1); const data = [ - governor.registerFunctionCall.getABIEncodedTransactionData( - true, - reg.functionSelectors[0], - reg.destinations[0], - reg.functionCallTimeLockSeconds[0], - ), + governor + .registerFunctionCall( + true, + reg.functionSelectors[0], + reg.destinations[0], + reg.functionCallTimeLockSeconds[0], + ) + .getABIEncodedTransactionData(), ]; const destinations = [governor.address]; const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync( diff --git a/contracts/staking/test/actors/finalizer_actor.ts b/contracts/staking/test/actors/finalizer_actor.ts index e5b6c52754..44d20ccf10 100644 --- a/contracts/staking/test/actors/finalizer_actor.ts +++ b/contracts/staking/test/actors/finalizer_actor.ts @@ -131,9 +131,17 @@ export class FinalizerActor extends BaseActor { for (const delegator of delegators) { let balance = new BigNumber(delegatorBalancesByPoolId[poolId][delegator] || 0); if (delegator === operator) { - balance = balance.plus(await computeRewardBalanceOfOperator.callAsync(poolId)); + balance = balance.plus( + await computeRewardBalanceOfOperator + .bind(this._stakingApiWrapper.stakingContract)(poolId) + .callAsync(), + ); } else { - balance = balance.plus(await computeRewardBalanceOfDelegator.callAsync(poolId, delegator)); + balance = balance.plus( + await computeRewardBalanceOfDelegator + .bind(this._stakingApiWrapper.stakingContract)(poolId, delegator) + .callAsync(), + ); } delegatorBalancesByPoolId[poolId][delegator] = balance; } @@ -144,16 +152,16 @@ export class FinalizerActor extends BaseActor { private async _getDelegatorStakesByPoolIdAsync( delegatorsByPoolId: DelegatorsByPoolId, ): Promise { - const { getStakeDelegatedToPoolByOwner } = this._stakingApiWrapper.stakingContract; const delegatorBalancesByPoolId: DelegatorBalancesByPoolId = {}; for (const poolId of Object.keys(delegatorsByPoolId)) { const delegators = delegatorsByPoolId[poolId]; delegatorBalancesByPoolId[poolId] = {}; for (const delegator of delegators) { - delegatorBalancesByPoolId[poolId][delegator] = (await getStakeDelegatedToPoolByOwner.callAsync( - delegator, - poolId, - )).currentEpochBalance; + delegatorBalancesByPoolId[poolId][ + delegator + ] = (await this._stakingApiWrapper.stakingContract + .getStakeDelegatedToPoolByOwner(delegator, poolId) + .callAsync()).currentEpochBalance; } } return delegatorBalancesByPoolId; @@ -208,9 +216,9 @@ export class FinalizerActor extends BaseActor { ): Promise { const operatorBalanceByPoolId: OperatorBalanceByPoolId = {}; for (const poolId of Object.keys(operatorByPoolId)) { - operatorBalanceByPoolId[poolId] = await this._stakingApiWrapper.wethContract.balanceOf.callAsync( - operatorByPoolId[poolId], - ); + operatorBalanceByPoolId[poolId] = await this._stakingApiWrapper.wethContract + .balanceOf(operatorByPoolId[poolId]) + .callAsync(); } return operatorBalanceByPoolId; } @@ -219,7 +227,7 @@ export class FinalizerActor extends BaseActor { const operatorShareByPoolId: OperatorShareByPoolId = {}; for (const poolId of poolIds) { operatorShareByPoolId[poolId] = new BigNumber( - (await this._stakingApiWrapper.stakingContract.getStakingPool.callAsync(poolId)).operatorShare, + (await this._stakingApiWrapper.stakingContract.getStakingPool(poolId).callAsync()).operatorShare, ); } return operatorShareByPoolId; @@ -228,9 +236,9 @@ export class FinalizerActor extends BaseActor { private async _getRewardBalanceByPoolIdAsync(poolIds: string[]): Promise { const rewardBalanceByPoolId: RewardBalanceByPoolId = {}; for (const poolId of poolIds) { - rewardBalanceByPoolId[poolId] = await this._stakingApiWrapper.stakingContract.rewardsByPoolId.callAsync( - poolId, - ); + rewardBalanceByPoolId[poolId] = await this._stakingApiWrapper.stakingContract + .rewardsByPoolId(poolId) + .callAsync(); } return rewardBalanceByPoolId; } @@ -238,7 +246,7 @@ export class FinalizerActor extends BaseActor { private async _getRewardByPoolIdAsync(poolIds: string[]): Promise { const activePools = await Promise.all( poolIds.map(async poolId => - this._stakingApiWrapper.stakingContract.getStakingPoolStatsThisEpoch.callAsync(poolId), + this._stakingApiWrapper.stakingContract.getStakingPoolStatsThisEpoch(poolId).callAsync(), ), ); const totalRewards = await this._stakingApiWrapper.utils.getAvailableRewardsBalanceAsync(); diff --git a/contracts/staking/test/actors/maker_actor.ts b/contracts/staking/test/actors/maker_actor.ts index 144aeee11b..f5331ae473 100644 --- a/contracts/staking/test/actors/maker_actor.ts +++ b/contracts/staking/test/actors/maker_actor.ts @@ -7,17 +7,16 @@ import { PoolOperatorActor } from './pool_operator_actor'; export class MakerActor extends PoolOperatorActor { public async joinStakingPoolAsMakerAsync(poolId: string, revertError?: RevertError): Promise { // add maker - const txReceiptPromise = this._stakingApiWrapper.stakingContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync( - poolId, - { from: this.getOwner() }, - ); + const txReceiptPromise = this._stakingApiWrapper.stakingContract + .joinStakingPoolAsMaker(poolId) + .awaitTransactionSuccessAsync({ from: this.getOwner() }); if (revertError !== undefined) { await expect(txReceiptPromise).to.revertWith(revertError); return; } await txReceiptPromise; // check the pool id of the maker - const poolIdOfMaker = await this._stakingApiWrapper.stakingContract.poolIdByMaker.callAsync(this.getOwner()); + const poolIdOfMaker = await this._stakingApiWrapper.stakingContract.poolIdByMaker(this.getOwner()).callAsync(); expect(poolIdOfMaker, 'pool id of maker').to.be.equal(poolId); } } diff --git a/contracts/staking/test/actors/pool_operator_actor.ts b/contracts/staking/test/actors/pool_operator_actor.ts index e7fd5f7e78..2bc1e124bc 100644 --- a/contracts/staking/test/actors/pool_operator_actor.ts +++ b/contracts/staking/test/actors/pool_operator_actor.ts @@ -22,12 +22,12 @@ export class PoolOperatorActor extends BaseActor { } const poolId = await poolIdPromise; // validate pool id - const lastPoolId = await this._stakingApiWrapper.stakingContract.lastPoolId.callAsync(); + const lastPoolId = await this._stakingApiWrapper.stakingContract.lastPoolId().callAsync(); expect(poolId, 'pool id').to.be.bignumber.equal(lastPoolId); if (addOperatorAsMaker) { // check the pool id of the operator - const poolIdOfMaker = await this._stakingApiWrapper.stakingContract.poolIdByMaker.callAsync(this._owner); + const poolIdOfMaker = await this._stakingApiWrapper.stakingContract.poolIdByMaker(this._owner).callAsync(); expect(poolIdOfMaker, 'pool id of maker').to.be.equal(poolId); } return poolId; @@ -38,18 +38,16 @@ export class PoolOperatorActor extends BaseActor { revertError?: RevertError, ): Promise { // decrease operator share - const txReceiptPromise = this._stakingApiWrapper.stakingContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - newOperatorShare, - { from: this._owner }, - ); + const txReceiptPromise = this._stakingApiWrapper.stakingContract + .decreaseStakingPoolOperatorShare(poolId, newOperatorShare) + .awaitTransactionSuccessAsync({ from: this._owner }); if (revertError !== undefined) { await expect(txReceiptPromise).to.revertWith(revertError); return; } await txReceiptPromise; // Check operator share - const pool = await this._stakingApiWrapper.stakingContract.getStakingPool.callAsync(poolId); + const pool = await this._stakingApiWrapper.stakingContract.getStakingPool(poolId).callAsync(); expect(pool.operatorShare, 'updated operator share').to.be.bignumber.equal(newOperatorShare); } } diff --git a/contracts/staking/test/actors/staker_actor.ts b/contracts/staking/test/actors/staker_actor.ts index 39a6a2cf90..6603d85774 100644 --- a/contracts/staking/test/actors/staker_actor.ts +++ b/contracts/staking/test/actors/staker_actor.ts @@ -39,13 +39,12 @@ export class StakerActor extends BaseActor { const initZrxBalanceOfVault = await this._stakingApiWrapper.utils.getZrxTokenBalanceOfZrxVaultAsync(); const initBalances = await this._getBalancesAsync(); // move stake - const txReceiptPromise = this._stakingApiWrapper.stakingProxyContract.batchExecute.awaitTransactionSuccessAsync( - [ - this._stakingApiWrapper.stakingContract.stake.getABIEncodedTransactionData(amount), - this._stakingApiWrapper.stakingContract.moveStake.getABIEncodedTransactionData(from, to, amount), - ], - { from: this._owner }, - ); + const txReceiptPromise = this._stakingApiWrapper.stakingProxyContract + .batchExecute([ + this._stakingApiWrapper.stakingContract.stake(amount).getABIEncodedTransactionData(), + this._stakingApiWrapper.stakingContract.moveStake(from, to, amount).getABIEncodedTransactionData(), + ]) + .awaitTransactionSuccessAsync({ from: this._owner }); if (revertError !== undefined) { await expect(txReceiptPromise, 'expected revert error').to.revertWith(revertError); return; @@ -70,7 +69,7 @@ export class StakerActor extends BaseActor { const initZrxBalanceOfVault = await this._stakingApiWrapper.utils.getZrxTokenBalanceOfZrxVaultAsync(); const initBalances = await this._getBalancesAsync(); // deposit stake - const txReceiptPromise = this._stakingApiWrapper.stakingContract.stake.awaitTransactionSuccessAsync(amount, { + const txReceiptPromise = this._stakingApiWrapper.stakingContract.stake(amount).awaitTransactionSuccessAsync({ from: this._owner, }); if (revertError !== undefined) { @@ -93,7 +92,7 @@ export class StakerActor extends BaseActor { const initZrxBalanceOfVault = await this._stakingApiWrapper.utils.getZrxTokenBalanceOfZrxVaultAsync(); const initBalances = await this._getBalancesAsync(); // deposit stake - const txReceiptPromise = this._stakingApiWrapper.stakingContract.unstake.awaitTransactionSuccessAsync(amount, { + const txReceiptPromise = this._stakingApiWrapper.stakingContract.unstake(amount).awaitTransactionSuccessAsync({ from: this._owner, }); if (revertError !== undefined) { @@ -127,12 +126,9 @@ export class StakerActor extends BaseActor { // Calculate the expected outcome after the move. const expectedBalances = await this._calculateExpectedBalancesAfterMoveAsync(from, to, amount); // move stake - const txReceiptPromise = this._stakingApiWrapper.stakingContract.moveStake.awaitTransactionSuccessAsync( - from, - to, - amount, - { from: this._owner }, - ); + const txReceiptPromise = this._stakingApiWrapper.stakingContract + .moveStake(from, to, amount) + .awaitTransactionSuccessAsync({ from: this._owner }); if (revertError !== undefined) { await expect(txReceiptPromise).to.revertWith(revertError); return; @@ -155,10 +151,9 @@ export class StakerActor extends BaseActor { } public async withdrawDelegatorRewardsAsync(poolId: string, revertError?: RevertError): Promise { - const txReceiptPromise = this._stakingApiWrapper.stakingContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync( - poolId, - { from: this._owner }, - ); + const txReceiptPromise = this._stakingApiWrapper.stakingContract + .withdrawDelegatorRewards(poolId) + .awaitTransactionSuccessAsync({ from: this._owner }); if (revertError !== undefined) { await expect(txReceiptPromise, 'expected revert error').to.revertWith(revertError); return; @@ -196,36 +191,33 @@ export class StakerActor extends BaseActor { } private async _getBalancesAsync(): Promise { const balances: StakeBalances = { - currentEpoch: await this._stakingApiWrapper.stakingContract.currentEpoch.callAsync(), - zrxBalance: await this._stakingApiWrapper.zrxTokenContract.balanceOf.callAsync(this._owner), - stakeBalance: await this._stakingApiWrapper.stakingContract.getTotalStake.callAsync(this._owner), - stakeBalanceInVault: await this._stakingApiWrapper.zrxVaultContract.balanceOf.callAsync(this._owner), - undelegatedStakeBalance: await this._stakingApiWrapper.stakingContract.getOwnerStakeByStatus.callAsync( - this._owner, - StakeStatus.Undelegated, - ), - delegatedStakeBalance: await this._stakingApiWrapper.stakingContract.getOwnerStakeByStatus.callAsync( - this._owner, - StakeStatus.Delegated, - ), - globalUndelegatedStakeBalance: await this._stakingApiWrapper.stakingContract.getGlobalStakeByStatus.callAsync( - StakeStatus.Undelegated, - ), - globalDelegatedStakeBalance: await this._stakingApiWrapper.stakingContract.getGlobalStakeByStatus.callAsync( - StakeStatus.Delegated, - ), + currentEpoch: await this._stakingApiWrapper.stakingContract.currentEpoch().callAsync(), + zrxBalance: await this._stakingApiWrapper.zrxTokenContract.balanceOf(this._owner).callAsync(), + stakeBalance: await this._stakingApiWrapper.stakingContract.getTotalStake(this._owner).callAsync(), + stakeBalanceInVault: await this._stakingApiWrapper.zrxVaultContract.balanceOf(this._owner).callAsync(), + undelegatedStakeBalance: await this._stakingApiWrapper.stakingContract + .getOwnerStakeByStatus(this._owner, StakeStatus.Undelegated) + .callAsync(), + delegatedStakeBalance: await this._stakingApiWrapper.stakingContract + .getOwnerStakeByStatus(this._owner, StakeStatus.Delegated) + .callAsync(), + globalUndelegatedStakeBalance: await this._stakingApiWrapper.stakingContract + .getGlobalStakeByStatus(StakeStatus.Undelegated) + .callAsync(), + globalDelegatedStakeBalance: await this._stakingApiWrapper.stakingContract + .getGlobalStakeByStatus(StakeStatus.Delegated) + .callAsync(), delegatedStakeByPool: {}, totalDelegatedStakeByPool: {}, }; // lookup for each pool for (const poolId of this._poolIds) { - const delegatedStakeBalanceByPool = await this._stakingApiWrapper.stakingContract.getStakeDelegatedToPoolByOwner.callAsync( - this._owner, - poolId, - ); - const totalDelegatedStakeBalanceByPool = await this._stakingApiWrapper.stakingContract.getTotalStakeDelegatedToPool.callAsync( - poolId, - ); + const delegatedStakeBalanceByPool = await this._stakingApiWrapper.stakingContract + .getStakeDelegatedToPoolByOwner(this._owner, poolId) + .callAsync(); + const totalDelegatedStakeBalanceByPool = await this._stakingApiWrapper.stakingContract + .getTotalStakeDelegatedToPool(poolId) + .callAsync(); balances.delegatedStakeByPool[poolId] = delegatedStakeBalanceByPool; balances.totalDelegatedStakeByPool[poolId] = totalDelegatedStakeBalanceByPool; } diff --git a/contracts/staking/test/epoch_test.ts b/contracts/staking/test/epoch_test.ts index 352a4c6d6b..36515cb166 100644 --- a/contracts/staking/test/epoch_test.ts +++ b/contracts/staking/test/epoch_test.ts @@ -33,14 +33,14 @@ blockchainTests('Epochs', env => { ///// 2/3 Validate Initial Epoch & TimeLock Period ///// { // epoch - const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync(); + const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch().callAsync(); expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH); } ///// 3/3 Increment Epoch (TimeLock Should Not Increment) ///// await stakingApiWrapper.utils.skipToNextEpochAndFinalizeAsync(); { // epoch - const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync(); + const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch().callAsync(); expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH.plus(1)); } }); diff --git a/contracts/staking/test/migration_test.ts b/contracts/staking/test/migration_test.ts index f1400b6310..c6ddc00401 100644 --- a/contracts/staking/test/migration_test.ts +++ b/contracts/staking/test/migration_test.ts @@ -28,7 +28,7 @@ blockchainTests('Migration tests', env => { env.txDefaults, artifacts, ); - await stakingContract.addAuthorizedAddress.awaitTransactionSuccessAsync(authorizedAddress); + await stakingContract.addAuthorizedAddress(authorizedAddress).awaitTransactionSuccessAsync(); }); describe('StakingProxy', () => { @@ -45,7 +45,7 @@ blockchainTests('Migration tests', env => { artifacts, stakingContractAddress || constants.NULL_ADDRESS, ); - await proxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(authorizedAddress); + await proxyContract.addAuthorizedAddress(authorizedAddress).awaitTransactionSuccessAsync(); return proxyContract; } @@ -57,7 +57,7 @@ blockchainTests('Migration tests', env => { env.txDefaults, artifacts, ); - revertAddress = await initTargetContract.SHOULD_REVERT_ADDRESS.callAsync(); + revertAddress = await initTargetContract.SHOULD_REVERT_ADDRESS().callAsync(); }); async function enableInitRevertsAsync(): Promise { @@ -75,12 +75,12 @@ blockchainTests('Migration tests', env => { } async function assertInitStateAsync(proxyContract: TestStakingProxyContract): Promise { - const [senderAddress, thisAddress] = await initTargetContract.getInitState.callAsync({ + const [senderAddress, thisAddress] = await initTargetContract.getInitState().callAsync({ to: proxyContract.address, }); expect(senderAddress).to.eq(authorizedAddress); expect(thisAddress).to.eq(proxyContract.address); - const attachedAddress = await proxyContract.stakingContract.callAsync(); + const attachedAddress = await proxyContract.stakingContract().callAsync(); expect(attachedAddress).to.eq(initTargetContract.address); } @@ -115,7 +115,7 @@ blockchainTests('Migration tests', env => { env.provider, env.txDefaults, ); - const params = await stakingProxyContract.getParams.callAsync(); + const params = await stakingProxyContract.getParams().callAsync(); expect(params[0]).to.bignumber.eq(stakingConstants.DEFAULT_PARAMS.epochDurationInSeconds); expect(params[1]).to.bignumber.eq(stakingConstants.DEFAULT_PARAMS.rewardDelegatedStakeWeight); expect(params[2]).to.bignumber.eq(stakingConstants.DEFAULT_PARAMS.minimumPoolStake); @@ -132,25 +132,24 @@ blockchainTests('Migration tests', env => { }); it('throws if not called by an authorized address', async () => { - const tx = proxyContract.attachStakingContract.awaitTransactionSuccessAsync( - initTargetContract.address, - { + const tx = proxyContract + .attachStakingContract(initTargetContract.address) + .awaitTransactionSuccessAsync({ from: notAuthorizedAddress, - }, - ); + }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddress); return expect(tx).to.revertWith(expectedError); }); it('calls init() and attaches the contract', async () => { - await proxyContract.attachStakingContract.awaitTransactionSuccessAsync(initTargetContract.address); + await proxyContract.attachStakingContract(initTargetContract.address).awaitTransactionSuccessAsync(); await assertInitStateAsync(proxyContract); }); it('emits a `StakingContractAttachedToProxy` event', async () => { - const receipt = await proxyContract.attachStakingContract.awaitTransactionSuccessAsync( - initTargetContract.address, - ); + const receipt = await proxyContract + .attachStakingContract(initTargetContract.address) + .awaitTransactionSuccessAsync(); const logsArgs = filterLogsToArguments( receipt.logs, 'StakingContractAttachedToProxy', @@ -164,12 +163,14 @@ blockchainTests('Migration tests', env => { it('reverts if init() reverts', async () => { await enableInitRevertsAsync(); - const tx = proxyContract.attachStakingContract.awaitTransactionSuccessAsync(initTargetContract.address); + const tx = proxyContract + .attachStakingContract(initTargetContract.address) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(INIT_REVERT_ERROR); }); it('reverts if assertValidStorageParams() fails', async () => { - const tx = proxyContract.attachStakingContract.awaitTransactionSuccessAsync(revertAddress); + const tx = proxyContract.attachStakingContract(revertAddress).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(STORAGE_PARAMS_REVERT_ERROR); }); }); @@ -177,8 +178,8 @@ blockchainTests('Migration tests', env => { blockchainTests.resets('upgrades', async () => { it('modifies prior state', async () => { const proxyContract = await deployStakingProxyAsync(initTargetContract.address); - await proxyContract.attachStakingContract.awaitTransactionSuccessAsync(initTargetContract.address); - const initCounter = await initTargetContract.getInitCounter.callAsync({ to: proxyContract.address }); + await proxyContract.attachStakingContract(initTargetContract.address).awaitTransactionSuccessAsync(); + const initCounter = await initTargetContract.getInitCounter().callAsync({ to: proxyContract.address }); expect(initCounter).to.bignumber.eq(2); }); }); @@ -186,7 +187,7 @@ blockchainTests('Migration tests', env => { blockchainTests.resets('Staking.init()', async () => { it('throws if not called by an authorized address', async () => { - const tx = stakingContract.init.awaitTransactionSuccessAsync({ + const tx = stakingContract.init().awaitTransactionSuccessAsync({ from: notAuthorizedAddress, }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddress); @@ -194,8 +195,8 @@ blockchainTests('Migration tests', env => { }); it('throws if already intitialized', async () => { - await stakingContract.init.awaitTransactionSuccessAsync(); - const tx = stakingContract.init.awaitTransactionSuccessAsync(); + await stakingContract.init().awaitTransactionSuccessAsync(); + const tx = stakingContract.init().awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InitializationError(); return expect(tx).to.revertWith(expectedError); }); @@ -215,96 +216,116 @@ blockchainTests('Migration tests', env => { }); it('succeeds if all params are valid', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync(stakingConstants.DEFAULT_PARAMS); + const tx = proxyContract.setAndAssertParams(stakingConstants.DEFAULT_PARAMS).awaitTransactionSuccessAsync(); expect(tx).to.be.fulfilled(''); }); it('reverts if epoch duration is < 5 days', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - epochDurationInSeconds: fiveDays.minus(1), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + epochDurationInSeconds: fiveDays.minus(1), + }) + .awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration, ); return expect(tx).to.revertWith(expectedError); }); it('reverts if epoch duration is > 30 days', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - epochDurationInSeconds: thirtyDays.plus(1), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + epochDurationInSeconds: thirtyDays.plus(1), + }) + .awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration, ); return expect(tx).to.revertWith(expectedError); }); it('succeeds if epoch duration is 5 days', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - epochDurationInSeconds: fiveDays, - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + epochDurationInSeconds: fiveDays, + }) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.fulfilled(''); }); it('succeeds if epoch duration is 30 days', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - epochDurationInSeconds: thirtyDays, - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + epochDurationInSeconds: thirtyDays, + }) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.fulfilled(''); }); it('reverts if alpha denominator is 0', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - cobbDouglasAlphaDenominator: constants.ZERO_AMOUNT, - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + cobbDouglasAlphaDenominator: constants.ZERO_AMOUNT, + }) + .awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha, ); return expect(tx).to.revertWith(expectedError); }); it('reverts if alpha > 1', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - cobbDouglasAlphaNumerator: new BigNumber(101), - cobbDouglasAlphaDenominator: new BigNumber(100), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + cobbDouglasAlphaNumerator: new BigNumber(101), + cobbDouglasAlphaDenominator: new BigNumber(100), + }) + .awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha, ); return expect(tx).to.revertWith(expectedError); }); it('succeeds if alpha == 1', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - cobbDouglasAlphaNumerator: new BigNumber(1), - cobbDouglasAlphaDenominator: new BigNumber(1), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + cobbDouglasAlphaNumerator: new BigNumber(1), + cobbDouglasAlphaDenominator: new BigNumber(1), + }) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.fulfilled(''); }); it('succeeds if alpha == 0', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - cobbDouglasAlphaNumerator: constants.ZERO_AMOUNT, - cobbDouglasAlphaDenominator: new BigNumber(1), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + cobbDouglasAlphaNumerator: constants.ZERO_AMOUNT, + cobbDouglasAlphaDenominator: new BigNumber(1), + }) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.fulfilled(''); }); it('reverts if delegation weight is > 100%', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM).plus(1), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM).plus(1), + }) + .awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight, ); return expect(tx).to.revertWith(expectedError); }); it('succeeds if delegation weight is 100%', async () => { - const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({ - ...stakingConstants.DEFAULT_PARAMS, - rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM), - }); + const tx = proxyContract + .setAndAssertParams({ + ...stakingConstants.DEFAULT_PARAMS, + rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM), + }) + .awaitTransactionSuccessAsync(); return expect(tx).to.be.fulfilled(''); }); }); diff --git a/contracts/staking/test/pools_test.ts b/contracts/staking/test/pools_test.ts index a5ace2b4aa..d58f1f61dc 100644 --- a/contracts/staking/test/pools_test.ts +++ b/contracts/staking/test/pools_test.ts @@ -41,7 +41,7 @@ blockchainTests('Staking Pool Management', env => { const poolId = await poolOperator.createStakingPoolAsync(operatorShare, false); expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); // check that the next pool id was incremented - const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId.callAsync(); + const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId().callAsync(); expect(lastPoolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); }); it('Should successfully create several staking pools, as long as the operator is only a maker in one', async () => { @@ -78,7 +78,7 @@ blockchainTests('Staking Pool Management', env => { const poolId = await poolOperator.createStakingPoolAsync(operatorShare, true); expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); // check that the next pool id was incremented - const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId.callAsync(); + const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId().callAsync(); expect(lastPoolId).to.be.equal(stakingConstants.INITIAL_POOL_ID); }); it('Should throw if operatorShare is > PPM_DENOMINATOR', async () => { diff --git a/contracts/staking/test/rewards_test.ts b/contracts/staking/test/rewards_test.ts index a9da9181ad..f83f3ef37f 100644 --- a/contracts/staking/test/rewards_test.ts +++ b/contracts/staking/test/rewards_test.ts @@ -59,7 +59,7 @@ blockchainTests.resets('Testing Rewards', env => { poolOperatorStaker = new StakerActor(poolOperator.getOwner(), stakingApiWrapper); await poolOperatorStaker.stakeWithPoolAsync(poolId, new BigNumber(2)); // set exchange address - await stakingApiWrapper.stakingContract.addExchangeAddress.awaitTransactionSuccessAsync(exchangeAddress); + await stakingApiWrapper.stakingContract.addExchangeAddress(exchangeAddress).awaitTransactionSuccessAsync(); // associate operators for tracking in Finalizer const operatorByPoolId: OperatorByPoolId = {}; operatorByPoolId[poolId] = poolOperator.getOwner(); @@ -118,21 +118,19 @@ blockchainTests.resets('Testing Rewards', env => { }; const finalEndBalancesAsArray = await Promise.all([ // staker 1 - stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync( - poolId, - stakers[0].getOwner(), - ), - stakingApiWrapper.wethContract.balanceOf.callAsync(stakers[0].getOwner()), + stakingApiWrapper.stakingContract + .computeRewardBalanceOfDelegator(poolId, stakers[0].getOwner()) + .callAsync(), + stakingApiWrapper.wethContract.balanceOf(stakers[0].getOwner()).callAsync(), // staker 2 - stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync( - poolId, - stakers[1].getOwner(), - ), - stakingApiWrapper.wethContract.balanceOf.callAsync(stakers[1].getOwner()), + stakingApiWrapper.stakingContract + .computeRewardBalanceOfDelegator(poolId, stakers[1].getOwner()) + .callAsync(), + stakingApiWrapper.wethContract.balanceOf(stakers[1].getOwner()).callAsync(), // operator - stakingApiWrapper.wethContract.balanceOf.callAsync(poolOperator.getOwner()), + stakingApiWrapper.wethContract.balanceOf(poolOperator.getOwner()).callAsync(), // undivided balance in reward pool - stakingApiWrapper.stakingContract.rewardsByPoolId.callAsync(poolId), + stakingApiWrapper.stakingContract.rewardsByPoolId(poolId).callAsync(), ]); expect(finalEndBalancesAsArray[0], 'stakerRewardBalance_1').to.be.bignumber.equal( expectedEndBalances.stakerRewardBalance_1, @@ -156,12 +154,9 @@ blockchainTests.resets('Testing Rewards', env => { const payProtocolFeeAndFinalize = async (_fee?: BigNumber) => { const fee = _fee !== undefined ? _fee : constants.ZERO_AMOUNT; if (!fee.eq(constants.ZERO_AMOUNT)) { - await stakingApiWrapper.stakingContract.payProtocolFee.awaitTransactionSuccessAsync( - poolOperator.getOwner(), - takerAddress, - fee, - { from: exchangeAddress, value: fee }, - ); + await stakingApiWrapper.stakingContract + .payProtocolFee(poolOperator.getOwner(), takerAddress, fee) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: fee }); } await finalizer.finalizeAsync(); }; @@ -575,7 +570,7 @@ blockchainTests.resets('Testing Rewards', env => { await payProtocolFeeAndFinalize(); // this should go to the delegator await payProtocolFeeAndFinalize(rewardForDelegator); - await stakingApiWrapper.stakingContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync(poolId, { + await stakingApiWrapper.stakingContract.withdrawDelegatorRewards(poolId).awaitTransactionSuccessAsync({ from: stakers[0].getOwner(), }); // sanity check final balances @@ -595,18 +590,15 @@ blockchainTests.resets('Testing Rewards', env => { new StakeInfo(StakeStatus.Delegated, poolId), stakeAmount, ); - await stakingApiWrapper.stakingContract.payProtocolFee.awaitTransactionSuccessAsync( - poolOperator.getOwner(), - takerAddress, - rewardForDelegator, - { from: exchangeAddress, value: rewardForDelegator }, - ); - const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync(); + await stakingApiWrapper.stakingContract + .payProtocolFee(poolOperator.getOwner(), takerAddress, rewardForDelegator) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: rewardForDelegator }); + const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch().callAsync(); await stakingApiWrapper.utils.fastForwardToNextEpochAsync(); await stakingApiWrapper.utils.endEpochAsync(); const expectedError = new StakingRevertErrors.PoolNotFinalizedError(poolId, currentEpoch); expect( - stakingApiWrapper.stakingContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync(poolId, { + stakingApiWrapper.stakingContract.withdrawDelegatorRewards(poolId).awaitTransactionSuccessAsync({ from: stakers[0].getOwner(), }), ).to.revertWith(expectedError); @@ -689,16 +681,18 @@ blockchainTests.resets('Testing Rewards', env => { const sneakyStakerExpectedWethBalance = expectedStakerRewards[0]; await sneakyStaker.withdrawDelegatorRewardsAsync(poolId); // Should have been credited the correct amount of rewards. - let sneakyStakerWethBalance = await stakingApiWrapper.wethContract.balanceOf.callAsync( - sneakyStaker.getOwner(), - ); + let sneakyStakerWethBalance = await stakingApiWrapper.wethContract + .balanceOf(sneakyStaker.getOwner()) + .callAsync(); expect(sneakyStakerWethBalance, 'WETH balance after first undelegate').to.bignumber.eq( sneakyStakerExpectedWethBalance, ); // Now he'll try to do it again to see if he gets credited twice. await sneakyStaker.withdrawDelegatorRewardsAsync(poolId); /// The total amount credited should remain the same. - sneakyStakerWethBalance = await stakingApiWrapper.wethContract.balanceOf.callAsync(sneakyStaker.getOwner()); + sneakyStakerWethBalance = await stakingApiWrapper.wethContract + .balanceOf(sneakyStaker.getOwner()) + .callAsync(); expect(sneakyStakerWethBalance, 'WETH balance after second undelegate').to.bignumber.eq( sneakyStakerExpectedWethBalance, ); diff --git a/contracts/staking/test/stake_test.ts b/contracts/staking/test/stake_test.ts index aa5ca3cacb..cb5ac96b77 100644 --- a/contracts/staking/test/stake_test.ts +++ b/contracts/staking/test/stake_test.ts @@ -45,7 +45,7 @@ blockchainTests.resets('Stake Statuses', env => { await stakingApiWrapper.utils.createStakingPoolAsync(poolOperator, 4, false), await stakingApiWrapper.utils.createStakingPoolAsync(poolOperator, 5, false), ]); - const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId.callAsync(); + const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId().callAsync(); unusedPoolId = `0x${new BigNumber(lastPoolId) .plus(1) .toString(16) diff --git a/contracts/staking/test/unit_tests/delegator_reward_test.ts b/contracts/staking/test/unit_tests/delegator_reward_test.ts index de36003a9a..45b9c3fb57 100644 --- a/contracts/staking/test/unit_tests/delegator_reward_test.ts +++ b/contracts/staking/test/unit_tests/delegator_reward_test.ts @@ -56,13 +56,15 @@ blockchainTests.resets('Delegator rewards unit tests', env => { }; // Generate a deterministic operator address based on the poolId. _opts.operator = poolIdToOperator(_opts.poolId); - await testContract.syncPoolRewards.awaitTransactionSuccessAsync( - _opts.poolId, - _opts.operator, - new BigNumber(_opts.operatorReward), - new BigNumber(_opts.membersReward), - new BigNumber(_opts.membersStake), - ); + await testContract + .syncPoolRewards( + _opts.poolId, + _opts.operator, + new BigNumber(_opts.operatorReward), + new BigNumber(_opts.membersReward), + new BigNumber(_opts.membersStake), + ) + .awaitTransactionSuccessAsync(); // Because the operator share is implicitly defined by the member and // operator reward, and is stored as a uint32, there will be precision // loss when the reward is combined then split again in the contracts. @@ -86,13 +88,15 @@ blockchainTests.resets('Delegator rewards unit tests', env => { }; // Generate a deterministic operator address based on the poolId. _opts.operator = poolIdToOperator(_opts.poolId); - await testContract.setUnfinalizedPoolReward.awaitTransactionSuccessAsync( - _opts.poolId, - _opts.operator, - new BigNumber(_opts.operatorReward), - new BigNumber(_opts.membersReward), - new BigNumber(_opts.membersStake), - ); + await testContract + .setUnfinalizedPoolReward( + _opts.poolId, + _opts.operator, + new BigNumber(_opts.operatorReward), + new BigNumber(_opts.membersReward), + new BigNumber(_opts.membersStake), + ) + .awaitTransactionSuccessAsync(); // Because the operator share is implicitly defined by the member and // operator reward, and is stored as a uint32, there will be precision // loss when the reward is combined then split again in the contracts. @@ -148,8 +152,10 @@ blockchainTests.resets('Delegator rewards unit tests', env => { stake: getRandomInteger(1, toBaseUnitAmount(10)), ...opts, }; - const fn = now ? testContract.delegateStakeNow : testContract.delegateStake; - const receipt = await fn.awaitTransactionSuccessAsync(_opts.delegator, poolId, new BigNumber(_opts.stake)); + const fn = now + ? testContract.delegateStakeNow.bind(testContract) + : testContract.delegateStake.bind(testContract); + const receipt = await fn(_opts.delegator, poolId, new BigNumber(_opts.stake)).awaitTransactionSuccessAsync(); const delegatorTransfers = getTransfersFromLogs(receipt.logs, _opts.delegator); return { ..._opts, @@ -164,9 +170,9 @@ blockchainTests.resets('Delegator rewards unit tests', env => { ): Promise> { const _stake = new BigNumber( stake || - (await testContract.getStakeDelegatedToPoolByOwner.callAsync(delegator, poolId)).currentEpochBalance, + (await testContract.getStakeDelegatedToPoolByOwner(delegator, poolId).callAsync()).currentEpochBalance, ); - const receipt = await testContract.undelegateStake.awaitTransactionSuccessAsync(delegator, poolId, _stake); + const receipt = await testContract.undelegateStake(delegator, poolId, _stake).awaitTransactionSuccessAsync(); const delegatorTransfers = getTransfersFromLogs(receipt.logs, delegator); return { stake: _stake, @@ -189,17 +195,17 @@ blockchainTests.resets('Delegator rewards unit tests', env => { } async function advanceEpochAsync(): Promise { - await testContract.advanceEpoch.awaitTransactionSuccessAsync(); - const epoch = await testContract.currentEpoch.callAsync(); + await testContract.advanceEpoch().awaitTransactionSuccessAsync(); + const epoch = await testContract.currentEpoch().callAsync(); return epoch.toNumber(); } async function getDelegatorRewardBalanceAsync(poolId: string, delegator: string): Promise { - return testContract.computeRewardBalanceOfDelegator.callAsync(poolId, delegator); + return testContract.computeRewardBalanceOfDelegator(poolId, delegator).callAsync(); } async function getOperatorRewardBalanceAsync(poolId: string): Promise { - return testContract.computeRewardBalanceOfOperator.callAsync(poolId); + return testContract.computeRewardBalanceOfOperator(poolId).callAsync(); } async function touchStakeAsync(poolId: string, delegator: string): Promise> { @@ -207,7 +213,7 @@ blockchainTests.resets('Delegator rewards unit tests', env => { } async function finalizePoolAsync(poolId: string): Promise> { - const receipt = await testContract.finalizePool.awaitTransactionSuccessAsync(poolId); + const receipt = await testContract.finalizePool(poolId).awaitTransactionSuccessAsync(); const delegatorTransfers = getTransfersFromLogs(receipt.logs, poolId); return { delegatorTransfers, diff --git a/contracts/staking/test/unit_tests/exchange_test.ts b/contracts/staking/test/unit_tests/exchange_test.ts index 54a4263e21..fba0d7b2d8 100644 --- a/contracts/staking/test/unit_tests/exchange_test.ts +++ b/contracts/staking/test/unit_tests/exchange_test.ts @@ -38,22 +38,22 @@ blockchainTests.resets('Exchange Unit Tests', env => { ); // Register the exchange. - await exchangeManager.setValidExchange.awaitTransactionSuccessAsync(exchange); + await exchangeManager.setValidExchange(exchange).awaitTransactionSuccessAsync(); // Register an authority. - await exchangeManager.addAuthorizedAddress.awaitTransactionSuccessAsync(authority, { from: owner }); + await exchangeManager.addAuthorizedAddress(authority).awaitTransactionSuccessAsync({ from: owner }); }); describe('onlyExchange', () => { it('should revert if called by an unregistered exchange', async () => { const expectedError = new StakingRevertErrors.OnlyCallableByExchangeError(nonExchange); - return expect(exchangeManager.onlyExchangeFunction.callAsync({ from: nonExchange })).to.revertWith( + return expect(exchangeManager.onlyExchangeFunction().callAsync({ from: nonExchange })).to.revertWith( expectedError, ); }); it('should succeed if called by a registered exchange', async () => { - const didSucceed = await exchangeManager.onlyExchangeFunction.callAsync({ from: exchange }); + const didSucceed = await exchangeManager.onlyExchangeFunction().callAsync({ from: exchange }); expect(didSucceed).to.be.true(); }); }); @@ -89,7 +89,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { describe('addExchangeAddress', () => { it('should revert if called by an unauthorized address', async () => { const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(nonAuthority); - const tx = exchangeManager.addExchangeAddress.awaitTransactionSuccessAsync(nonExchange, { + const tx = exchangeManager.addExchangeAddress(nonExchange).awaitTransactionSuccessAsync({ from: nonAuthority, }); return expect(tx).to.revertWith(expectedError); @@ -97,7 +97,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { it('should revert when adding an exchange if called by the (non-authorized) owner', async () => { const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(owner); - const tx = exchangeManager.addExchangeAddress.awaitTransactionSuccessAsync(nonExchange, { + const tx = exchangeManager.addExchangeAddress(nonExchange).awaitTransactionSuccessAsync({ from: owner, }); return expect(tx).to.revertWith(expectedError); @@ -105,7 +105,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { it('should successfully add an exchange if called by an authorized address', async () => { // Register a new exchange. - const receipt = await exchangeManager.addExchangeAddress.awaitTransactionSuccessAsync(nonExchange, { + const receipt = await exchangeManager.addExchangeAddress(nonExchange).awaitTransactionSuccessAsync({ from: authority, }); @@ -113,7 +113,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { verifyExchangeManagerEvent(ExchangeManagerEventType.ExchangeAdded, nonExchange, receipt); // Ensure that the exchange was successfully registered. - const isValidExchange = await exchangeManager.validExchanges.callAsync(nonExchange); + const isValidExchange = await exchangeManager.validExchanges(nonExchange).callAsync(); expect(isValidExchange).to.be.true(); }); @@ -122,7 +122,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { StakingRevertErrors.ExchangeManagerErrorCodes.ExchangeAlreadyRegistered, exchange, ); - const tx = exchangeManager.addExchangeAddress.awaitTransactionSuccessAsync(exchange, { from: authority }); + const tx = exchangeManager.addExchangeAddress(exchange).awaitTransactionSuccessAsync({ from: authority }); return expect(tx).to.revertWith(expectedError); }); }); @@ -130,7 +130,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { describe('removeExchangeAddress', () => { it('should revert if called by an unauthorized address', async () => { const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(nonAuthority); - const tx = exchangeManager.removeExchangeAddress.awaitTransactionSuccessAsync(exchange, { + const tx = exchangeManager.removeExchangeAddress(exchange).awaitTransactionSuccessAsync({ from: nonAuthority, }); return expect(tx).to.revertWith(expectedError); @@ -138,7 +138,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { it('should revert when removing an exchange if called by the (non-authorized) owner', async () => { const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(owner); - const tx = exchangeManager.removeExchangeAddress.awaitTransactionSuccessAsync(nonExchange, { + const tx = exchangeManager.removeExchangeAddress(nonExchange).awaitTransactionSuccessAsync({ from: owner, }); return expect(tx).to.revertWith(expectedError); @@ -146,7 +146,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { it('should successfully remove a registered exchange if called by an authorized address', async () => { // Remove the registered exchange. - const receipt = await exchangeManager.removeExchangeAddress.awaitTransactionSuccessAsync(exchange, { + const receipt = await exchangeManager.removeExchangeAddress(exchange).awaitTransactionSuccessAsync({ from: authority, }); @@ -154,7 +154,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { verifyExchangeManagerEvent(ExchangeManagerEventType.ExchangeRemoved, exchange, receipt); // Ensure that the exchange was removed. - const isValidExchange = await exchangeManager.validExchanges.callAsync(exchange); + const isValidExchange = await exchangeManager.validExchanges(exchange).callAsync(); expect(isValidExchange).to.be.false(); }); @@ -163,7 +163,7 @@ blockchainTests.resets('Exchange Unit Tests', env => { StakingRevertErrors.ExchangeManagerErrorCodes.ExchangeNotRegistered, nonExchange, ); - const tx = exchangeManager.removeExchangeAddress.awaitTransactionSuccessAsync(nonExchange, { + const tx = exchangeManager.removeExchangeAddress(nonExchange).awaitTransactionSuccessAsync({ from: authority, }); return expect(tx).to.revertWith(expectedError); diff --git a/contracts/staking/test/unit_tests/finalizer_test.ts b/contracts/staking/test/unit_tests/finalizer_test.ts index 04846e498b..571b46502a 100644 --- a/contracts/staking/test/unit_tests/finalizer_test.ts +++ b/contracts/staking/test/unit_tests/finalizer_test.ts @@ -76,13 +76,15 @@ blockchainTests.resets('Finalizer unit tests', env => { weightedStake: getRandomInteger(0, maxAmount), ...opts, }; - await testContract.addActivePool.awaitTransactionSuccessAsync( - _opts.poolId, - new BigNumber(_opts.operatorShare * constants.PPM_DENOMINATOR).integerValue(), - new BigNumber(_opts.feesCollected), - new BigNumber(_opts.membersStake), - new BigNumber(_opts.weightedStake), - ); + await testContract + .addActivePool( + _opts.poolId, + new BigNumber(_opts.operatorShare * constants.PPM_DENOMINATOR).integerValue(), + new BigNumber(_opts.feesCollected), + new BigNumber(_opts.membersStake), + new BigNumber(_opts.weightedStake), + ) + .awaitTransactionSuccessAsync(); return _opts; } @@ -95,13 +97,13 @@ blockchainTests.resets('Finalizer unit tests', env => { } async function getUnfinalizedStateAsync(): Promise { - return testContract.getAggregatedStatsForPreviousEpoch.callAsync(); + return testContract.getAggregatedStatsForPreviousEpoch().callAsync(); } async function finalizePoolsAsync(poolIds: string[]): Promise { const logs = [] as LogEntry[]; for (const poolId of poolIds) { - const receipt = await testContract.finalizePool.awaitTransactionSuccessAsync(poolId); + const receipt = await testContract.finalizePool(poolId).awaitTransactionSuccessAsync(); logs.splice(logs.length, 0, ...receipt.logs); } return logs; @@ -208,13 +210,15 @@ blockchainTests.resets('Finalizer unit tests', env => { if (feesCollected.isZero()) { continue; } - poolRewards[i] = await testContract.cobbDouglas.callAsync( - new BigNumber(rewardsAvailable), - new BigNumber(feesCollected), - new BigNumber(totalFees), - new BigNumber(pool.weightedStake), - new BigNumber(totalStake), - ); + poolRewards[i] = await testContract + .cobbDouglas( + new BigNumber(rewardsAvailable), + new BigNumber(feesCollected), + new BigNumber(totalFees), + new BigNumber(pool.weightedStake), + new BigNumber(totalStake), + ) + .callAsync(); } return poolRewards; } @@ -257,7 +261,7 @@ blockchainTests.resets('Finalizer unit tests', env => { } async function getCurrentEpochAsync(): Promise { - return testContract.currentEpoch.callAsync(); + return testContract.currentEpoch().callAsync(); } async function getBalanceOfAsync(whom: string): Promise { @@ -266,13 +270,13 @@ blockchainTests.resets('Finalizer unit tests', env => { describe('endEpoch()', () => { it('advances the epoch', async () => { - await testContract.endEpoch.awaitTransactionSuccessAsync(); - const currentEpoch = await testContract.currentEpoch.callAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); + const currentEpoch = await testContract.currentEpoch().callAsync(); expect(currentEpoch).to.bignumber.eq(stakingConstants.INITIAL_EPOCH.plus(1)); }); it('emits an `EpochEnded` event', async () => { - const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync(); assertEpochEndedEvent(receipt.logs, { epoch: stakingConstants.INITIAL_EPOCH, numActivePools: ZERO_AMOUNT, @@ -283,7 +287,7 @@ blockchainTests.resets('Finalizer unit tests', env => { }); it('immediately finalizes if there are no pools to finalize', async () => { - const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync(); assertEpochFinalizedEvent(receipt.logs, { epoch: stakingConstants.INITIAL_EPOCH, rewardsPaid: ZERO_AMOUNT, @@ -293,7 +297,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('does not immediately finalize if there is a pool to finalize', async () => { await addActivePoolAsync(); - const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync(); const events = filterLogsToArguments( receipt.logs, IStakingEventsEvents.EpochFinalized, @@ -304,7 +308,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('prepares unfinalized state', async () => { // Add a pool so there is state to clear. const pool = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); return assertUnfinalizedStateAsync({ numPoolsToFinalize: 1, rewardsAvailable: INITIAL_BALANCE, @@ -315,9 +319,9 @@ blockchainTests.resets('Finalizer unit tests', env => { it("correctly stores the epoch's aggregated stats after ending the epoch", async () => { const pool = await addActivePoolAsync(); - const epoch = await testContract.currentEpoch.callAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); - const aggregatedStats = await testContract.aggregatedStatsByEpoch.callAsync(epoch); + const epoch = await testContract.currentEpoch().callAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); + const aggregatedStats = await testContract.aggregatedStatsByEpoch(epoch).callAsync(); expect(aggregatedStats).to.be.deep.equal([ INITIAL_BALANCE, new BigNumber(1), // pools to finalize @@ -329,8 +333,8 @@ blockchainTests.resets('Finalizer unit tests', env => { it('reverts if the prior epoch is unfinalized', async () => { await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); - const tx = testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); + const tx = testContract.endEpoch().awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.PreviousEpochNotFinalizedError( stakingConstants.INITIAL_EPOCH, 1, @@ -341,7 +345,7 @@ blockchainTests.resets('Finalizer unit tests', env => { describe('_finalizePool()', () => { it('does nothing if there were no pools to finalize', async () => { - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const poolId = hexRandom(); const logs = await finalizePoolsAsync([poolId]); expect(logs).to.deep.eq([]); @@ -349,21 +353,21 @@ blockchainTests.resets('Finalizer unit tests', env => { it('can finalize a pool', async () => { const pool = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const logs = await finalizePoolsAsync([pool.poolId]); return assertFinalizationLogsAndBalancesAsync(INITIAL_BALANCE, [pool], logs); }); it('can finalize multiple pools over multiple transactions', async () => { const pools = await Promise.all(_.times(2, async () => addActivePoolAsync())); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const logs = await finalizePoolsAsync(pools.map(p => p.poolId)); return assertFinalizationLogsAndBalancesAsync(INITIAL_BALANCE, pools, logs); }); it('ignores a finalized pool', async () => { const pools = await Promise.all(_.times(3, async () => addActivePoolAsync())); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const [finalizedPool] = _.sampleSize(pools, 1); await finalizePoolsAsync([finalizedPool.poolId]); const logs = await finalizePoolsAsync([finalizedPool.poolId]); @@ -374,12 +378,11 @@ blockchainTests.resets('Finalizer unit tests', env => { it('resets pool state after finalizing it', async () => { const pools = await Promise.all(_.times(3, async () => addActivePoolAsync())); const pool = _.sample(pools) as ActivePoolOpts; - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await finalizePoolsAsync([pool.poolId]); - const poolState = await testContract.getPoolStatsFromEpoch.callAsync( - stakingConstants.INITIAL_EPOCH, - pool.poolId, - ); + const poolState = await testContract + .getPoolStatsFromEpoch(stakingConstants.INITIAL_EPOCH, pool.poolId) + .callAsync(); expect(poolState.feesCollected).to.bignumber.eq(0); expect(poolState.weightedStake).to.bignumber.eq(0); expect(poolState.membersStake).to.bignumber.eq(0); @@ -387,7 +390,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('`rewardsPaid` <= `rewardsAvailable` <= contract balance at the end of the epoch', async () => { const pools = await Promise.all(_.times(3, async () => addActivePoolAsync())); - const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync(); const { rewardsAvailable } = getEpochEndedEvents(receipt.logs)[0]; expect(rewardsAvailable).to.bignumber.lte(INITIAL_BALANCE); const logs = await finalizePoolsAsync(pools.map(r => r.poolId)); @@ -398,7 +401,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('`rewardsPaid` <= `rewardsAvailable` with two equal pools', async () => { const pool1 = await addActivePoolAsync(); const pool2 = await addActivePoolAsync(_.omit(pool1, 'poolId')); - const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync(); const { rewardsAvailable } = getEpochEndedEvents(receipt.logs)[0]; const logs = await finalizePoolsAsync([pool1, pool2].map(r => r.poolId)); const { rewardsPaid } = getEpochFinalizedEvents(logs)[0]; @@ -411,7 +414,7 @@ blockchainTests.resets('Finalizer unit tests', env => { const numPools = _.random(1, 32); it(`${i + 1}/${numTests} \`rewardsPaid\` <= \`rewardsAvailable\` (${numPools} pools)`, async () => { const pools = await Promise.all(_.times(numPools, async () => addActivePoolAsync())); - const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync(); const { rewardsAvailable } = getEpochEndedEvents(receipt.logs)[0]; const logs = await finalizePoolsAsync(pools.map(r => r.poolId)); const { rewardsPaid } = getEpochFinalizedEvents(logs)[0]; @@ -424,18 +427,18 @@ blockchainTests.resets('Finalizer unit tests', env => { describe('lifecycle', () => { it('can advance the epoch after the prior epoch is finalized', async () => { const pool = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await finalizePoolsAsync([pool.poolId]); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); return expect(getCurrentEpochAsync()).to.become(stakingConstants.INITIAL_EPOCH.plus(2)); }); it('does not reward a pool that only earned rewards 2 epochs ago', async () => { const pool1 = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await finalizePoolsAsync([pool1.poolId]); await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); expect(getCurrentEpochAsync()).to.become(stakingConstants.INITIAL_EPOCH.plus(2)); const logs = await finalizePoolsAsync([pool1.poolId]); const rewardsPaidEvents = getRewardsPaidEvents(logs); @@ -444,11 +447,11 @@ blockchainTests.resets('Finalizer unit tests', env => { it('does not reward a pool that only earned rewards 3 epochs ago', async () => { const pool1 = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await finalizePoolsAsync([pool1.poolId]); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); expect(getCurrentEpochAsync()).to.become(stakingConstants.INITIAL_EPOCH.plus(3)); const logs = await finalizePoolsAsync([pool1.poolId]); const rewardsPaidEvents = getRewardsPaidEvents(logs); @@ -458,11 +461,11 @@ blockchainTests.resets('Finalizer unit tests', env => { it('rolls over leftover rewards into the next epoch', async () => { const poolIds = _.times(3, () => hexRandom()); await Promise.all(poolIds.map(async id => addActivePoolAsync({ poolId: id }))); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const finalizeLogs = await finalizePoolsAsync(poolIds); const { rewardsRemaining: rolledOverRewards } = getEpochFinalizedEvents(finalizeLogs)[0]; await Promise.all(poolIds.map(async id => addActivePoolAsync({ poolId: id }))); - const { logs: endEpochLogs } = await testContract.endEpoch.awaitTransactionSuccessAsync(); + const { logs: endEpochLogs } = await testContract.endEpoch().awaitTransactionSuccessAsync(); const { rewardsAvailable } = getEpochEndedEvents(endEpochLogs)[0]; expect(rewardsAvailable).to.bignumber.eq(rolledOverRewards); }); @@ -477,7 +480,7 @@ blockchainTests.resets('Finalizer unit tests', env => { poolId: string, expected: Partial, ): Promise { - const actual = await testContract.getUnfinalizedPoolRewards.callAsync(poolId); + const actual = await testContract.getUnfinalizedPoolRewards(poolId).callAsync(); if (expected.totalReward !== undefined) { expect(actual.totalReward).to.bignumber.eq(expected.totalReward); } @@ -498,7 +501,7 @@ blockchainTests.resets('Finalizer unit tests', env => { }); it('returns empty if pool did not earn rewards', async () => { - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const poolId = hexRandom(); return assertUnfinalizedPoolRewardsAsync(poolId, ZERO_REWARDS); }); @@ -510,7 +513,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('returns empty if pool only earned rewards in the 2 epochs ago', async () => { const pool = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await finalizePoolsAsync([pool.poolId]); return assertUnfinalizedPoolRewardsAsync(pool.poolId, ZERO_REWARDS); }); @@ -518,14 +521,14 @@ blockchainTests.resets('Finalizer unit tests', env => { it('returns empty if pool was already finalized', async () => { const pools = await Promise.all(_.times(3, async () => addActivePoolAsync())); const [pool] = _.sampleSize(pools, 1); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); await finalizePoolsAsync([pool.poolId]); return assertUnfinalizedPoolRewardsAsync(pool.poolId, ZERO_REWARDS); }); it('computes one reward among one pool', async () => { const pool = await addActivePoolAsync(); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const expectedTotalRewards = INITIAL_BALANCE; return assertUnfinalizedPoolRewardsAsync(pool.poolId, { totalReward: expectedTotalRewards, @@ -535,7 +538,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('computes one reward among multiple pools', async () => { const pools = await Promise.all(_.times(3, async () => addActivePoolAsync())); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); const expectedPoolRewards = await calculatePoolRewardsAsync(INITIAL_BALANCE, pools); const [pool, reward] = _.sampleSize(shortZip(pools, expectedPoolRewards), 1)[0]; return assertUnfinalizedPoolRewardsAsync(pool.poolId, { @@ -546,7 +549,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('computes a reward with 0% operatorShare', async () => { const pool = await addActivePoolAsync({ operatorShare: 0 }); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); return assertUnfinalizedPoolRewardsAsync(pool.poolId, { totalReward: INITIAL_BALANCE, membersStake: pool.membersStake, @@ -555,7 +558,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('computes a reward with 0% < operatorShare < 100%', async () => { const pool = await addActivePoolAsync({ operatorShare: Math.random() }); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); return assertUnfinalizedPoolRewardsAsync(pool.poolId, { totalReward: INITIAL_BALANCE, membersStake: pool.membersStake, @@ -564,7 +567,7 @@ blockchainTests.resets('Finalizer unit tests', env => { it('computes a reward with 100% operatorShare', async () => { const pool = await addActivePoolAsync({ operatorShare: 1 }); - await testContract.endEpoch.awaitTransactionSuccessAsync(); + await testContract.endEpoch().awaitTransactionSuccessAsync(); return assertUnfinalizedPoolRewardsAsync(pool.poolId, { totalReward: INITIAL_BALANCE, membersStake: pool.membersStake, diff --git a/contracts/staking/test/unit_tests/lib_cobb_douglas_test.ts b/contracts/staking/test/unit_tests/lib_cobb_douglas_test.ts index f37fbc4751..4c186299a5 100644 --- a/contracts/staking/test/unit_tests/lib_cobb_douglas_test.ts +++ b/contracts/staking/test/unit_tests/lib_cobb_douglas_test.ts @@ -56,18 +56,19 @@ blockchainTests('LibCobbDouglas unit tests', env => { ...DEFAULT_COBB_DOUGLAS_PARAMS, ...params, }; - return testContract.cobbDouglas.callAsync( - new BigNumber(_params.totalRewards), - new BigNumber(_params.ownerFees), - new BigNumber(_params.totalFees), - new BigNumber(_params.ownerStake), - new BigNumber(_params.totalStake), - new BigNumber(_params.alphaNumerator), - new BigNumber(_params.alphaDenominator), - { + return testContract + .cobbDouglas( + new BigNumber(_params.totalRewards), + new BigNumber(_params.ownerFees), + new BigNumber(_params.totalFees), + new BigNumber(_params.ownerStake), + new BigNumber(_params.totalStake), + new BigNumber(_params.alphaNumerator), + new BigNumber(_params.alphaDenominator), + ) + .callAsync({ gas: TX_GAS_FEE + (_params.gas === undefined ? MAX_COBB_DOUGLAS_GAS : _params.gas), - }, - ); + }); } function cobbDouglas(params?: Partial): BigNumber { diff --git a/contracts/staking/test/unit_tests/lib_fixed_math_test.ts b/contracts/staking/test/unit_tests/lib_fixed_math_test.ts index 43aeface8c..ae020ebc4d 100644 --- a/contracts/staking/test/unit_tests/lib_fixed_math_test.ts +++ b/contracts/staking/test/unit_tests/lib_fixed_math_test.ts @@ -41,7 +41,7 @@ blockchainTests('LibFixedMath unit tests', env => { describe('one()', () => { it('equals 1', async () => { - const r = await testContract.one.callAsync(); + const r = await testContract.one().callAsync(); assertFixedEquals(r, 1); }); }); @@ -49,25 +49,25 @@ blockchainTests('LibFixedMath unit tests', env => { describe('abs()', () => { it('abs(n) == n', async () => { const n = 1337.5912; - const r = await testContract.abs.callAsync(toFixed(n)); + const r = await testContract.abs(toFixed(n)).callAsync(); assertFixedEquals(r, n); }); it('abs(-n) == n', async () => { const n = -1337.5912; - const r = await testContract.abs.callAsync(toFixed(n)); + const r = await testContract.abs(toFixed(n)).callAsync(); assertFixedEquals(r, -n); }); it('abs(0) == 0', async () => { const n = 0; - const r = await testContract.abs.callAsync(toFixed(n)); + const r = await testContract.abs(toFixed(n)).callAsync(); expect(r).to.bignumber.eq(0); }); it('abs(MAX_FIXED) == MAX_FIXED', async () => { const n = MAX_FIXED_VALUE; - const r = await testContract.abs.callAsync(n); + const r = await testContract.abs(n).callAsync(); expect(r).to.bignumber.eq(n); }); @@ -77,19 +77,19 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooSmall, n, ); - const tx = testContract.abs.callAsync(n); + const tx = testContract.abs(n).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('abs(int(-1)) == int(1)', async () => { const n = -1; - const r = await testContract.abs.callAsync(new BigNumber(n)); + const r = await testContract.abs(new BigNumber(n)).callAsync(); expect(r).to.bignumber.eq(1); }); it('abs(int(1)) == int(1)', async () => { const n = 1; - const r = await testContract.abs.callAsync(new BigNumber(n)); + const r = await testContract.abs(new BigNumber(n)).callAsync(); expect(r).to.bignumber.eq(1); }); }); @@ -97,19 +97,19 @@ blockchainTests('LibFixedMath unit tests', env => { describe('invert()', () => { it('invert(1) == 1', async () => { const n = 1; - const r = await testContract.invert.callAsync(toFixed(n)); + const r = await testContract.invert(toFixed(n)).callAsync(); assertFixedEquals(r, n); }); it('invert(n) == 1 / n', async () => { const n = 1337.5912; - const r = await testContract.invert.callAsync(toFixed(n)); + const r = await testContract.invert(toFixed(n)).callAsync(); assertFixedRoughlyEquals(r, 1 / n); }); it('invert(-n) == -1 / n', async () => { const n = -1337.5912; - const r = await testContract.invert.callAsync(toFixed(n)); + const r = await testContract.invert(toFixed(n)).callAsync(); assertFixedRoughlyEquals(r, 1 / n); }); @@ -117,7 +117,7 @@ blockchainTests('LibFixedMath unit tests', env => { const expectedError = new FixedMathRevertErrors.BinOpError( FixedMathRevertErrors.BinOpErrorCodes.DivisionByZero, ); - const tx = testContract.invert.callAsync(toFixed(0)); + const tx = testContract.invert(toFixed(0)).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -125,31 +125,31 @@ blockchainTests('LibFixedMath unit tests', env => { describe('mulDiv()', () => { it('mulDiv(0, 0, 1) == 0', async () => { const [a, n, d] = [0, 0, 1]; - const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, 0); }); it('mulDiv(0, x, y) == 0', async () => { const [a, n, d] = [0, 13, 300]; - const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, 0); }); it('mulDiv(x, y, y) == x', async () => { const [a, n, d] = [1.2345, 149, 149]; - const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, a); }); it('mulDiv(x, -y, y) == -x', async () => { const [a, n, d] = [1.2345, -149, 149]; - const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, -a); }); it('mulDiv(-x, -y, y) == x', async () => { const [a, n, d] = [-1.2345, -149, 149]; - const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, -a); }); @@ -158,19 +158,19 @@ blockchainTests('LibFixedMath unit tests', env => { const expectedError = new FixedMathRevertErrors.BinOpError( FixedMathRevertErrors.BinOpErrorCodes.DivisionByZero, ); - const tx = testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d)); + const tx = testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('mulDiv(int(-1), int(1), int(-1)) == int(1)', async () => { const [a, n, d] = [-1, 1, -1]; - const r = await testContract.mulDiv.callAsync(new BigNumber(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(new BigNumber(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, fromFixed(1)); }); it('mulDiv(int(1), int(-1), int(-1)) == int(1)', async () => { const [a, n, d] = [1, -1, -1]; - const r = await testContract.mulDiv.callAsync(new BigNumber(a), new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(new BigNumber(a), new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, fromFixed(1)); }); @@ -181,7 +181,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, n, ); - const tx = testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d)); + const tx = testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -192,7 +192,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, n, ); - const tx = testContract.mulDiv.callAsync(new BigNumber(a), n, new BigNumber(d)); + const tx = testContract.mulDiv(new BigNumber(a), n, new BigNumber(d)).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -203,19 +203,19 @@ blockchainTests('LibFixedMath unit tests', env => { a, d, ); - const tx = testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d)); + const tx = testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('mulDiv(MAX_FIXED, int(-1), int(1)) == -MAX_FIXED', async () => { const [a, n, d] = [MAX_FIXED_VALUE, -1, 1]; - const r = await testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync(); expect(r).to.bignumber.eq(MAX_FIXED_VALUE.negated()); }); it('mulDiv(MAX_FIXED, int(1), int(-1)) == -MAX_FIXED', async () => { const [a, n, d] = [MAX_FIXED_VALUE, 1, -1]; - const r = await testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d)); + const r = await testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync(); expect(r).to.bignumber.eq(MAX_FIXED_VALUE.negated()); }); }); @@ -227,19 +227,19 @@ blockchainTests('LibFixedMath unit tests', env => { it('0 + 0 == 0', async () => { const [a, b] = [0, 0]; - const r = await testContract.add.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.add(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, 0); }); it('adds two positive decimals', async () => { const [a, b] = ['9310841.31841', '491021921.318948193']; - const r = await testContract.add.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.add(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, add(a, b)); }); it('adds two mixed decimals', async () => { const [a, b] = ['9310841.31841', '-491021921.318948193']; - const r = await testContract.add.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.add(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, add(a, b)); }); @@ -250,7 +250,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.add.callAsync(a, b); + const tx = testContract.add(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -261,7 +261,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.add.callAsync(a, b); + const tx = testContract.add(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -272,7 +272,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.add.callAsync(a, b); + const tx = testContract.add(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -283,19 +283,19 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.add.callAsync(a, b); + const tx = testContract.add(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('MIN_FIXED + MAX_FIXED == int(-1)', async () => { const [a, b] = [MIN_FIXED_VALUE, MAX_FIXED_VALUE]; - const r = await testContract.add.callAsync(a, b); + const r = await testContract.add(a, b).callAsync(); expect(r).to.bignumber.eq(-1); }); it('MAX_FIXED + (MIN_FIXED + int(1)) == 0', async () => { const [a, b] = [MAX_FIXED_VALUE, MIN_FIXED_VALUE.plus(1)]; - const r = await testContract.add.callAsync(a, b); + const r = await testContract.add(a, b).callAsync(); expect(r).to.bignumber.eq(0); }); }); @@ -307,19 +307,19 @@ blockchainTests('LibFixedMath unit tests', env => { it('0 - 0 == 0', async () => { const [a, b] = [0, 0]; - const r = await testContract.sub.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.sub(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, 0); }); it('subtracts two positive decimals', async () => { const [a, b] = ['9310841.31841', '491021921.318948193']; - const r = await testContract.sub.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.sub(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, sub(a, b)); }); it('subtracts two mixed decimals', async () => { const [a, b] = ['9310841.31841', '-491021921.318948193']; - const r = await testContract.sub.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.sub(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, sub(a, b)); }); @@ -330,7 +330,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b.negated(), ); - const tx = testContract.sub.callAsync(a, b); + const tx = testContract.sub(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -341,7 +341,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b.negated(), ); - const tx = testContract.sub.callAsync(a, b); + const tx = testContract.sub(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -353,13 +353,13 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooSmall, b, ); - const tx = testContract.sub.callAsync(a, b); + const tx = testContract.sub(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('MAX_FIXED - MAX_FIXED == 0', async () => { const [a, b] = [MAX_FIXED_VALUE, MAX_FIXED_VALUE]; - const r = await testContract.sub.callAsync(a, b); + const r = await testContract.sub(a, b).callAsync(); expect(r).to.bignumber.eq(0); }); @@ -370,7 +370,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b.negated(), ); - const tx = testContract.sub.callAsync(a, b); + const tx = testContract.sub(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -380,7 +380,7 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooSmall, b, ); - const tx = testContract.sub.callAsync(a, b); + const tx = testContract.sub(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -396,31 +396,31 @@ blockchainTests('LibFixedMath unit tests', env => { it('x * 0 == 0', async () => { const [a, b] = [1337, 0]; - const r = await testContract.mul.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, b); }); it('x * 1 == x', async () => { const [a, b] = [0.5, 1]; - const r = await testContract.mul.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, a); }); it('x * -1 == -x', async () => { const [a, b] = [0.5, -1]; - const r = await testContract.mul.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, -a); }); it('multiplies two positive decimals', async () => { const [a, b] = ['1.25394912112', '0.03413318948193']; - const r = await testContract.mul.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, mul(a, b)); }); it('multiplies two mixed decimals', async () => { const [a, b] = ['1.25394912112', '-0.03413318948193']; - const r = await testContract.mul.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, mul(a, b)); }); @@ -431,7 +431,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, b); + const tx = testContract.mul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -442,13 +442,13 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, b); + const tx = testContract.mul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('MAX_FIXED * int(1) == MAX_FIXED / FIXED_1', async () => { const [a, b] = [MAX_FIXED_VALUE, 1]; - const r = await testContract.mul.callAsync(a, new BigNumber(b)); + const r = await testContract.mul(a, new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(MAX_FIXED_VALUE.dividedToIntegerBy(FIXED_1)); }); @@ -459,7 +459,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, new BigNumber(b)); + const tx = testContract.mul(a, new BigNumber(b)).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -470,7 +470,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, b); + const tx = testContract.mul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -481,7 +481,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, b); + const tx = testContract.mul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -492,7 +492,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, b); + const tx = testContract.mul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -503,7 +503,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(a, new BigNumber(b)); + const tx = testContract.mul(a, new BigNumber(b)).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -514,13 +514,13 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.mul.callAsync(new BigNumber(a), b); + const tx = testContract.mul(new BigNumber(a), b).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('MAX_FIXED * int(-1) == -MAX_FIXED / FIXED_1', async () => { const [a, b] = [MAX_FIXED_VALUE, -1]; - const r = await testContract.mul.callAsync(a, new BigNumber(b)); + const r = await testContract.mul(a, new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(MAX_FIXED_VALUE.negated().dividedToIntegerBy(FIXED_1)); }); }); @@ -541,31 +541,31 @@ blockchainTests('LibFixedMath unit tests', env => { toFixed(a).times(FIXED_POINT_DIVISOR), toFixed(b), ); - const tx = testContract.div.callAsync(toFixed(a), toFixed(b)); + const tx = testContract.div(toFixed(a), toFixed(b)).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('x / 1 == x', async () => { const [a, b] = [1.41214552, 1]; - const r = await testContract.div.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.div(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, a); }); it('x / -1 == -x', async () => { const [a, b] = [1.109312, -1]; - const r = await testContract.div.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.div(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, -a); }); it('divides two positive decimals', async () => { const [a, b] = ['1.25394912112', '0.03413318948193']; - const r = await testContract.div.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.div(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, div(a, b)); }); it('divides two mixed decimals', async () => { const [a, b] = ['1.25394912112', '-0.03413318948193']; - const r = await testContract.div.callAsync(toFixed(a), toFixed(b)); + const r = await testContract.div(toFixed(a), toFixed(b)).callAsync(); assertFixedEquals(r, div(a, b)); }); @@ -576,7 +576,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, FIXED_1, ); - const tx = testContract.div.callAsync(a, new BigNumber(b)); + const tx = testContract.div(a, new BigNumber(b)).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -587,13 +587,13 @@ blockchainTests('LibFixedMath unit tests', env => { a, FIXED_1, ); - const tx = testContract.div.callAsync(a, new BigNumber(b)); + const tx = testContract.div(a, new BigNumber(b)).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('int(-1) / MIN_FIXED == 0', async () => { const [a, b] = [-1, MIN_FIXED_VALUE]; - const r = await testContract.div.callAsync(new BigNumber(a), b); + const r = await testContract.div(new BigNumber(a), b).callAsync(); expect(r).to.bignumber.eq(0); }); }); @@ -601,31 +601,31 @@ blockchainTests('LibFixedMath unit tests', env => { describe('uintMul()', () => { it('0 * x == 0', async () => { const [a, b] = [0, 1234]; - const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b)); + const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(0); }); it('1 * x == int(x)', async () => { const [a, b] = [1, 1234]; - const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b)); + const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(Math.trunc(b)); }); it('-1 * x == 0', async () => { const [a, b] = [-1, 1234]; - const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b)); + const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(0); }); it('0.5 * x == x/2', async () => { const [a, b] = [0.5, 1234]; - const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b)); + const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(b / 2); }); it('0.5 * x == 0 if x = 1', async () => { const [a, b] = [0.5, 1]; - const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b)); + const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync(); expect(r).to.bignumber.eq(0); }); @@ -635,7 +635,7 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooLarge, b, ); - const tx = testContract.uintMul.callAsync(a, b); + const tx = testContract.uintMul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -646,7 +646,7 @@ blockchainTests('LibFixedMath unit tests', env => { a, b, ); - const tx = testContract.uintMul.callAsync(a, b); + const tx = testContract.uintMul(a, b).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -654,31 +654,31 @@ blockchainTests('LibFixedMath unit tests', env => { describe('toInteger()', () => { it('toInteger(n) == int(n)', async () => { const n = 1337.5912; - const r = await testContract.toInteger.callAsync(toFixed(n)); + const r = await testContract.toInteger(toFixed(n)).callAsync(); expect(r).to.bignumber.eq(Math.trunc(n)); }); it('toInteger(-n) == -int(n)', async () => { const n = -1337.5912; - const r = await testContract.toInteger.callAsync(toFixed(n)); + const r = await testContract.toInteger(toFixed(n)).callAsync(); expect(r).to.bignumber.eq(Math.trunc(n)); }); it('toInteger(n) == 0, when 0 < n < 1', async () => { const n = 0.9995; - const r = await testContract.toInteger.callAsync(toFixed(n)); + const r = await testContract.toInteger(toFixed(n)).callAsync(); expect(r).to.bignumber.eq(0); }); it('toInteger(-n) == 0, when -1 < n < 0', async () => { const n = -0.9995; - const r = await testContract.toInteger.callAsync(toFixed(n)); + const r = await testContract.toInteger(toFixed(n)).callAsync(); expect(r).to.bignumber.eq(0); }); it('toInteger(0) == 0', async () => { const n = 0; - const r = await testContract.toInteger.callAsync(toFixed(n)); + const r = await testContract.toInteger(toFixed(n)).callAsync(); expect(r).to.bignumber.eq(0); }); }); @@ -687,37 +687,37 @@ blockchainTests('LibFixedMath unit tests', env => { describe('signed', () => { it('converts a positive integer', async () => { const n = 1337; - const r = await testContract.toFixedSigned1.callAsync(new BigNumber(n)); + const r = await testContract.toFixedSigned1(new BigNumber(n)).callAsync(); assertFixedEquals(r, n); }); it('converts a negative integer', async () => { const n = -1337; - const r = await testContract.toFixedSigned1.callAsync(new BigNumber(n)); + const r = await testContract.toFixedSigned1(new BigNumber(n)).callAsync(); assertFixedEquals(r, n); }); it('converts a fraction with a positive numerator and denominator', async () => { const [n, d] = [1337, 1000]; - const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d)); + const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, n / d); }); it('converts a fraction with a negative numerator and positive denominator', async () => { const [n, d] = [-1337, 1000]; - const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d)); + const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, n / d); }); it('converts a fraction with a negative numerator and denominator', async () => { const [n, d] = [-1337, -1000]; - const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d)); + const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, n / d); }); it('converts a fraction with a negative numerator and negative denominator', async () => { const [n, d] = [-1337, -1000]; - const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d)); + const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, n / d); }); @@ -728,7 +728,7 @@ blockchainTests('LibFixedMath unit tests', env => { n, FIXED_POINT_DIVISOR, ); - const tx = testContract.toFixedSigned2.callAsync(n, d); + const tx = testContract.toFixedSigned2(n, d).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -739,7 +739,7 @@ blockchainTests('LibFixedMath unit tests', env => { n.times(FIXED_POINT_DIVISOR), d, ); - const tx = testContract.toFixedSigned2.callAsync(n, d); + const tx = testContract.toFixedSigned2(n, d).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -747,13 +747,13 @@ blockchainTests('LibFixedMath unit tests', env => { describe('unsigned', () => { it('converts an integer', async () => { const n = 1337; - const r = await testContract.toFixedUnsigned1.callAsync(new BigNumber(n)); + const r = await testContract.toFixedUnsigned1(new BigNumber(n)).callAsync(); assertFixedEquals(r, n); }); it('converts a fraction', async () => { const [n, d] = [1337, 1000]; - const r = await testContract.toFixedUnsigned2.callAsync(new BigNumber(n), new BigNumber(d)); + const r = await testContract.toFixedUnsigned2(new BigNumber(n), new BigNumber(d)).callAsync(); assertFixedEquals(r, n / d); }); @@ -763,7 +763,7 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooLarge, n, ); - const tx = testContract.toFixedUnsigned2.callAsync(n, d); + const tx = testContract.toFixedUnsigned2(n, d).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -773,7 +773,7 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooLarge, d, ); - const tx = testContract.toFixedUnsigned2.callAsync(n, d); + const tx = testContract.toFixedUnsigned2(n, d).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -784,7 +784,7 @@ blockchainTests('LibFixedMath unit tests', env => { n, FIXED_POINT_DIVISOR, ); - const tx = testContract.toFixedUnsigned2.callAsync(n, d); + const tx = testContract.toFixedUnsigned2(n, d).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -795,7 +795,7 @@ blockchainTests('LibFixedMath unit tests', env => { n.times(FIXED_POINT_DIVISOR), d, ); - const tx = testContract.toFixedUnsigned2.callAsync(n, d); + const tx = testContract.toFixedUnsigned2(n, d).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -824,7 +824,7 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooSmall, x, ); - const tx = testContract.ln.callAsync(x); + const tx = testContract.ln(x).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -834,7 +834,7 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooLarge, x, ); - const tx = testContract.ln.callAsync(x); + const tx = testContract.ln(x).callAsync(); return expect(tx).to.revertWith(expectedError); }); @@ -844,37 +844,37 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooSmall, x, ); - const tx = testContract.ln.callAsync(x); + const tx = testContract.ln(x).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('ln(x = 1) == 0', async () => { const x = toFixed(1); - const r = await testContract.ln.callAsync(x); + const r = await testContract.ln(x).callAsync(); assertFixedEquals(r, 0); }); it('ln(x < LN_MIN_VAL) == EXP_MIN_VAL', async () => { const x = toFixed(MIN_LN_NUMBER).minus(1); - const r = await testContract.ln.callAsync(x); + const r = await testContract.ln(x).callAsync(); assertFixedEquals(r, MIN_EXP_NUMBER); }); it('ln(x), where x is close to 0', async () => { const x = new BigNumber('1e-27'); - const r = await testContract.ln.callAsync(toFixed(x)); + const r = await testContract.ln(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, ln(x), 12); }); it('ln(x), where x is close to 1', async () => { const x = new BigNumber(1).minus('1e-27'); - const r = await testContract.ln.callAsync(toFixed(x)); + const r = await testContract.ln(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, ln(x), LN_PRECISION); }); it('ln(x = 0.85)', async () => { const x = 0.85; - const r = await testContract.ln.callAsync(toFixed(x)); + const r = await testContract.ln(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, ln(x), LN_PRECISION); }); @@ -882,7 +882,7 @@ blockchainTests('LibFixedMath unit tests', env => { const inputs = _.times(FUZZ_COUNT, () => getRandomDecimal(0, 1)); for (const x of inputs) { it(`ln(${x.toString(10)})`, async () => { - const r = await testContract.ln.callAsync(toFixed(x)); + const r = await testContract.ln(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, ln(x), LN_PRECISION); }); } @@ -902,7 +902,7 @@ blockchainTests('LibFixedMath unit tests', env => { it('exp(x = 0) == 1', async () => { const x = toFixed(0); - const r = await testContract.exp.callAsync(x); + const r = await testContract.exp(x).callAsync(); assertFixedEquals(r, 1); }); @@ -912,31 +912,31 @@ blockchainTests('LibFixedMath unit tests', env => { FixedMathRevertErrors.ValueErrorCodes.TooLarge, x, ); - const tx = testContract.exp.callAsync(x); + const tx = testContract.exp(x).callAsync(); return expect(tx).to.revertWith(expectedError); }); it('exp(x < EXP_MIN_VAL) == 0', async () => { const x = toFixed(MIN_EXP_NUMBER).minus(1); - const r = await testContract.exp.callAsync(x); + const r = await testContract.exp(x).callAsync(); assertFixedEquals(r, 0); }); it('exp(x < 0), where x is close to 0', async () => { const x = new BigNumber('-1e-18'); - const r = await testContract.exp.callAsync(toFixed(x)); + const r = await testContract.exp(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION); }); it('exp(x), where x is close to EXP_MIN_VAL', async () => { const x = MIN_EXP_NUMBER.plus('1e-18'); - const r = await testContract.exp.callAsync(toFixed(x)); + const r = await testContract.exp(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION); }); it('exp(x = -0.85)', async () => { const x = -0.85; - const r = await testContract.exp.callAsync(toFixed(x)); + const r = await testContract.exp(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION); }); @@ -944,7 +944,7 @@ blockchainTests('LibFixedMath unit tests', env => { const inputs = _.times(FUZZ_COUNT, () => getRandomDecimal(MIN_EXP_NUMBER, MAX_EXP_NUMBER)); for (const x of inputs) { it(`exp(${x.toString(10)})`, async () => { - const r = await testContract.exp.callAsync(toFixed(x)); + const r = await testContract.exp(toFixed(x)).callAsync(); assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION); }); } diff --git a/contracts/staking/test/unit_tests/lib_safe_downcast_test.ts b/contracts/staking/test/unit_tests/lib_safe_downcast_test.ts index 4cc19e4d38..c04f1fe2e6 100644 --- a/contracts/staking/test/unit_tests/lib_safe_downcast_test.ts +++ b/contracts/staking/test/unit_tests/lib_safe_downcast_test.ts @@ -22,7 +22,7 @@ blockchainTests('LibSafeDowncast unit tests', env => { describe('downcastToUint96', () => { async function verifyCorrectDowncastAsync(n: Numberish): Promise { - const actual = await testContract.downcastToUint96.callAsync(new BigNumber(n)); + const actual = await testContract.downcastToUint96(new BigNumber(n)).callAsync(); expect(actual).to.bignumber.eq(n); } function toDowncastError(n: Numberish): SafeMathRevertErrors.Uint256DowncastError { @@ -53,7 +53,7 @@ blockchainTests('LibSafeDowncast unit tests', env => { describe('downcastToUint64', () => { async function verifyCorrectDowncastAsync(n: Numberish): Promise { - const actual = await testContract.downcastToUint64.callAsync(new BigNumber(n)); + const actual = await testContract.downcastToUint64(new BigNumber(n)).callAsync(); expect(actual).to.bignumber.eq(n); } function toDowncastError(n: Numberish): SafeMathRevertErrors.Uint256DowncastError { diff --git a/contracts/staking/test/unit_tests/mixin_cumulative_rewards_test.ts b/contracts/staking/test/unit_tests/mixin_cumulative_rewards_test.ts index 8b9a4e161e..51e18c00b2 100644 --- a/contracts/staking/test/unit_tests/mixin_cumulative_rewards_test.ts +++ b/contracts/staking/test/unit_tests/mixin_cumulative_rewards_test.ts @@ -41,89 +41,79 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => { // Create a test pool const operatorShare = new BigNumber(1); const addOperatorAsMaker = true; - const txReceipt = await testContract.createStakingPool.awaitTransactionSuccessAsync( - operatorShare, - addOperatorAsMaker, - ); + const txReceipt = await testContract + .createStakingPool(operatorShare, addOperatorAsMaker) + .awaitTransactionSuccessAsync(); const createStakingPoolLog = txReceipt.logs[0]; testPoolId = (createStakingPoolLog as any).args.poolId; }); describe('_isCumulativeRewardSet', () => { it('Should return true iff denominator is non-zero', async () => { - const isSet = await testContract.isCumulativeRewardSet.callAsync({ - numerator: ZERO, - denominator: new BigNumber(1), - }); + const isSet = await testContract + .isCumulativeRewardSet({ + numerator: ZERO, + denominator: new BigNumber(1), + }) + .callAsync(); expect(isSet).to.be.true(); }); it('Should return false iff denominator is zero', async () => { - const isSet = await testContract.isCumulativeRewardSet.callAsync({ - numerator: new BigNumber(1), - denominator: ZERO, - }); + const isSet = await testContract + .isCumulativeRewardSet({ + numerator: new BigNumber(1), + denominator: ZERO, + }) + .callAsync(); expect(isSet).to.be.false(); }); }); describe('_addCumulativeReward', () => { it('Should set value to `reward/stake` if this is the first cumulative reward', async () => { - await testContract.addCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[0].numerator, - testRewards[0].denominator, - ); - const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId); + await testContract + .addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator) + .awaitTransactionSuccessAsync(); + const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync(); expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]); }); it('Should do nothing if a cumulative reward has already been recorded in the current epoch (`lastStoredEpoch == currentEpoch_`)', async () => { - await testContract.addCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[0].numerator, - testRewards[0].denominator, - ); + await testContract + .addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator) + .awaitTransactionSuccessAsync(); // this call should not overwrite existing value (testRewards[0]) - await testContract.addCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[1].numerator, - testRewards[1].denominator, - ); - const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId); + await testContract + .addCumulativeReward(testPoolId, testRewards[1].numerator, testRewards[1].denominator) + .awaitTransactionSuccessAsync(); + const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync(); expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]); }); it('Should set value to normalized sum of `reward/stake` plus most recent cumulative reward, given one exists', async () => { - await testContract.addCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[0].numerator, - testRewards[0].denominator, - ); - await testContract.incrementEpoch.awaitTransactionSuccessAsync(); - await testContract.addCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[1].numerator, - testRewards[1].denominator, - ); - const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId); + await testContract + .addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator) + .awaitTransactionSuccessAsync(); + await testContract.incrementEpoch().awaitTransactionSuccessAsync(); + await testContract + .addCumulativeReward(testPoolId, testRewards[1].numerator, testRewards[1].denominator) + .awaitTransactionSuccessAsync(); + const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync(); expect(mostRecentCumulativeReward).to.deep.equal(sumOfTestRewardsNormalized); }); }); describe('_updateCumulativeReward', () => { it('Should set current cumulative reward to most recent cumulative reward', async () => { - await testContract.addCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[0].numerator, - testRewards[0].denominator, - ); - await testContract.incrementEpoch.awaitTransactionSuccessAsync(); - await testContract.updateCumulativeReward.awaitTransactionSuccessAsync(testPoolId); + await testContract + .addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator) + .awaitTransactionSuccessAsync(); + await testContract.incrementEpoch().awaitTransactionSuccessAsync(); + await testContract.updateCumulativeReward(testPoolId).awaitTransactionSuccessAsync(); const epoch = new BigNumber(2); - const mostRecentCumulativeReward = await testContract.getCumulativeRewardAtEpochRaw.callAsync( - testPoolId, - epoch, - ); + const mostRecentCumulativeReward = await testContract + .getCumulativeRewardAtEpochRaw(testPoolId, epoch) + .callAsync(); expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]); }); }); @@ -137,22 +127,15 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => { epochOfIntervalEnd: BigNumber, ): Promise => { // Simulate earning reward - await testContract.storeCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - testRewards[0], - epochOfFirstReward, - ); - await testContract.storeCumulativeReward.awaitTransactionSuccessAsync( - testPoolId, - sumOfTestRewardsNormalized, - epochOfSecondReward, - ); - const reward = await testContract.computeMemberRewardOverInterval.callAsync( - testPoolId, - amountToStake, - epochOfIntervalStart, - epochOfIntervalEnd, - ); + await testContract + .storeCumulativeReward(testPoolId, testRewards[0], epochOfFirstReward) + .awaitTransactionSuccessAsync(); + await testContract + .storeCumulativeReward(testPoolId, sumOfTestRewardsNormalized, epochOfSecondReward) + .awaitTransactionSuccessAsync(); + const reward = await testContract + .computeMemberRewardOverInterval(testPoolId, amountToStake, epochOfIntervalStart, epochOfIntervalEnd) + .callAsync(); // Compute expected reward const lhs = sumOfTestRewardsNormalized.numerator.dividedBy(sumOfTestRewardsNormalized.denominator); const rhs = testRewards[0].numerator.dividedBy(testRewards[0].denominator); @@ -213,12 +196,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => { const stake = toBaseUnitAmount(1); const beginEpoch = new BigNumber(1); const endEpoch = new BigNumber(2); - const reward = await testContract.computeMemberRewardOverInterval.callAsync( - testPoolId, - stake, - beginEpoch, - endEpoch, - ); + const reward = await testContract + .computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch) + .callAsync(); expect(reward).to.bignumber.equal(ZERO); }); @@ -226,12 +206,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => { const stake = toBaseUnitAmount(0); const beginEpoch = new BigNumber(1); const endEpoch = new BigNumber(2); - const reward = await testContract.computeMemberRewardOverInterval.callAsync( - testPoolId, - stake, - beginEpoch, - endEpoch, - ); + const reward = await testContract + .computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch) + .callAsync(); expect(reward).to.bignumber.equal(ZERO); }); @@ -239,12 +216,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => { const stake = toBaseUnitAmount(1); const beginEpoch = new BigNumber(1); const endEpoch = new BigNumber(1); - const reward = await testContract.computeMemberRewardOverInterval.callAsync( - testPoolId, - stake, - beginEpoch, - endEpoch, - ); + const reward = await testContract + .computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch) + .callAsync(); expect(reward).to.bignumber.equal(ZERO); }); @@ -252,7 +226,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => { const stake = toBaseUnitAmount(1); const beginEpoch = new BigNumber(2); const endEpoch = new BigNumber(1); - const tx = testContract.computeMemberRewardOverInterval.callAsync(testPoolId, stake, beginEpoch, endEpoch); + const tx = testContract + .computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch) + .callAsync(); return expect(tx).to.revertWith('CR_INTERVAL_INVALID'); }); }); diff --git a/contracts/staking/test/unit_tests/mixin_scheduler_test.ts b/contracts/staking/test/unit_tests/mixin_scheduler_test.ts index d13a8f4d29..7c032727b8 100644 --- a/contracts/staking/test/unit_tests/mixin_scheduler_test.ts +++ b/contracts/staking/test/unit_tests/mixin_scheduler_test.ts @@ -29,10 +29,12 @@ blockchainTests.resets('MixinScheduler unit tests', env => { describe('getCurrentEpochEarliestEndTimeInSeconds', () => { it('Should return the sum of `epoch start time + epoch duration`', async () => { - const testDeployedTimestamp = await testContract.testDeployedTimestamp.callAsync(); - const epochDurationInSeconds = await testContract.epochDurationInSeconds.callAsync(); + const testDeployedTimestamp = await testContract.testDeployedTimestamp().callAsync(); + const epochDurationInSeconds = await testContract.epochDurationInSeconds().callAsync(); const expectedCurrentEpochEarliestEndTimeInSeconds = testDeployedTimestamp.plus(epochDurationInSeconds); - const currentEpochEarliestEndTimeInSeconds = await testContract.getCurrentEpochEarliestEndTimeInSeconds.callAsync(); + const currentEpochEarliestEndTimeInSeconds = await testContract + .getCurrentEpochEarliestEndTimeInSeconds() + .callAsync(); expect(currentEpochEarliestEndTimeInSeconds).to.bignumber.equal( expectedCurrentEpochEarliestEndTimeInSeconds, ); @@ -42,23 +44,23 @@ blockchainTests.resets('MixinScheduler unit tests', env => { describe('_initMixinScheduler', () => { it('Should succeed if scheduler is not yet initialized (`currentEpochStartTimeInSeconds == 0`)', async () => { const initCurrentEpochStartTimeInSeconds = constants.ZERO_AMOUNT; - const txReceipt = await testContract.initMixinSchedulerTest.awaitTransactionSuccessAsync( - initCurrentEpochStartTimeInSeconds, - ); + const txReceipt = await testContract + .initMixinSchedulerTest(initCurrentEpochStartTimeInSeconds) + .awaitTransactionSuccessAsync(); // Assert `currentEpochStartTimeInSeconds` was properly initialized const blockTimestamp = await env.web3Wrapper.getBlockTimestampAsync(txReceipt.blockNumber); - const currentEpochStartTimeInSeconds = await testContract.currentEpochStartTimeInSeconds.callAsync(); + const currentEpochStartTimeInSeconds = await testContract.currentEpochStartTimeInSeconds().callAsync(); expect(currentEpochStartTimeInSeconds).to.bignumber.equal(blockTimestamp); // Assert `currentEpoch` was properly initialized - const currentEpoch = await testContract.currentEpoch.callAsync(); + const currentEpoch = await testContract.currentEpoch().callAsync(); expect(currentEpoch).to.bignumber.equal(1); }); it('Should revert if scheduler is already initialized (`currentEpochStartTimeInSeconds != 0`)', async () => { const initCurrentEpochStartTimeInSeconds = new BigNumber(10); - const tx = testContract.initMixinSchedulerTest.awaitTransactionSuccessAsync( - initCurrentEpochStartTimeInSeconds, - ); + const tx = testContract + .initMixinSchedulerTest(initCurrentEpochStartTimeInSeconds) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith( new StakingRevertErrors.InitializationError( StakingRevertErrors.InitializationErrorCodes.MixinSchedulerAlreadyInitialized, @@ -70,9 +72,9 @@ blockchainTests.resets('MixinScheduler unit tests', env => { describe('_goToNextEpoch', () => { it('Should succeed if epoch end time is strictly less than to block timestamp', async () => { const epochEndTimeDelta = new BigNumber(-10); - const txReceipt = await testContract.goToNextEpochTest.awaitTransactionSuccessAsync(epochEndTimeDelta); - const currentEpoch = await testContract.currentEpoch.callAsync(); - const currentEpochStartTimeInSeconds = await testContract.currentEpochStartTimeInSeconds.callAsync(); + const txReceipt = await testContract.goToNextEpochTest(epochEndTimeDelta).awaitTransactionSuccessAsync(); + const currentEpoch = await testContract.currentEpoch().callAsync(); + const currentEpochStartTimeInSeconds = await testContract.currentEpochStartTimeInSeconds().callAsync(); verifyEventsFromLogs( txReceipt.logs, [ @@ -87,20 +89,20 @@ blockchainTests.resets('MixinScheduler unit tests', env => { it('Should succeed if epoch end time is equal to block timestamp', async () => { const epochEndTimeDelta = constants.ZERO_AMOUNT; - const txReceipt = await testContract.goToNextEpochTest.awaitTransactionSuccessAsync(epochEndTimeDelta); + const txReceipt = await testContract.goToNextEpochTest(epochEndTimeDelta).awaitTransactionSuccessAsync(); // tslint:disable-next-line no-unnecessary-type-assertion const testLog: TestMixinSchedulerGoToNextEpochTestInfoEventArgs = (txReceipt.logs[0] as LogWithDecodedArgs< TestMixinSchedulerGoToNextEpochTestInfoEventArgs >).args; - const currentEpoch = await testContract.currentEpoch.callAsync(); - const currentEpochStartTimeInSeconds = await testContract.currentEpochStartTimeInSeconds.callAsync(); + const currentEpoch = await testContract.currentEpoch().callAsync(); + const currentEpochStartTimeInSeconds = await testContract.currentEpochStartTimeInSeconds().callAsync(); expect(currentEpoch).to.bignumber.equal(testLog.oldEpoch.plus(1)); expect(currentEpochStartTimeInSeconds).to.bignumber.equal(testLog.blockTimestamp); }); it('Should revert if epoch end time is strictly greater than block timestamp', async () => { const epochEndTimeDelta = new BigNumber(10); - const tx = testContract.goToNextEpochTest.awaitTransactionSuccessAsync(epochEndTimeDelta); + const tx = testContract.goToNextEpochTest(epochEndTimeDelta).awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(new StakingRevertErrors.BlockTimestampTooLowError()); }); }); diff --git a/contracts/staking/test/unit_tests/mixin_stake_storage_test.ts b/contracts/staking/test/unit_tests/mixin_stake_storage_test.ts index c3da4d3487..6167f75324 100644 --- a/contracts/staking/test/unit_tests/mixin_stake_storage_test.ts +++ b/contracts/staking/test/unit_tests/mixin_stake_storage_test.ts @@ -25,7 +25,7 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { env.txDefaults, artifacts, ); - await testContract.setCurrentEpoch.awaitTransactionSuccessAsync(CURRENT_EPOCH); + await testContract.setCurrentEpoch(CURRENT_EPOCH).awaitTransactionSuccessAsync(); defaultUninitializedBalance = { currentEpoch: constants.INITIAL_EPOCH, currentEpochBalance: new BigNumber(0), @@ -49,7 +49,7 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { storedBalance.currentEpoch, storedBalance.currentEpochBalance, storedBalance.nextEpochBalance, - ] = await testContract.testBalances.callAsync(new BigNumber(index)); + ] = await testContract.testBalances(new BigNumber(index)).callAsync(); return storedBalance as StoredBalance; } @@ -59,9 +59,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { toBalance: StoredBalance, amount: BigNumber, ): Promise { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(fromBalance, INDEX_ZERO); - await testContract.setStoredBalance.awaitTransactionSuccessAsync(toBalance, INDEX_ONE); - await testContract.moveStake.awaitTransactionSuccessAsync(INDEX_ZERO, INDEX_ONE, amount); + await testContract.setStoredBalance(fromBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); + await testContract.setStoredBalance(toBalance, INDEX_ONE).awaitTransactionSuccessAsync(); + await testContract.moveStake(INDEX_ZERO, INDEX_ONE, amount).awaitTransactionSuccessAsync(); const actualBalances = await Promise.all([ getTestBalancesAsync(INDEX_ZERO), @@ -101,20 +101,18 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { ); }); it('Noop if pointers are equal', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); // If the pointers weren't equal, this would revert with InsufficientBalanceError - await testContract.moveStake.awaitTransactionSuccessAsync( - INDEX_ZERO, - INDEX_ZERO, - defaultSyncedBalance.nextEpochBalance.plus(1), - ); + await testContract + .moveStake(INDEX_ZERO, INDEX_ZERO, defaultSyncedBalance.nextEpochBalance.plus(1)) + .awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal(defaultSyncedBalance); }); it("Reverts if attempting to move more than next epoch's balance", async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultSyncedBalance.nextEpochBalance.plus(1); - const tx = testContract.moveStake.awaitTransactionSuccessAsync(INDEX_ZERO, INDEX_ONE, amount); + const tx = testContract.moveStake(INDEX_ZERO, INDEX_ONE, amount).awaitTransactionSuccessAsync(); await expect(tx).to.revertWith( new StakingRevertErrors.InsufficientBalanceError(amount, defaultSyncedBalance.nextEpochBalance), ); @@ -123,32 +121,32 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { describe('Load balance', () => { it('Balance does not change state if balance was previously synced in the current epoch', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO); - const actualBalance = await testContract.loadCurrentBalance.callAsync(INDEX_ZERO); + await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); + const actualBalance = await testContract.loadCurrentBalance(INDEX_ZERO).callAsync(); expect(actualBalance).to.deep.equal(defaultSyncedBalance); }); it('Balance updates current epoch fields if the balance has not yet been synced in the current epoch', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO); - const actualBalance = await testContract.loadCurrentBalance.callAsync(INDEX_ZERO); + await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); + const actualBalance = await testContract.loadCurrentBalance(INDEX_ZERO).callAsync(); expect(actualBalance).to.deep.equal(defaultSyncedBalance); }); it('Balance loads unsynced balance from storage without changing fields', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO); - const actualBalance = await testContract.loadStaleBalance.callAsync(INDEX_ZERO); + await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); + const actualBalance = await testContract.loadStaleBalance(INDEX_ZERO).callAsync(); expect(actualBalance).to.deep.equal(defaultUnsyncedBalance); }); it('Balance loads synced balance from storage without changing fields', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO); - const actualBalance = await testContract.loadStaleBalance.callAsync(INDEX_ZERO); + await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); + const actualBalance = await testContract.loadStaleBalance(INDEX_ZERO).callAsync(); expect(actualBalance).to.deep.equal(defaultSyncedBalance); }); }); describe('Increase/decrease balance', () => { it('_increaseCurrentAndNextBalance', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2); - await testContract.increaseCurrentAndNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount); + await testContract.increaseCurrentAndNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal({ ...defaultSyncedBalance, @@ -157,16 +155,16 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { }); }); it('_increaseCurrentAndNextBalance (previously uninitialized)', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUninitializedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultUninitializedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultSyncedBalance.currentEpochBalance; - await testContract.increaseCurrentAndNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount); + await testContract.increaseCurrentAndNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal(defaultSyncedBalance); }); it('_decreaseCurrentAndNextBalance', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2); - await testContract.decreaseCurrentAndNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount); + await testContract.decreaseCurrentAndNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal({ ...defaultSyncedBalance, @@ -175,9 +173,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { }); }); it('_increaseNextBalance', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2); - await testContract.increaseNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount); + await testContract.increaseNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal({ ...defaultSyncedBalance, @@ -185,9 +183,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { }); }); it('_increaseCurrentAndNextBalance (previously uninitialized)', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUninitializedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultUninitializedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultSyncedBalance.currentEpochBalance; - await testContract.increaseNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount); + await testContract.increaseNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal({ ...defaultSyncedBalance, @@ -195,9 +193,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => { }); }); it('_decreaseNextBalance', async () => { - await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO); + await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync(); const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2); - await testContract.decreaseNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount); + await testContract.decreaseNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync(); const actualBalance = await getTestBalancesAsync(INDEX_ZERO); expect(actualBalance).to.deep.equal({ ...defaultSyncedBalance, diff --git a/contracts/staking/test/unit_tests/mixin_staking_pool_rewards.ts b/contracts/staking/test/unit_tests/mixin_staking_pool_rewards.ts index a125b9d90b..f0a284e459 100644 --- a/contracts/staking/test/unit_tests/mixin_staking_pool_rewards.ts +++ b/contracts/staking/test/unit_tests/mixin_staking_pool_rewards.ts @@ -8,7 +8,6 @@ import { hexRandom, Numberish, randomAddress, - TransactionHelper, verifyEventsFromLogs, } from '@0x/contracts-test-utils'; import { BigNumber } from '@0x/utils'; @@ -21,7 +20,6 @@ import { TestMixinStakingPoolRewardsContract, TestMixinStakingPoolRewardsEvents blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { let testContract: TestMixinStakingPoolRewardsContract; - let txHelper: TransactionHelper; const POOL_ID = hexRandom(); const OPERATOR = randomAddress(); @@ -35,12 +33,13 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { env.txDefaults, artifacts, ); - await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, { - operator: OPERATOR, - operatorShare: OPERATOR_SHARE, - }); + await testContract + .setPool(POOL_ID, { + operator: OPERATOR, + operatorShare: OPERATOR_SHARE, + }) + .awaitTransactionSuccessAsync(); [caller] = await env.getAccountAddressesAsync(); - txHelper = new TransactionHelper(env.web3Wrapper, artifacts); }); async function setUnfinalizedPoolRewardsAsync( @@ -48,11 +47,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { reward: Numberish, membersStake: Numberish, ): Promise { - await testContract.setUnfinalizedPoolRewards.awaitTransactionSuccessAsync( - poolId, - new BigNumber(reward), - new BigNumber(membersStake), - ); + await testContract + .setUnfinalizedPoolRewards(poolId, new BigNumber(reward), new BigNumber(membersStake)) + .awaitTransactionSuccessAsync(); } // Set the delegated stake of a delegator in a pool. @@ -68,11 +65,13 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { nextEpochBalance: getRandomInteger(1, 1e18), ...stake, }; - await testContract.setDelegatedStakeToPoolByOwner.awaitTransactionSuccessAsync(delegator, poolId, { - currentEpoch: _stake.currentEpoch, - currentEpochBalance: _stake.currentEpochBalance, - nextEpochBalance: _stake.nextEpochBalance, - }); + await testContract + .setDelegatedStakeToPoolByOwner(delegator, poolId, { + currentEpoch: _stake.currentEpoch, + currentEpochBalance: _stake.currentEpochBalance, + nextEpochBalance: _stake.nextEpochBalance, + }) + .awaitTransactionSuccessAsync(); return _stake; } @@ -83,25 +82,29 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { delegator: string, finalizedReward?: Numberish, ): Promise { - const stake = await testContract.delegatedStakeToPoolByOwner.callAsync(delegator, poolId); + const stake = await testContract.delegatedStakeToPoolByOwner(delegator, poolId).callAsync(); // Split the rewards up across the two calls to `_computeMemberRewardOverInterval()` const reward = finalizedReward === undefined ? getRandomInteger(1, 1e18) : new BigNumber(finalizedReward); const oldRewards = getRandomPortion(reward); - await testContract.setMemberRewardsOverInterval.awaitTransactionSuccessAsync( - poolId, - stake.currentEpochBalance, - stake.currentEpoch, - stake.currentEpoch.plus(1), - oldRewards, - ); + await testContract + .setMemberRewardsOverInterval( + poolId, + stake.currentEpochBalance, + stake.currentEpoch, + stake.currentEpoch.plus(1), + oldRewards, + ) + .awaitTransactionSuccessAsync(); const newRewards = reward.minus(oldRewards); - await testContract.setMemberRewardsOverInterval.awaitTransactionSuccessAsync( - poolId, - stake.nextEpochBalance, - stake.currentEpoch.plus(1), - await testContract.currentEpoch.callAsync(), - newRewards, - ); + await testContract + .setMemberRewardsOverInterval( + poolId, + stake.nextEpochBalance, + stake.currentEpoch.plus(1), + await testContract.currentEpoch().callAsync(), + newRewards, + ) + .awaitTransactionSuccessAsync(); return reward; } @@ -119,7 +122,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { describe('withdrawDelegatorRewards()', () => { it('calls `_withdrawAndSyncDelegatorRewards()` with the sender as the member', async () => { - const { logs } = await testContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync(POOL_ID); + const { logs } = await testContract.withdrawDelegatorRewards(POOL_ID).awaitTransactionSuccessAsync(); verifyEventsFromLogs( logs, [{ poolId: POOL_ID, delegator: caller }], @@ -136,14 +139,14 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { before(async () => { stake = await setStakeAsync(POOL_ID, DELEGATOR); - await testContract.setPoolRewards.awaitTransactionSuccessAsync(POOL_ID, POOL_REWARD); - await testContract.setWethReservedForPoolRewards.awaitTransactionSuccessAsync( - WETH_RESERVED_FOR_POOL_REWARDS, - ); + await testContract.setPoolRewards(POOL_ID, POOL_REWARD).awaitTransactionSuccessAsync(); + await testContract + .setWethReservedForPoolRewards(WETH_RESERVED_FOR_POOL_REWARDS) + .awaitTransactionSuccessAsync(); }); async function withdrawAndSyncDelegatorRewardsAsync(): Promise { - return testContract.withdrawAndSyncDelegatorRewards.awaitTransactionSuccessAsync(POOL_ID, DELEGATOR); + return testContract.withdrawAndSyncDelegatorRewards(POOL_ID, DELEGATOR).awaitTransactionSuccessAsync(); } it('reverts if the pool is not finalized', async () => { @@ -169,20 +172,20 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const finalizedReward = getRandomPortion(POOL_REWARD); await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, finalizedReward); await withdrawAndSyncDelegatorRewardsAsync(); - const poolReward = await testContract.rewardsByPoolId.callAsync(POOL_ID); + const poolReward = await testContract.rewardsByPoolId(POOL_ID).callAsync(); expect(poolReward).to.bignumber.eq(POOL_REWARD.minus(finalizedReward)); }); it('reduces `wethReservedForPoolRewards` for the pool', async () => { const finalizedReward = getRandomPortion(POOL_REWARD); await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, finalizedReward); await withdrawAndSyncDelegatorRewardsAsync(); - const wethReserved = await testContract.wethReservedForPoolRewards.callAsync(); + const wethReserved = await testContract.wethReservedForPoolRewards().callAsync(); expect(wethReserved).to.bignumber.eq(WETH_RESERVED_FOR_POOL_REWARDS.minus(finalizedReward)); }); it('syncs `_delegatedStakeToPoolByOwner`', async () => { await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, getRandomPortion(POOL_REWARD)); await withdrawAndSyncDelegatorRewardsAsync(); - const stakeAfter = await testContract.delegatedStakeToPoolByOwner.callAsync(DELEGATOR, POOL_ID); + const stakeAfter = await testContract.delegatedStakeToPoolByOwner(DELEGATOR, POOL_ID).callAsync(); // `_loadCurrentBalance` is overridden to just increment `currentEpoch`. expect(stakeAfter).to.deep.eq({ currentEpoch: stake.currentEpoch.plus(1), @@ -198,7 +201,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { it('no rewards if the delegated stake epoch == current epoch', async () => { // Set some finalized rewards that should be ignored. await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, getRandomInteger(1, POOL_REWARD)); - await testContract.setCurrentEpoch.awaitTransactionSuccessAsync(stake.currentEpoch); + await testContract.setCurrentEpoch(stake.currentEpoch).awaitTransactionSuccessAsync(); const { logs } = await withdrawAndSyncDelegatorRewardsAsync(); // There will be no Transfer events if computed rewards are zero. verifyEventsFromLogs(logs, [], Events.Transfer); @@ -207,7 +210,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { describe('computeRewardBalanceOfOperator()', () => { async function computeRewardBalanceOfOperatorAsync(): Promise { - return testContract.computeRewardBalanceOfOperator.callAsync(POOL_ID); + return testContract.computeRewardBalanceOfOperator(POOL_ID).callAsync(); } it('returns only unfinalized rewards', async () => { @@ -239,19 +242,23 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { expect(reward).to.bignumber.eq(unfinalizedReward); }); it('returns no reward if operator share is zero', async () => { - await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, { - operator: OPERATOR, - operatorShare: constants.ZERO_AMOUNT, - }); + await testContract + .setPool(POOL_ID, { + operator: OPERATOR, + operatorShare: constants.ZERO_AMOUNT, + }) + .awaitTransactionSuccessAsync(); await setUnfinalizedPoolRewardsAsync(POOL_ID, getRandomInteger(1, 1e18), getRandomInteger(1, 1e18)); const reward = await computeRewardBalanceOfOperatorAsync(); expect(reward).to.bignumber.eq(0); }); it('returns all unfinalized reward if operator share is 100%', async () => { - await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, { - operator: OPERATOR, - operatorShare: constants.PPM_100_PERCENT, - }); + await testContract + .setPool(POOL_ID, { + operator: OPERATOR, + operatorShare: constants.PPM_100_PERCENT, + }) + .awaitTransactionSuccessAsync(); const unfinalizedReward = getRandomInteger(1, 1e18); await setUnfinalizedPoolRewardsAsync(POOL_ID, unfinalizedReward, getRandomInteger(1, 1e18)); const reward = await computeRewardBalanceOfOperatorAsync(); @@ -265,12 +272,12 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { let stake: StoredBalance; before(async () => { - currentEpoch = await testContract.currentEpoch.callAsync(); + currentEpoch = await testContract.currentEpoch().callAsync(); stake = await setStakeAsync(POOL_ID, DELEGATOR); }); async function computeRewardBalanceOfDelegatorAsync(): Promise { - return testContract.computeRewardBalanceOfDelegator.callAsync(POOL_ID, DELEGATOR); + return testContract.computeRewardBalanceOfDelegator(POOL_ID, DELEGATOR).callAsync(); } function getDelegatorPortionOfUnfinalizedReward( @@ -316,7 +323,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { currentEpoch: new BigNumber(epoch - 2), nextEpochBalance: constants.ZERO_AMOUNT, }); - await testContract.setCurrentEpoch.awaitTransactionSuccessAsync(new BigNumber(epoch)); + await testContract.setCurrentEpoch(new BigNumber(epoch)).awaitTransactionSuccessAsync(); await setUnfinalizedPoolRewardsAsync(POOL_ID, getRandomInteger(1, 1e18), getRandomInteger(1, 1e18)); const reward = await computeRewardBalanceOfDelegatorAsync(); expect(reward).to.bignumber.eq(0); @@ -348,23 +355,24 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const WETH_RESERVED_FOR_POOL_REWARDS = POOL_REWARD.plus(getRandomInteger(1, 100e18)); before(async () => { - await testContract.setPoolRewards.awaitTransactionSuccessAsync(POOL_ID, POOL_REWARD); - await testContract.setWethReservedForPoolRewards.awaitTransactionSuccessAsync( - WETH_RESERVED_FOR_POOL_REWARDS, - ); + await testContract.setPoolRewards(POOL_ID, POOL_REWARD).awaitTransactionSuccessAsync(); + await testContract + .setWethReservedForPoolRewards(WETH_RESERVED_FOR_POOL_REWARDS) + .awaitTransactionSuccessAsync(); }); async function syncPoolRewardsAsync( reward: Numberish, membersStake: Numberish, ): Promise<[[BigNumber, BigNumber], LogEntry[]]> { - const [result, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.syncPoolRewards, + const contractFn = testContract.syncPoolRewards( POOL_ID, new BigNumber(reward), new BigNumber(membersStake), ); - return [result, receipt.logs]; + const result = await contractFn.callAsync(); + const { logs } = await contractFn.awaitTransactionSuccessAsync(); + return [result, logs]; } it("transfers operator's portion of the reward to the operator", async () => { @@ -383,7 +391,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const membersStake = getRandomInteger(1, 1e18); await syncPoolRewardsAsync(totalReward, membersStake); const expectedMembersReward = toMembersPortion(OPERATOR_SHARE, totalReward); - const poolReward = await testContract.rewardsByPoolId.callAsync(POOL_ID); + const poolReward = await testContract.rewardsByPoolId(POOL_ID).callAsync(); expect(poolReward).to.bignumber.eq(POOL_REWARD.plus(expectedMembersReward)); }); it("increases `wethReservedForPoolRewards` with members' portion of rewards", async () => { @@ -391,7 +399,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const membersStake = getRandomInteger(1, 1e18); await syncPoolRewardsAsync(totalReward, membersStake); const expectedMembersReward = toMembersPortion(OPERATOR_SHARE, totalReward); - const wethReserved = await testContract.wethReservedForPoolRewards.callAsync(); + const wethReserved = await testContract.wethReservedForPoolRewards().callAsync(); expect(wethReserved).to.bignumber.eq(WETH_RESERVED_FOR_POOL_REWARDS.plus(expectedMembersReward)); }); it("returns operator and members' portion of the reward", async () => { @@ -416,10 +424,12 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { }); it("gives all rewards to members if operator's share is zero", async () => { const totalReward = getRandomInteger(1, 1e18); - await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, { - operator: OPERATOR, - operatorShare: constants.ZERO_AMOUNT, - }); + await testContract + .setPool(POOL_ID, { + operator: OPERATOR, + operatorShare: constants.ZERO_AMOUNT, + }) + .awaitTransactionSuccessAsync(); const [[operatorReward, membersReward], logs] = await syncPoolRewardsAsync( totalReward, getRandomInteger(1, 1e18), @@ -436,11 +446,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const operatorShare = getRandomPortion(constants.PPM_100_PERCENT); const totalReward = getRandomInteger(1, 1e18); const membersStake = constants.ZERO_AMOUNT; - const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync( - operatorShare, - totalReward, - membersStake, - ); + const [operatorReward, membersReward] = await testContract + .computePoolRewardsSplit(operatorShare, totalReward, membersStake) + .callAsync(); expect(operatorReward).to.bignumber.eq(totalReward); expect(membersReward).to.bignumber.eq(0); }); @@ -448,11 +456,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const operatorShare = constants.ZERO_AMOUNT; const totalReward = getRandomInteger(1, 1e18); const membersStake = constants.ZERO_AMOUNT; - const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync( - operatorShare, - totalReward, - membersStake, - ); + const [operatorReward, membersReward] = await testContract + .computePoolRewardsSplit(operatorShare, totalReward, membersStake) + .callAsync(); expect(operatorReward).to.bignumber.eq(totalReward); expect(membersReward).to.bignumber.eq(0); }); @@ -460,11 +466,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const operatorShare = constants.PPM_100_PERCENT; const totalReward = getRandomInteger(1, 1e18); const membersStake = getRandomInteger(1, 1e18); - const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync( - operatorShare, - totalReward, - membersStake, - ); + const [operatorReward, membersReward] = await testContract + .computePoolRewardsSplit(operatorShare, totalReward, membersStake) + .callAsync(); expect(operatorReward).to.bignumber.eq(totalReward); expect(membersReward).to.bignumber.eq(0); }); @@ -472,11 +476,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const operatorShare = constants.ZERO_AMOUNT; const totalReward = getRandomInteger(1, 1e18); const membersStake = getRandomInteger(1, 1e18); - const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync( - operatorShare, - totalReward, - membersStake, - ); + const [operatorReward, membersReward] = await testContract + .computePoolRewardsSplit(operatorShare, totalReward, membersStake) + .callAsync(); expect(operatorReward).to.bignumber.eq(0); expect(membersReward).to.bignumber.eq(totalReward); }); @@ -484,11 +486,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { const operatorShare = getRandomPortion(constants.PPM_100_PERCENT); const totalReward = getRandomInteger(1, 1e18); const membersStake = getRandomInteger(1, 1e18); - const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync( - operatorShare, - totalReward, - membersStake, - ); + const [operatorReward, membersReward] = await testContract + .computePoolRewardsSplit(operatorShare, totalReward, membersStake) + .callAsync(); expect(operatorReward).to.bignumber.eq(toOperatorPortion(operatorShare, totalReward)); expect(membersReward).to.bignumber.eq(toMembersPortion(operatorShare, totalReward)); }); diff --git a/contracts/staking/test/unit_tests/params_test.ts b/contracts/staking/test/unit_tests/params_test.ts index 146a267905..ce518e98de 100644 --- a/contracts/staking/test/unit_tests/params_test.ts +++ b/contracts/staking/test/unit_tests/params_test.ts @@ -22,7 +22,7 @@ blockchainTests('Configurable Parameters unit tests', env => { env.txDefaults, artifacts, ); - await testContract.addAuthorizedAddress.awaitTransactionSuccessAsync(authorizedAddress); + await testContract.addAuthorizedAddress(authorizedAddress).awaitTransactionSuccessAsync(); }); blockchainTests.resets('setParams()', () => { @@ -34,14 +34,15 @@ blockchainTests('Configurable Parameters unit tests', env => { ...stakingConstants.DEFAULT_PARAMS, ...params, }; - const receipt = await testContract.setParams.awaitTransactionSuccessAsync( - new BigNumber(_params.epochDurationInSeconds), - new BigNumber(_params.rewardDelegatedStakeWeight), - new BigNumber(_params.minimumPoolStake), - new BigNumber(_params.cobbDouglasAlphaNumerator), - new BigNumber(_params.cobbDouglasAlphaDenominator), - { from }, - ); + const receipt = await testContract + .setParams( + new BigNumber(_params.epochDurationInSeconds), + new BigNumber(_params.rewardDelegatedStakeWeight), + new BigNumber(_params.minimumPoolStake), + new BigNumber(_params.cobbDouglasAlphaNumerator), + new BigNumber(_params.cobbDouglasAlphaDenominator), + ) + .awaitTransactionSuccessAsync({ from }); // Assert event. const events = filterLogsToArguments(receipt.logs, 'ParamsSet'); expect(events.length).to.eq(1); @@ -52,7 +53,7 @@ blockchainTests('Configurable Parameters unit tests', env => { expect(event.cobbDouglasAlphaNumerator).to.bignumber.eq(_params.cobbDouglasAlphaNumerator); expect(event.cobbDouglasAlphaDenominator).to.bignumber.eq(_params.cobbDouglasAlphaDenominator); // Assert `getParams()`. - const actual = await testContract.getParams.callAsync(); + const actual = await testContract.getParams().callAsync(); expect(actual[0]).to.bignumber.eq(_params.epochDurationInSeconds); expect(actual[1]).to.bignumber.eq(_params.rewardDelegatedStakeWeight); expect(actual[2]).to.bignumber.eq(_params.minimumPoolStake); @@ -68,7 +69,7 @@ blockchainTests('Configurable Parameters unit tests', env => { }); it('throws if `assertValidStorageParams()` throws`', async () => { - await testContract.setShouldFailAssertValidStorageParams.awaitTransactionSuccessAsync(true); + await testContract.setShouldFailAssertValidStorageParams(true).awaitTransactionSuccessAsync(); const tx = setParamsAndAssertAsync({}); return expect(tx).to.revertWith('ASSERT_VALID_STORAGE_PARAMS_FAILED'); }); diff --git a/contracts/staking/test/unit_tests/protocol_fees_test.ts b/contracts/staking/test/unit_tests/protocol_fees_test.ts index fc082262ba..06a52f7d14 100644 --- a/contracts/staking/test/unit_tests/protocol_fees_test.ts +++ b/contracts/staking/test/unit_tests/protocol_fees_test.ts @@ -45,7 +45,7 @@ blockchainTests('Protocol Fees unit tests', env => { exchangeAddress, ); - minimumStake = (await testContract.getParams.callAsync())[2]; + minimumStake = (await testContract.getParams().callAsync())[2]; }); interface CreateTestPoolOpts { @@ -63,12 +63,14 @@ blockchainTests('Protocol Fees unit tests', env => { makers: _.times(2, () => randomAddress()), ...opts, }; - await testContract.createTestPool.awaitTransactionSuccessAsync( - _opts.poolId, - new BigNumber(_opts.operatorStake), - new BigNumber(_opts.membersStake), - _opts.makers, - ); + await testContract + .createTestPool( + _opts.poolId, + new BigNumber(_opts.operatorStake), + new BigNumber(_opts.membersStake), + _opts.makers, + ) + .awaitTransactionSuccessAsync(); return _opts; } @@ -80,23 +82,17 @@ blockchainTests('Protocol Fees unit tests', env => { describe('forbidden actions', () => { it('should revert if called by a non-exchange', async () => { - const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: notExchangeAddress }, - ); + const tx = testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: notExchangeAddress }); const expectedError = new StakingRevertErrors.OnlyCallableByExchangeError(notExchangeAddress); return expect(tx).to.revertWith(expectedError); }); it('should revert if `protocolFee` is zero with non-zero value sent', async () => { - const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - ZERO_AMOUNT, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + const tx = testContract + .payProtocolFee(makerAddress, payerAddress, ZERO_AMOUNT) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); const expectedError = new StakingRevertErrors.InvalidProtocolFeePaymentError( ZERO_AMOUNT, DEFAULT_PROTOCOL_FEE_PAID, @@ -105,12 +101,9 @@ blockchainTests('Protocol Fees unit tests', env => { }); it('should revert if `protocolFee` is < than the provided message value', async () => { - const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.minus(1) }, - ); + const tx = testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.minus(1) }); const expectedError = new StakingRevertErrors.InvalidProtocolFeePaymentError( DEFAULT_PROTOCOL_FEE_PAID, DEFAULT_PROTOCOL_FEE_PAID.minus(1), @@ -119,12 +112,9 @@ blockchainTests('Protocol Fees unit tests', env => { }); it('should revert if `protocolFee` is > than the provided message value', async () => { - const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.plus(1) }, - ); + const tx = testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.plus(1) }); const expectedError = new StakingRevertErrors.InvalidProtocolFeePaymentError( DEFAULT_PROTOCOL_FEE_PAID, DEFAULT_PROTOCOL_FEE_PAID.plus(1), @@ -134,7 +124,7 @@ blockchainTests('Protocol Fees unit tests', env => { }); async function getProtocolFeesAsync(poolId: string): Promise { - return (await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId)).feesCollected; + return (await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync()).feesCollected; } describe('ETH fees', () => { @@ -148,23 +138,17 @@ blockchainTests('Protocol Fees unit tests', env => { it('should not transfer WETH if value is sent', async () => { await createTestPoolAsync({ operatorStake: minimumStake }); - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); assertNoWETHTransferLogs(receipt.logs); }); it('should credit pool if the maker is in a pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] }); - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); assertNoWETHTransferLogs(receipt.logs); const poolFees = await getProtocolFeesAsync(poolId); @@ -173,12 +157,9 @@ blockchainTests('Protocol Fees unit tests', env => { it('should not credit the pool if maker is not in a pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake }); - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); assertNoWETHTransferLogs(receipt.logs); const poolFees = await getProtocolFeesAsync(poolId); expect(poolFees).to.bignumber.eq(ZERO_AMOUNT); @@ -187,12 +168,9 @@ blockchainTests('Protocol Fees unit tests', env => { it('fees paid to the same maker should go to the same pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] }); const payAsync = async () => { - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); assertNoWETHTransferLogs(receipt.logs); }; await payAsync(); @@ -219,23 +197,17 @@ blockchainTests('Protocol Fees unit tests', env => { it('should transfer WETH if no value is sent and the maker is not in a pool', async () => { await createTestPoolAsync({ operatorStake: minimumStake }); - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: ZERO_AMOUNT }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT }); assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID); }); it('should update `protocolFeesThisEpochByPool` if the maker is in a pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] }); - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: ZERO_AMOUNT }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT }); assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID); const poolFees = await getProtocolFeesAsync(poolId); expect(poolFees).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); @@ -243,12 +215,9 @@ blockchainTests('Protocol Fees unit tests', env => { it('should not update `protocolFeesThisEpochByPool` if maker is not in a pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake }); - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: ZERO_AMOUNT }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT }); assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID); const poolFees = await getProtocolFeesAsync(poolId); expect(poolFees).to.bignumber.eq(ZERO_AMOUNT); @@ -257,12 +226,9 @@ blockchainTests('Protocol Fees unit tests', env => { it('fees paid to the same maker should go to the same pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] }); const payAsync = async () => { - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: ZERO_AMOUNT }, - ); + const receipt = await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT }); assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID); }; await payAsync(); @@ -275,15 +241,12 @@ blockchainTests('Protocol Fees unit tests', env => { it('fees paid to the same maker in WETH then ETH should go to the same pool', async () => { const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] }); const payAsync = async (inWETH: boolean) => { - await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - payerAddress, - DEFAULT_PROTOCOL_FEE_PAID, - { + await testContract + .payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: inWETH ? ZERO_AMOUNT : DEFAULT_PROTOCOL_FEE_PAID, - }, - ); + }); }; await payAsync(true); await payAsync(false); @@ -300,12 +263,9 @@ blockchainTests('Protocol Fees unit tests', env => { membersStake: 0, makers: [makerAddress], }); - await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - constants.NULL_ADDRESS, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + await testContract + .payProtocolFee(makerAddress, constants.NULL_ADDRESS, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); const feesCredited = await getProtocolFeesAsync(poolId); expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); }); @@ -316,12 +276,9 @@ blockchainTests('Protocol Fees unit tests', env => { membersStake: 0, makers: [makerAddress], }); - await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - constants.NULL_ADDRESS, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + await testContract + .payProtocolFee(makerAddress, constants.NULL_ADDRESS, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); const feesCredited = await getProtocolFeesAsync(poolId); expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID); }); @@ -332,12 +289,9 @@ blockchainTests('Protocol Fees unit tests', env => { membersStake: 0, makers: [makerAddress], }); - await testContract.payProtocolFee.awaitTransactionSuccessAsync( - makerAddress, - constants.NULL_ADDRESS, - DEFAULT_PROTOCOL_FEE_PAID, - { from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }, - ); + await testContract + .payProtocolFee(makerAddress, constants.NULL_ADDRESS, DEFAULT_PROTOCOL_FEE_PAID) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID }); const feesCredited = await getProtocolFeesAsync(poolId); expect(feesCredited).to.bignumber.eq(0); }); @@ -347,7 +301,7 @@ blockchainTests('Protocol Fees unit tests', env => { let membersStakeWeight: number; before(async () => { - membersStakeWeight = (await testContract.getParams.callAsync())[1]; + membersStakeWeight = (await testContract.getParams().callAsync())[1]; }); interface FinalizationState { @@ -357,7 +311,7 @@ blockchainTests('Protocol Fees unit tests', env => { } async function getFinalizationStateAsync(): Promise { - const aggregatedStats = await testContract.getAggregatedStatsForCurrentEpoch.callAsync(); + const aggregatedStats = await testContract.getAggregatedStatsForCurrentEpoch().callAsync(); return { numPoolsToFinalize: aggregatedStats.numPoolsToFinalize, totalFeesCollected: aggregatedStats.totalFeesCollected, @@ -372,12 +326,9 @@ blockchainTests('Protocol Fees unit tests', env => { async function payToMakerAsync(poolMaker: string, fee?: Numberish): Promise { const _fee = fee === undefined ? getRandomInteger(1, '1e18') : fee; - const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync( - poolMaker, - payerAddress, - new BigNumber(_fee), - { from: exchangeAddress, value: _fee }, - ); + const receipt = await testContract + .payProtocolFee(poolMaker, payerAddress, new BigNumber(_fee)) + .awaitTransactionSuccessAsync({ from: exchangeAddress, value: _fee }); const events = filterLogsToArguments( receipt.logs, IStakingEventsEvents.StakingPoolEarnedRewardsInEpoch, @@ -404,7 +355,7 @@ blockchainTests('Protocol Fees unit tests', env => { it('pool is not registered to start', async () => { const { poolId } = await createTestPoolAsync(); - const pool = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId); + const pool = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync(); expect(pool.feesCollected).to.bignumber.eq(0); expect(pool.membersStake).to.bignumber.eq(0); expect(pool.weightedStake).to.bignumber.eq(0); @@ -419,7 +370,7 @@ blockchainTests('Protocol Fees unit tests', env => { const { fee, poolEarnedRewardsEvents } = await payToMakerAsync(poolMaker); expect(poolEarnedRewardsEvents.length).to.eq(1); expect(poolEarnedRewardsEvents[0].poolId).to.eq(poolId); - const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId); + const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync(); const expectedWeightedStake = toWeightedStake(pool.operatorStake, pool.membersStake); expect(actualPoolStats.feesCollected).to.bignumber.eq(fee); expect(actualPoolStats.membersStake).to.bignumber.eq(pool.membersStake); @@ -439,7 +390,7 @@ blockchainTests('Protocol Fees unit tests', env => { const { fee: fee1 } = await payToMakerAsync(poolMaker); const { fee: fee2, poolEarnedRewardsEvents } = await payToMakerAsync(poolMaker); expect(poolEarnedRewardsEvents).to.deep.eq([]); - const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId); + const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync(); const expectedWeightedStake = toWeightedStake(pool.operatorStake, pool.membersStake); const fees = BigNumber.sum(fee1, fee2); expect(actualPoolStats.feesCollected).to.bignumber.eq(fees); @@ -463,7 +414,7 @@ blockchainTests('Protocol Fees unit tests', env => { const { fee, poolEarnedRewardsEvents } = await payToMakerAsync(poolMaker); expect(poolEarnedRewardsEvents.length).to.eq(1); expect(poolEarnedRewardsEvents[0].poolId).to.eq(poolId); - const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId); + const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync(); const expectedWeightedStake = toWeightedStake(pool.operatorStake, pool.membersStake); expect(actualPoolStats.feesCollected).to.bignumber.eq(fee); expect(actualPoolStats.membersStake).to.bignumber.eq(pool.membersStake); @@ -484,8 +435,8 @@ blockchainTests('Protocol Fees unit tests', env => { makers: [poolMaker], } = pool; await payToMakerAsync(poolMaker); - await testContract.advanceEpoch.awaitTransactionSuccessAsync(); - const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId); + await testContract.advanceEpoch().awaitTransactionSuccessAsync(); + const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync(); expect(actualPoolStats.feesCollected).to.bignumber.eq(0); expect(actualPoolStats.membersStake).to.bignumber.eq(0); expect(actualPoolStats.weightedStake).to.bignumber.eq(0); diff --git a/contracts/staking/test/unit_tests/stake_balances_test.ts b/contracts/staking/test/unit_tests/stake_balances_test.ts index d4f28914df..44d625fe2f 100644 --- a/contracts/staking/test/unit_tests/stake_balances_test.ts +++ b/contracts/staking/test/unit_tests/stake_balances_test.ts @@ -61,11 +61,10 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { ); before(async () => { - await testContract.setGlobalStakeByStatus.awaitTransactionSuccessAsync( - StakeStatus.Delegated, - delegatedBalance, - ); - await testContract.setBalanceOfZrxVault.awaitTransactionSuccessAsync(zrxVaultBalance); + await testContract + .setGlobalStakeByStatus(StakeStatus.Delegated, delegatedBalance) + .awaitTransactionSuccessAsync(); + await testContract.setBalanceOfZrxVault(zrxVaultBalance).awaitTransactionSuccessAsync(); }); it('undelegated stake is the difference between zrx vault balance and global delegated stake', async () => { @@ -74,12 +73,12 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { currentEpochBalance: zrxVaultBalance.minus(delegatedBalance.currentEpochBalance), nextEpochBalance: zrxVaultBalance.minus(delegatedBalance.nextEpochBalance), }; - const actualBalance = await testContract.getGlobalStakeByStatus.callAsync(StakeStatus.Undelegated); + const actualBalance = await testContract.getGlobalStakeByStatus(StakeStatus.Undelegated).callAsync(); expect(actualBalance).to.deep.eq(expectedBalance); }); it('delegated stake is the global delegated stake', async () => { - const actualBalance = await testContract.getGlobalStakeByStatus.callAsync(StakeStatus.Delegated); + const actualBalance = await testContract.getGlobalStakeByStatus(StakeStatus.Delegated).callAsync(); expect(actualBalance).to.deep.eq(toCurrentBalance(delegatedBalance)); }); @@ -88,8 +87,8 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { delegatedBalance.currentEpochBalance, delegatedBalance.nextEpochBalance, ).minus(1); - await testContract.setBalanceOfZrxVault.awaitTransactionSuccessAsync(_zrxVaultBalance); - const tx = testContract.getGlobalStakeByStatus.callAsync(StakeStatus.Undelegated); + await testContract.setBalanceOfZrxVault(_zrxVaultBalance).awaitTransactionSuccessAsync(); + const tx = testContract.getGlobalStakeByStatus(StakeStatus.Undelegated).callAsync(); const expectedError = new SafeMathRevertErrors.Uint256BinOpError( SafeMathRevertErrors.BinOpErrorCodes.SubtractionUnderflow, _zrxVaultBalance, @@ -101,7 +100,7 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { }); it('throws if unknown stake status is passed in', async () => { - const tx = testContract.getGlobalStakeByStatus.callAsync(2); + const tx = testContract.getGlobalStakeByStatus(2).callAsync(); return expect(tx).to.be.rejected(); }); }); @@ -113,40 +112,36 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { const undelegatedStake = randomStoredBalance(); before(async () => { - await testContract.setOwnerStakeByStatus.awaitTransactionSuccessAsync( - staker, - StakeStatus.Delegated, - delegatedStake, - ); - await testContract.setOwnerStakeByStatus.awaitTransactionSuccessAsync( - staker, - StakeStatus.Undelegated, - undelegatedStake, - ); + await testContract + .setOwnerStakeByStatus(staker, StakeStatus.Delegated, delegatedStake) + .awaitTransactionSuccessAsync(); + await testContract + .setOwnerStakeByStatus(staker, StakeStatus.Undelegated, undelegatedStake) + .awaitTransactionSuccessAsync(); }); it('throws if unknown stake status is passed in', async () => { - const tx = testContract.getOwnerStakeByStatus.callAsync(staker, 2); + const tx = testContract.getOwnerStakeByStatus(staker, 2).callAsync(); return expect(tx).to.be.rejected(); }); it('returns empty delegated stake for an unstaked owner', async () => { - const balance = await testContract.getOwnerStakeByStatus.callAsync(notStaker, StakeStatus.Delegated); + const balance = await testContract.getOwnerStakeByStatus(notStaker, StakeStatus.Delegated).callAsync(); expect(balance).to.deep.eq(EMPTY_BALANCE); }); it('returns empty undelegated stake for an unstaked owner', async () => { - const balance = await testContract.getOwnerStakeByStatus.callAsync(notStaker, StakeStatus.Undelegated); + const balance = await testContract.getOwnerStakeByStatus(notStaker, StakeStatus.Undelegated).callAsync(); expect(balance).to.deep.eq(EMPTY_BALANCE); }); it('returns undelegated stake for a staked owner', async () => { - const balance = await testContract.getOwnerStakeByStatus.callAsync(staker, StakeStatus.Undelegated); + const balance = await testContract.getOwnerStakeByStatus(staker, StakeStatus.Undelegated).callAsync(); expect(balance).to.deep.eq(toCurrentBalance(undelegatedStake)); }); it('returns delegated stake for a staked owner', async () => { - const balance = await testContract.getOwnerStakeByStatus.callAsync(staker, StakeStatus.Delegated); + const balance = await testContract.getOwnerStakeByStatus(staker, StakeStatus.Delegated).callAsync(); expect(balance).to.deep.eq(toCurrentBalance(delegatedStake)); }); }); @@ -157,16 +152,16 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { const stakerAmount = randomAmount(); before(async () => { - await testContract.setZrxBalanceOf.awaitTransactionSuccessAsync(staker, stakerAmount); + await testContract.setZrxBalanceOf(staker, stakerAmount).awaitTransactionSuccessAsync(); }); it('returns empty for unstaked owner', async () => { - const amount = await testContract.getTotalStake.callAsync(notStaker); + const amount = await testContract.getTotalStake(notStaker).callAsync(); expect(amount).to.bignumber.eq(0); }); it('returns stake for staked owner', async () => { - const amount = await testContract.getTotalStake.callAsync(staker); + const amount = await testContract.getTotalStake(staker).callAsync(); expect(amount).to.bignumber.eq(stakerAmount); }); }); @@ -179,25 +174,23 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { const delegatedBalance = randomStoredBalance(); before(async () => { - await testContract.setDelegatedStakeToPoolByOwner.awaitTransactionSuccessAsync( - staker, - poolId, - delegatedBalance, - ); + await testContract + .setDelegatedStakeToPoolByOwner(staker, poolId, delegatedBalance) + .awaitTransactionSuccessAsync(); }); it('returns empty for unstaked owner', async () => { - const balance = await testContract.getStakeDelegatedToPoolByOwner.callAsync(notStaker, poolId); + const balance = await testContract.getStakeDelegatedToPoolByOwner(notStaker, poolId).callAsync(); expect(balance).to.deep.eq(EMPTY_BALANCE); }); it('returns empty for empty pool', async () => { - const balance = await testContract.getStakeDelegatedToPoolByOwner.callAsync(staker, notPoolId); + const balance = await testContract.getStakeDelegatedToPoolByOwner(staker, notPoolId).callAsync(); expect(balance).to.deep.eq(EMPTY_BALANCE); }); it('returns stake for staked owner in their pool', async () => { - const balance = await testContract.getStakeDelegatedToPoolByOwner.callAsync(staker, poolId); + const balance = await testContract.getStakeDelegatedToPoolByOwner(staker, poolId).callAsync(); expect(balance).to.deep.eq(toCurrentBalance(delegatedBalance)); }); }); @@ -208,16 +201,16 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => { const delegatedBalance = randomStoredBalance(); before(async () => { - await testContract.setDelegatedStakeByPoolId.awaitTransactionSuccessAsync(poolId, delegatedBalance); + await testContract.setDelegatedStakeByPoolId(poolId, delegatedBalance).awaitTransactionSuccessAsync(); }); it('returns empty for empty pool', async () => { - const balance = await testContract.getTotalStakeDelegatedToPool.callAsync(notPoolId); + const balance = await testContract.getTotalStakeDelegatedToPool(notPoolId).callAsync(); expect(balance).to.deep.eq(EMPTY_BALANCE); }); it('returns stake for staked pool', async () => { - const balance = await testContract.getTotalStakeDelegatedToPool.callAsync(poolId); + const balance = await testContract.getTotalStakeDelegatedToPool(poolId).callAsync(); expect(balance).to.deep.eq(toCurrentBalance(delegatedBalance)); }); }); diff --git a/contracts/staking/test/unit_tests/stake_test.ts b/contracts/staking/test/unit_tests/stake_test.ts index 1c50d162cf..d3d56af949 100644 --- a/contracts/staking/test/unit_tests/stake_test.ts +++ b/contracts/staking/test/unit_tests/stake_test.ts @@ -46,17 +46,16 @@ blockchainTests.resets('MixinStake unit tests', env => { env.txDefaults, artifacts, ); - currentEpoch = await testContract.currentEpoch.callAsync(); - stakerUndelegatedStakeSlot = await testContract.getOwnerStakeByStatusSlot.callAsync( - staker, - StakeStatus.Undelegated, - ); + currentEpoch = await testContract.currentEpoch().callAsync(); + stakerUndelegatedStakeSlot = await testContract + .getOwnerStakeByStatusSlot(staker, StakeStatus.Undelegated) + .callAsync(); }); describe('stake()', () => { it('deposits funds into the ZRX vault', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.stake.awaitTransactionSuccessAsync(amount); + const { logs } = await testContract.stake(amount).awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.ZrxVaultDepositFrom); expect(events).to.be.length(1); expect(events[0].staker).to.eq(staker); @@ -65,7 +64,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('increases current and next undelegated stake balance', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.stake.awaitTransactionSuccessAsync(amount); + const { logs } = await testContract.stake(amount).awaitTransactionSuccessAsync(); const events = filterLogsToArguments( logs, StakeEvents.IncreaseCurrentAndNextBalance, @@ -77,7 +76,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('raises a `Stake` event', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.stake.awaitTransactionSuccessAsync(amount); + const { logs } = await testContract.stake(amount).awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.Stake); expect(events).to.be.length(1); expect(events[0].staker).to.eq(staker); @@ -90,17 +89,19 @@ blockchainTests.resets('MixinStake unit tests', env => { currentEpochBalance: Numberish, nextEpochBalance: Numberish, ): Promise { - await testContract.setOwnerStakeByStatus.awaitTransactionSuccessAsync(staker, StakeStatus.Undelegated, { - currentEpoch, - currentEpochBalance: new BigNumber(currentEpochBalance), - nextEpochBalance: new BigNumber(nextEpochBalance), - }); + await testContract + .setOwnerStakeByStatus(staker, StakeStatus.Undelegated, { + currentEpoch, + currentEpochBalance: new BigNumber(currentEpochBalance), + nextEpochBalance: new BigNumber(nextEpochBalance), + }) + .awaitTransactionSuccessAsync(); } it('throws if not enough undelegated stake in the current epoch', async () => { const amount = getRandomInteger(0, 100e18); await setUndelegatedStakeAsync(amount.minus(1), amount); - const tx = testContract.unstake.awaitTransactionSuccessAsync(amount); + const tx = testContract.unstake(amount).awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InsufficientBalanceError(amount, amount.minus(1)); return expect(tx).to.revertWith(expectedError); }); @@ -108,7 +109,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('throws if not enough undelegated stake in the next epoch', async () => { const amount = getRandomInteger(0, 100e18); await setUndelegatedStakeAsync(amount, amount.minus(1)); - const tx = testContract.unstake.awaitTransactionSuccessAsync(amount); + const tx = testContract.unstake(amount).awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InsufficientBalanceError(amount, amount.minus(1)); return expect(tx).to.revertWith(expectedError); }); @@ -116,7 +117,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('throws if not enough undelegated stake in both epochs', async () => { const amount = getRandomInteger(0, 100e18); await setUndelegatedStakeAsync(amount.minus(1), amount.minus(1)); - const tx = testContract.unstake.awaitTransactionSuccessAsync(amount); + const tx = testContract.unstake(amount).awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.InsufficientBalanceError(amount, amount.minus(1)); return expect(tx).to.revertWith(expectedError); }); @@ -124,7 +125,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('decreases current and next undelegated stake balance', async () => { const amount = getRandomInteger(0, 100e18); await setUndelegatedStakeAsync(amount, amount); - const { logs } = await testContract.unstake.awaitTransactionSuccessAsync(amount); + const { logs } = await testContract.unstake(amount).awaitTransactionSuccessAsync(); const events = filterLogsToArguments( logs, StakeEvents.DecreaseCurrentAndNextBalance, @@ -137,7 +138,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('withdraws funds from the ZRX vault', async () => { const amount = getRandomInteger(0, 100e18); await setUndelegatedStakeAsync(amount, amount); - const { logs } = await testContract.unstake.awaitTransactionSuccessAsync(amount); + const { logs } = await testContract.unstake(amount).awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.ZrxVaultWithdrawFrom); expect(events).to.be.length(1); expect(events[0].staker).to.eq(staker); @@ -147,7 +148,7 @@ blockchainTests.resets('MixinStake unit tests', env => { it('emits an `Unstake` event', async () => { const amount = getRandomInteger(0, 100e18); await setUndelegatedStakeAsync(amount, amount); - const { logs } = await testContract.unstake.awaitTransactionSuccessAsync(amount); + const { logs } = await testContract.unstake(amount).awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.Unstake); expect(events).to.be.length(1); expect(events[0].staker).to.eq(staker); @@ -167,52 +168,59 @@ blockchainTests.resets('MixinStake unit tests', env => { before(async () => { delegatedStakeToPoolByOwnerSlots = await Promise.all( VALID_POOL_IDS.map(async poolId => - testContract.getDelegatedStakeToPoolByOwnerSlot.callAsync(poolId, staker), + testContract.getDelegatedStakeToPoolByOwnerSlot(poolId, staker).callAsync(), ), ); delegatedStakeByPoolIdSlots = await Promise.all( - VALID_POOL_IDS.map(async poolId => testContract.getDelegatedStakeByPoolIdSlot.callAsync(poolId)), - ); - globalDelegatedStakeSlot = await testContract.getGlobalStakeByStatusSlot.callAsync(StakeStatus.Delegated); - stakerDelegatedStakeSlot = await testContract.getOwnerStakeByStatusSlot.callAsync( - staker, - StakeStatus.Delegated, + VALID_POOL_IDS.map(async poolId => testContract.getDelegatedStakeByPoolIdSlot(poolId).callAsync()), ); + globalDelegatedStakeSlot = await testContract.getGlobalStakeByStatusSlot(StakeStatus.Delegated).callAsync(); + stakerDelegatedStakeSlot = await testContract + .getOwnerStakeByStatusSlot(staker, StakeStatus.Delegated) + .callAsync(); }); it('throws if the "from" pool is invalid', async () => { - const tx = testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - getRandomInteger(0, 100e18), - ); + const tx = testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(INVALID_POOL_ERROR); }); it('throws if the "to" pool is invalid', async () => { - const tx = testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, - getRandomInteger(0, 100e18), - ); + const tx = testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(INVALID_POOL_ERROR); }); it('throws if the "from" and "to" pools are invalid', async () => { - const tx = testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, - { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, - getRandomInteger(0, 100e18), - ); + const tx = testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, + { status: StakeStatus.Delegated, poolId: INVALID_POOL_ID }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith(INVALID_POOL_ERROR); }); it('withdraws delegator rewards when "from" stake is delegated', async () => { - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, - getRandomInteger(0, 100e18), - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments( logs, StakeEvents.WithdrawAndSyncDelegatorRewards, @@ -223,11 +231,13 @@ blockchainTests.resets('MixinStake unit tests', env => { }); it('withdraws delegator rewards when "to" stake is delegated', async () => { - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - getRandomInteger(0, 100e18), - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments( logs, StakeEvents.WithdrawAndSyncDelegatorRewards, @@ -238,11 +248,13 @@ blockchainTests.resets('MixinStake unit tests', env => { }); it('withdraws delegator rewards when both stakes are both delegated', async () => { - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - getRandomInteger(0, 100e18), - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments( logs, StakeEvents.WithdrawAndSyncDelegatorRewards, @@ -255,11 +267,13 @@ blockchainTests.resets('MixinStake unit tests', env => { }); it('does not withdraw delegator rewards when both stakes are both undelegated', async () => { - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, - getRandomInteger(0, 100e18), - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, + getRandomInteger(0, 100e18), + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments( logs, StakeEvents.WithdrawAndSyncDelegatorRewards, @@ -269,11 +283,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('decreases pool and global delegated stake counters when "from" stake is delegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const decreaseNextBalanceEvents = filterLogsToArguments( logs, StakeEvents.DecreaseNextBalance, @@ -292,11 +308,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('increases pool and global delegated stake counters when "to" stake is delegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const increaseNextBalanceEvents = filterLogsToArguments( logs, StakeEvents.IncreaseNextBalance, @@ -315,11 +333,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('decreases then increases pool and global delegated stake counters when both stakes are delegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const decreaseNextBalanceEvents = filterLogs( logs, StakeEvents.DecreaseNextBalance, @@ -356,11 +376,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('does not change pool and global delegated stake counters when both stakes are undelegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const decreaseNextBalanceEvents = filterLogsToArguments( logs, StakeEvents.DecreaseNextBalance, @@ -375,33 +397,39 @@ blockchainTests.resets('MixinStake unit tests', env => { it('does nothing when moving the owner stake from undelegated to undelegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.MoveStakeStorage); expect(events).to.be.length(0); }); it('does nothing when moving zero stake', async () => { const amount = new BigNumber(0); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.MoveStakeStorage); expect(events).to.be.length(0); }); it('moves the owner stake between the same pointer when both are delegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.MoveStakeStorage); expect(events).to.be.length(1); expect(events[0].fromBalanceSlot).to.eq(stakerDelegatedStakeSlot); @@ -411,11 +439,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('moves the owner stake between different pointers when "from" is undelegated and "to" is delegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.MoveStakeStorage); expect(events).to.be.length(1); expect(events[0].fromBalanceSlot).to.eq(stakerUndelegatedStakeSlot); @@ -425,11 +455,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('moves the owner stake between different pointers when "from" is delegated and "to" is undelegated', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.MoveStakeStorage); expect(events).to.be.length(1); expect(events[0].fromBalanceSlot).to.eq(stakerDelegatedStakeSlot); @@ -439,11 +471,13 @@ blockchainTests.resets('MixinStake unit tests', env => { it('emits a `MoveStake` event', async () => { const amount = getRandomInteger(0, 100e18); - const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync( - { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, - { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, - amount, - ); + const { logs } = await testContract + .moveStake( + { status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] }, + { status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] }, + amount, + ) + .awaitTransactionSuccessAsync(); const events = filterLogsToArguments(logs, StakeEvents.MoveStake); expect(events).to.be.length(1); expect(events[0].staker).to.eq(staker); diff --git a/contracts/staking/test/unit_tests/staking_pool_test.ts b/contracts/staking/test/unit_tests/staking_pool_test.ts index 2849a28d15..84b349bcac 100644 --- a/contracts/staking/test/unit_tests/staking_pool_test.ts +++ b/contracts/staking/test/unit_tests/staking_pool_test.ts @@ -56,34 +56,36 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { operatorShare: randomOperatorShare(), ...opts, }; - await testContract.setPoolById.awaitTransactionSuccessAsync(_opts.poolId, { - operator: _opts.operator, - operatorShare: _opts.operatorShare, - }); + await testContract + .setPoolById(_opts.poolId, { + operator: _opts.operator, + operatorShare: _opts.operatorShare, + }) + .awaitTransactionSuccessAsync(); return _opts; } async function addMakerToPoolAsync(poolId: string, _maker: string): Promise { - await testContract.setPoolIdByMaker.awaitTransactionSuccessAsync(poolId, _maker); + await testContract.setPoolIdByMaker(poolId, _maker).awaitTransactionSuccessAsync(); } describe('onlyStakingPoolOperator modifier', () => { it('fails if not called by the pool operator', async () => { const { poolId } = await createPoolAsync(); - const tx = testContract.testOnlyStakingPoolOperatorModifier.callAsync(poolId, { from: notOperatorOrMaker }); + const tx = testContract.testOnlyStakingPoolOperatorModifier(poolId).callAsync({ from: notOperatorOrMaker }); const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(notOperatorOrMaker, poolId); return expect(tx).to.revertWith(expectedError); }); it('fails if called by a pool maker', async () => { const { poolId } = await createPoolAsync(); await addMakerToPoolAsync(poolId, maker); - const tx = testContract.testOnlyStakingPoolOperatorModifier.callAsync(poolId, { from: maker }); + const tx = testContract.testOnlyStakingPoolOperatorModifier(poolId).callAsync({ from: maker }); const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(maker, poolId); return expect(tx).to.revertWith(expectedError); }); it('succeeds if called by the pool operator', async () => { const { poolId } = await createPoolAsync(); - await testContract.testOnlyStakingPoolOperatorModifier.callAsync(poolId, { from: operator }); + await testContract.testOnlyStakingPoolOperatorModifier(poolId).callAsync({ from: operator }); }); }); @@ -91,12 +93,12 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { let nextPoolId: string; before(async () => { - nextPoolId = toNextPoolId(await testContract.lastPoolId.callAsync()); + nextPoolId = toNextPoolId(await testContract.lastPoolId().callAsync()); }); it('fails if the next pool ID overflows', async () => { - await testContract.setLastPoolId.awaitTransactionSuccessAsync(toHex(constants.MAX_UINT256)); - const tx = testContract.createStakingPool.awaitTransactionSuccessAsync(randomOperatorShare(), false); + await testContract.setLastPoolId(toHex(constants.MAX_UINT256)).awaitTransactionSuccessAsync(); + const tx = testContract.createStakingPool(randomOperatorShare(), false).awaitTransactionSuccessAsync(); const expectedError = new SafeMathRevertErrors.Uint256BinOpError( SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow, constants.MAX_UINT256, @@ -106,7 +108,7 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { }); it('fails if the operator share is invalid', async () => { const operatorShare = constants.PPM_100_PERCENT + 1; - const tx = testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false); + const tx = testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync(); const expectedError = new StakingRevertErrors.OperatorShareError( StakingRevertErrors.OperatorShareErrorCodes.OperatorShareTooLarge, nextPoolId, @@ -115,14 +117,12 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { return expect(tx).to.revertWith(expectedError); }); it('operator can create and own multiple pools', async () => { - const { logs: logs1 } = await testContract.createStakingPool.awaitTransactionSuccessAsync( - randomOperatorShare(), - false, - ); - const { logs: logs2 } = await testContract.createStakingPool.awaitTransactionSuccessAsync( - randomOperatorShare(), - false, - ); + const { logs: logs1 } = await testContract + .createStakingPool(randomOperatorShare(), false) + .awaitTransactionSuccessAsync(); + const { logs: logs2 } = await testContract + .createStakingPool(randomOperatorShare(), false) + .awaitTransactionSuccessAsync(); const createEvents = filterLogsToArguments( [...logs1, ...logs2], TestMixinStakingPoolEvents.StakingPoolCreated, @@ -130,27 +130,27 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { expect(createEvents).to.be.length(2); const poolIds = createEvents.map(e => e.poolId); expect(poolIds[0]).to.not.eq(poolIds[1]); - const pools = await Promise.all(poolIds.map(async poolId => testContract.getStakingPool.callAsync(poolId))); + const pools = await Promise.all( + poolIds.map(async poolId => testContract.getStakingPool(poolId).callAsync()), + ); expect(pools[0].operator).to.eq(pools[1].operator); }); it('operator can only be maker of one pool', async () => { - await testContract.createStakingPool.awaitTransactionSuccessAsync(randomOperatorShare(), true); - const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync( - randomOperatorShare(), - true, - ); + await testContract.createStakingPool(randomOperatorShare(), true).awaitTransactionSuccessAsync(); + const { logs } = await testContract + .createStakingPool(randomOperatorShare(), true) + .awaitTransactionSuccessAsync(); const createEvents = filterLogsToArguments( logs, TestMixinStakingPoolEvents.StakingPoolCreated, ); - const makerPool = await testContract.poolIdByMaker.callAsync(operator); + const makerPool = await testContract.poolIdByMaker(operator).callAsync(); expect(makerPool).to.eq(createEvents[0].poolId); }); it('computes correct next pool ID', async () => { - const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync( - randomOperatorShare(), - false, - ); + const { logs } = await testContract + .createStakingPool(randomOperatorShare(), false) + .awaitTransactionSuccessAsync(); const createEvents = filterLogsToArguments( logs, TestMixinStakingPoolEvents.StakingPoolCreated, @@ -159,46 +159,46 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { expect(poolId).to.eq(nextPoolId); }); it('increments last pool ID counter', async () => { - await testContract.createStakingPool.awaitTransactionSuccessAsync(randomOperatorShare(), false); - const lastPoolIdAfter = await testContract.lastPoolId.callAsync(); + await testContract.createStakingPool(randomOperatorShare(), false).awaitTransactionSuccessAsync(); + const lastPoolIdAfter = await testContract.lastPoolId().callAsync(); expect(lastPoolIdAfter).to.eq(nextPoolId); }); it('records pool details', async () => { const operatorShare = randomOperatorShare(); - await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { from: operator }); - const pool = await testContract.getStakingPool.callAsync(nextPoolId); + await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator }); + const pool = await testContract.getStakingPool(nextPoolId).callAsync(); expect(pool.operator).to.eq(operator); expect(pool.operatorShare).to.bignumber.eq(operatorShare); }); it('records pool details when operator share is 100%', async () => { const operatorShare = constants.PPM_100_PERCENT; - await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { from: operator }); - const pool = await testContract.getStakingPool.callAsync(nextPoolId); + await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator }); + const pool = await testContract.getStakingPool(nextPoolId).callAsync(); expect(pool.operator).to.eq(operator); expect(pool.operatorShare).to.bignumber.eq(operatorShare); }); it('records pool details when operator share is 0%', async () => { const operatorShare = constants.ZERO_AMOUNT; - await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { from: operator }); - const pool = await testContract.getStakingPool.callAsync(nextPoolId); + await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator }); + const pool = await testContract.getStakingPool(nextPoolId).callAsync(); expect(pool.operator).to.eq(operator); expect(pool.operatorShare).to.bignumber.eq(operatorShare); }); it('returns the next pool ID', async () => { - const poolId = await testContract.createStakingPool.callAsync(randomOperatorShare(), false, { + const poolId = await testContract.createStakingPool(randomOperatorShare(), false).callAsync({ from: operator, }); expect(poolId).to.eq(nextPoolId); }); it('can add operator as a maker', async () => { const operatorShare = randomOperatorShare(); - await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, true, { from: operator }); - const makerPoolId = await testContract.poolIdByMaker.callAsync(operator); + await testContract.createStakingPool(operatorShare, true).awaitTransactionSuccessAsync({ from: operator }); + const makerPoolId = await testContract.poolIdByMaker(operator).callAsync(); expect(makerPoolId).to.eq(nextPoolId); }); it('emits a `StakingPoolCreated` event', async () => { const operatorShare = randomOperatorShare(); - const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { + const { logs } = await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator, }); verifyEventsFromLogs( @@ -215,7 +215,7 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { }); it('emits a `MakerStakingPoolSet` event when also joining as a maker', async () => { const operatorShare = randomOperatorShare(); - const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, true, { + const { logs } = await testContract.createStakingPool(operatorShare, true).awaitTransactionSuccessAsync({ from: operator, }); verifyEventsFromLogs( @@ -234,32 +234,26 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { describe('decreaseStakingPoolOperatorShare()', () => { it('fails if not called by operator', async () => { const { poolId, operatorShare } = await createPoolAsync(); - const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare - 1, - { from: notOperatorOrMaker }, - ); + const tx = testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare - 1) + .awaitTransactionSuccessAsync({ from: notOperatorOrMaker }); const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(notOperatorOrMaker, poolId); return expect(tx).to.revertWith(expectedError); }); it('fails if called by maker', async () => { const { poolId, operatorShare } = await createPoolAsync(); await addMakerToPoolAsync(poolId, maker); - const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare - 1, - { from: maker }, - ); + const tx = testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare - 1) + .awaitTransactionSuccessAsync({ from: maker }); const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(maker, poolId); return expect(tx).to.revertWith(expectedError); }); it('fails if operator share is greater than current', async () => { const { poolId, operatorShare } = await createPoolAsync(); - const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare + 1, - { from: operator }, - ); + const tx = testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare + 1) + .awaitTransactionSuccessAsync({ from: operator }); const expectedError = new StakingRevertErrors.OperatorShareError( StakingRevertErrors.OperatorShareErrorCodes.CanOnlyDecreaseOperatorShare, poolId, @@ -269,11 +263,9 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { }); it('fails if operator share is greater than PPM_100_PERCENT', async () => { const { poolId } = await createPoolAsync(); - const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - constants.PPM_100_PERCENT + 1, - { from: operator }, - ); + const tx = testContract + .decreaseStakingPoolOperatorShare(poolId, constants.PPM_100_PERCENT + 1) + .awaitTransactionSuccessAsync({ from: operator }); const expectedError = new StakingRevertErrors.OperatorShareError( StakingRevertErrors.OperatorShareErrorCodes.OperatorShareTooLarge, poolId, @@ -283,39 +275,33 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { }); it('records new operator share', async () => { const { poolId, operatorShare } = await createPoolAsync(); - await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare - 1, - { from: operator }, - ); - const pool = await testContract.getStakingPool.callAsync(poolId); + await testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare - 1) + .awaitTransactionSuccessAsync({ from: operator }); + const pool = await testContract.getStakingPool(poolId).callAsync(); expect(pool.operatorShare).to.bignumber.eq(operatorShare - 1); }); it('does not modify operator share if equal to current', async () => { const { poolId, operatorShare } = await createPoolAsync(); - await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(poolId, operatorShare, { + await testContract.decreaseStakingPoolOperatorShare(poolId, operatorShare).awaitTransactionSuccessAsync({ from: operator, }); - const pool = await testContract.getStakingPool.callAsync(poolId); + const pool = await testContract.getStakingPool(poolId).callAsync(); expect(pool.operatorShare).to.bignumber.eq(operatorShare); }); it('does not modify operator', async () => { const { poolId, operatorShare } = await createPoolAsync(); - await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare - 1, - { from: operator }, - ); - const pool = await testContract.getStakingPool.callAsync(poolId); + await testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare - 1) + .awaitTransactionSuccessAsync({ from: operator }); + const pool = await testContract.getStakingPool(poolId).callAsync(); expect(pool.operator).to.eq(operator); }); it('emits an `OperatorShareDecreased` event', async () => { const { poolId, operatorShare } = await createPoolAsync(); - const { logs } = await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare - 1, - { from: operator }, - ); + const { logs } = await testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare - 1) + .awaitTransactionSuccessAsync({ from: operator }); verifyEventsFromLogs( logs, [ @@ -333,36 +319,36 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { describe('joinStakingPoolAsMaker()', () => { it('records sender as maker for the pool', async () => { const { poolId } = await createPoolAsync(); - await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: maker }); - const makerPoolId = await testContract.poolIdByMaker.callAsync(maker); + await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker }); + const makerPoolId = await testContract.poolIdByMaker(maker).callAsync(); expect(makerPoolId).to.eq(poolId); }); it('operator can join as maker for the pool', async () => { const { poolId } = await createPoolAsync(); - await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: operator }); - const makerPoolId = await testContract.poolIdByMaker.callAsync(operator); + await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: operator }); + const makerPoolId = await testContract.poolIdByMaker(operator).callAsync(); expect(makerPoolId).to.eq(poolId); }); it('can join the same pool as a maker twice', async () => { const { poolId } = await createPoolAsync(); - await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: maker }); - await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: maker }); - const makerPoolId = await testContract.poolIdByMaker.callAsync(maker); + await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker }); + await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker }); + const makerPoolId = await testContract.poolIdByMaker(maker).callAsync(); expect(makerPoolId).to.eq(poolId); }); it('can only be a maker in one pool at a time', async () => { const { poolId: poolId1 } = await createPoolAsync(); const { poolId: poolId2 } = await createPoolAsync(); - await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId1, { from: maker }); - let makerPoolId = await testContract.poolIdByMaker.callAsync(maker); + await testContract.joinStakingPoolAsMaker(poolId1).awaitTransactionSuccessAsync({ from: maker }); + let makerPoolId = await testContract.poolIdByMaker(maker).callAsync(); expect(makerPoolId).to.eq(poolId1); - await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId2, { from: maker }); - makerPoolId = await testContract.poolIdByMaker.callAsync(maker); + await testContract.joinStakingPoolAsMaker(poolId2).awaitTransactionSuccessAsync({ from: maker }); + makerPoolId = await testContract.poolIdByMaker(maker).callAsync(); expect(makerPoolId).to.eq(poolId2); }); it('emits a `MakerStakingPoolSet` event', async () => { const { poolId } = await createPoolAsync(); - const { logs } = await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { + const { logs } = await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker, }); verifyEventsFromLogs( diff --git a/contracts/staking/test/unit_tests/staking_proxy_test.ts b/contracts/staking/test/unit_tests/staking_proxy_test.ts index d89a87a6ab..915b6952ed 100644 --- a/contracts/staking/test/unit_tests/staking_proxy_test.ts +++ b/contracts/staking/test/unit_tests/staking_proxy_test.ts @@ -59,23 +59,23 @@ blockchainTests.resets('StakingProxy unit tests', env => { ); // Add authorized address to Staking Proxy - await testProxyContract.addAuthorizedAddress.sendTransactionAsync(authorizedAddress, { from: owner }); + await testProxyContract.addAuthorizedAddress(authorizedAddress).sendTransactionAsync({ from: owner }); }); describe('Fallback function', () => { it('should pass back the return value of the destination contract', async () => { - const returnValue = await testContractViaProxy.echo.callAsync(testString); + const returnValue = await testContractViaProxy.echo(testString).callAsync(); expect(returnValue).to.equal(testString); }); it('should revert with correct value when destination reverts', async () => { - return expect(testContractViaProxy.die.callAsync()).to.revertWith(testRevertString); + return expect(testContractViaProxy.die().callAsync()).to.revertWith(testRevertString); }); it('should revert if no staking contract is attached', async () => { - await testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({ from: authorizedAddress }); + await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress }); const expectedError = new StakingRevertErrors.ProxyDestinationCannotBeNilError(); - const tx = testContractViaProxy.echo.callAsync(testString); + const tx = testContractViaProxy.echo(testString).callAsync(); return expect(tx).to.revertWith(expectedError); }); }); @@ -83,11 +83,10 @@ blockchainTests.resets('StakingProxy unit tests', env => { describe('attachStakingContract', () => { it('should successfully attaching a new staking contract', async () => { // Cache existing staking contract and attach a new one - const initStakingContractAddress = await testProxyContract.stakingContract.callAsync(); - const txReceipt = await testProxyContract.attachStakingContract.awaitTransactionSuccessAsync( - testContract2.address, - { from: authorizedAddress }, - ); + const initStakingContractAddress = await testProxyContract.stakingContract().callAsync(); + const txReceipt = await testProxyContract + .attachStakingContract(testContract2.address) + .awaitTransactionSuccessAsync({ from: authorizedAddress }); // Validate `ContractAttachedToProxy` event verifyEventsFromLogs( @@ -112,14 +111,14 @@ blockchainTests.resets('StakingProxy unit tests', env => { ); // Validate new staking contract address - const finalStakingContractAddress = await testProxyContract.stakingContract.callAsync(); + const finalStakingContractAddress = await testProxyContract.stakingContract().callAsync(); expect(finalStakingContractAddress).to.be.equal(testContract2.address); expect(finalStakingContractAddress).to.not.equal(initStakingContractAddress); }); it('should revert if call to `init` on new staking contract fails', async () => { - await testProxyContract.setInitFailFlag.awaitTransactionSuccessAsync(); - const tx = testProxyContract.attachStakingContract.awaitTransactionSuccessAsync(testContract2.address, { + await testProxyContract.setInitFailFlag().awaitTransactionSuccessAsync(); + const tx = testProxyContract.attachStakingContract(testContract2.address).awaitTransactionSuccessAsync({ from: authorizedAddress, }); const expectedError = 'INIT_FAIL_FLAG_SET'; @@ -127,7 +126,7 @@ blockchainTests.resets('StakingProxy unit tests', env => { }); it('should revert if called by unauthorized address', async () => { - const tx = testProxyContract.attachStakingContract.awaitTransactionSuccessAsync(testContract2.address, { + const tx = testProxyContract.attachStakingContract(testContract2.address).awaitTransactionSuccessAsync({ from: notAuthorizedAddresses[0], }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddresses[0]); @@ -138,8 +137,8 @@ blockchainTests.resets('StakingProxy unit tests', env => { describe('detachStakingContract', () => { it('should detach staking contract', async () => { // Cache existing staking contract and attach a new one - const initStakingContractAddress = await testProxyContract.stakingContract.callAsync(); - const txReceipt = await testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({ + const initStakingContractAddress = await testProxyContract.stakingContract().callAsync(); + const txReceipt = await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress, }); @@ -147,13 +146,13 @@ blockchainTests.resets('StakingProxy unit tests', env => { verifyEventsFromLogs(txReceipt.logs, [{}], StakingProxyEvents.StakingContractDetachedFromProxy); // Validate staking contract address was unset - const finalStakingContractAddress = await testProxyContract.stakingContract.callAsync(); + const finalStakingContractAddress = await testProxyContract.stakingContract().callAsync(); expect(finalStakingContractAddress).to.be.equal(stakingConstants.NIL_ADDRESS); expect(finalStakingContractAddress).to.not.equal(initStakingContractAddress); }); it('should revert if called by unauthorized address', async () => { - const tx = testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({ + const tx = testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: notAuthorizedAddresses[0], }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddresses[0]); @@ -163,27 +162,27 @@ blockchainTests.resets('StakingProxy unit tests', env => { describe('batchExecute', () => { it('should execute no-op if no calls to make', async () => { - await testProxyContract.batchExecute.awaitTransactionSuccessAsync([]); + await testProxyContract.batchExecute([]).awaitTransactionSuccessAsync(); }); it('should call one function and return the output', async () => { - const calls = [testContract.echo.getABIEncodedTransactionData(testString)]; - const rawResults = await testProxyContract.batchExecute.callAsync(calls); + const calls = [testContract.echo(testString).getABIEncodedTransactionData()]; + const rawResults = await testProxyContract.batchExecute(calls).callAsync(); expect(rawResults.length).to.equal(1); - const returnValues = [testContract.echo.getABIDecodedReturnData(rawResults[0])]; + const returnValues = [testContract.getABIDecodedReturnData<{}>('echo', rawResults[0])]; expect(returnValues[0]).to.equal(testString); }); it('should call multiple functions and return their outputs', async () => { const calls = [ - testContract.echo.getABIEncodedTransactionData(testString), - testContract.doMath.getABIEncodedTransactionData(new BigNumber(2), new BigNumber(1)), + testContract.echo(testString).getABIEncodedTransactionData(), + testContract.doMath(new BigNumber(2), new BigNumber(1)).getABIEncodedTransactionData(), ]; - const rawResults = await testProxyContract.batchExecute.callAsync(calls); + const rawResults = await testProxyContract.batchExecute(calls).callAsync(); expect(rawResults.length).to.equal(2); const returnValues = [ - testContract.echo.getABIDecodedReturnData(rawResults[0]), - testContract.doMath.getABIDecodedReturnData(rawResults[1]), + testContract.getABIDecodedReturnData('echo', rawResults[0]), + testContract.getABIDecodedReturnData('doMath', rawResults[1]), ]; expect(returnValues[0]).to.equal(testString); expect(returnValues[1][0]).to.bignumber.equal(new BigNumber(3)); @@ -192,20 +191,20 @@ blockchainTests.resets('StakingProxy unit tests', env => { it('should revert if a call reverts', async () => { const calls = [ - testContract.echo.getABIEncodedTransactionData(testString), - testContract.die.getABIEncodedTransactionData(), - testContract.doMath.getABIEncodedTransactionData(new BigNumber(2), new BigNumber(1)), + testContract.echo(testString).getABIEncodedTransactionData(), + testContract.die().getABIEncodedTransactionData(), + testContract.doMath(new BigNumber(2), new BigNumber(1)).getABIEncodedTransactionData(), ]; - const tx = testProxyContract.batchExecute.callAsync(calls); + const tx = testProxyContract.batchExecute(calls).callAsync(); const expectedError = testRevertString; return expect(tx).to.revertWith(expectedError); }); it('should revert if no staking contract is attached', async () => { - await testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({ from: authorizedAddress }); - const calls = [testContract.echo.getABIEncodedTransactionData(testString)]; + await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress }); + const calls = [testContract.echo(testString).getABIEncodedTransactionData()]; - const tx = testProxyContract.batchExecute.callAsync(calls); + const tx = testProxyContract.batchExecute(calls).callAsync(); const expectedError = new StakingRevertErrors.ProxyDestinationCannotBeNilError(); return expect(tx).to.revertWith(expectedError); }); @@ -220,16 +219,16 @@ blockchainTests.resets('StakingProxy unit tests', env => { minimumPoolStake: new BigNumber(100), }; it('should not revert if all storage params are valid', async () => { - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(validStorageParams); - await testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(validStorageParams).awaitTransactionSuccessAsync(); + await testProxyContract.assertValidStorageParams().callAsync(); }); it('should revert if `epochDurationInSeconds` is less than 5 days', async () => { const invalidStorageParams = { ...validStorageParams, epochDurationInSeconds: new BigNumber(0), }; - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams); - const tx = testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); + const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration, ); @@ -240,8 +239,8 @@ blockchainTests.resets('StakingProxy unit tests', env => { ...validStorageParams, epochDurationInSeconds: new BigNumber(stakingConstants.ONE_DAY_IN_SECONDS * 31), }; - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams); - const tx = testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); + const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration, ); @@ -253,8 +252,8 @@ blockchainTests.resets('StakingProxy unit tests', env => { cobbDouglasAlphaNumerator: new BigNumber(2), cobbDouglasAlphaDenominator: new BigNumber(1), }; - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams); - const tx = testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); + const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha, ); @@ -265,8 +264,8 @@ blockchainTests.resets('StakingProxy unit tests', env => { ...validStorageParams, cobbDouglasAlphaDenominator: new BigNumber(0), }; - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams); - const tx = testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); + const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha, ); @@ -277,8 +276,8 @@ blockchainTests.resets('StakingProxy unit tests', env => { ...validStorageParams, rewardDelegatedStakeWeight: new BigNumber(constants.PPM_DENOMINATOR + 1), }; - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams); - const tx = testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); + const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight, ); @@ -289,8 +288,8 @@ blockchainTests.resets('StakingProxy unit tests', env => { ...validStorageParams, minimumPoolStake: new BigNumber(1), }; - await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams); - const tx = testProxyContract.assertValidStorageParams.callAsync(); + await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync(); + const tx = testProxyContract.assertValidStorageParams().callAsync(); const expectedError = new StakingRevertErrors.InvalidParamValueError( StakingRevertErrors.InvalidParamValueErrorCodes.InvalidMinimumPoolStake, ); diff --git a/contracts/staking/test/unit_tests/zrx_vault_test.ts b/contracts/staking/test/unit_tests/zrx_vault_test.ts index 031a78ef83..099f3e5fda 100644 --- a/contracts/staking/test/unit_tests/zrx_vault_test.ts +++ b/contracts/staking/test/unit_tests/zrx_vault_test.ts @@ -48,7 +48,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { zrxProxyAddress = erc20ProxyContract.address; // deploy zrx token const [zrxTokenContract] = await erc20Wrapper.deployDummyTokensAsync(1, constants.DUMMY_TOKEN_DECIMALS); - zrxAssetData = await devUtils.encodeERC20AssetData.callAsync(zrxTokenContract.address); + zrxAssetData = await devUtils.encodeERC20AssetData(zrxTokenContract.address).callAsync(); await erc20Wrapper.setBalancesAndAllowancesAsync(); @@ -61,10 +61,10 @@ blockchainTests.resets('ZrxVault unit tests', env => { zrxTokenContract.address, ); - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(owner); + await zrxVault.addAuthorizedAddress(owner).awaitTransactionSuccessAsync(); // configure erc20 proxy to accept calls from zrx vault - await erc20ProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(zrxVault.address); + await erc20ProxyContract.addAuthorizedAddress(zrxVault.address).awaitTransactionSuccessAsync(); }); enum ZrxTransfer { @@ -88,7 +88,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { expect(eventArgs[0].staker).to.equal(staker); expect(eventArgs[0].amount).to.bignumber.equal(amount); - const newVaultBalance = await zrxVault.balanceOf.callAsync(staker); + const newVaultBalance = await zrxVault.balanceOf(staker).callAsync(); const newTokenBalance = await erc20Wrapper.getBalanceAsync(staker, zrxAssetData); const [expectedVaultBalance, expectedTokenBalance] = transferType === ZrxTransfer.Deposit @@ -110,13 +110,13 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); expect(eventArgs.length).to.equal(1); expect(eventArgs[0].stakingProxyAddress).to.equal(newProxy); - const actualAddress = await zrxVault.stakingProxyAddress.callAsync(); + const actualAddress = await zrxVault.stakingProxyAddress().callAsync(); expect(actualAddress).to.equal(newProxy); } it('Owner can set the ZRX proxy', async () => { const newProxy = nonOwnerAddresses[0]; - const receipt = await zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, { + const receipt = await zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({ from: owner, }); const eventArgs = filterLogsToArguments(receipt.logs, 'ZrxProxySet'); @@ -125,8 +125,8 @@ blockchainTests.resets('ZrxVault unit tests', env => { }); it('Authorized address can set the ZRX proxy', async () => { const [authorized, newProxy] = nonOwnerAddresses; - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - const receipt = await zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, { + await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + const receipt = await zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({ from: authorized, }); const eventArgs = filterLogsToArguments(receipt.logs, 'ZrxProxySet'); @@ -135,7 +135,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { }); it('Non-authorized address cannot set the ZRX proxy', async () => { const [notAuthorized, newProxy] = nonOwnerAddresses; - const tx = zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, { + const tx = zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({ from: notAuthorized, }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorized); @@ -143,27 +143,27 @@ blockchainTests.resets('ZrxVault unit tests', env => { }); it('Owner can set the staking proxy', async () => { const newProxy = nonOwnerAddresses[0]; - const receipt = await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(newProxy, { + const receipt = await zrxVault.setStakingProxy(newProxy).awaitTransactionSuccessAsync({ from: owner, }); await verifyStakingProxySetAsync(receipt, newProxy); }); it('Authorized address can set the staking proxy', async () => { const [authorized, newProxy] = nonOwnerAddresses; - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - const receipt = await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(newProxy, { + await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + const receipt = await zrxVault.setStakingProxy(newProxy).awaitTransactionSuccessAsync({ from: authorized, }); await verifyStakingProxySetAsync(receipt, newProxy); }); it('Non-authorized address cannot set the staking proxy', async () => { const [notAuthorized, newProxy] = nonOwnerAddresses; - const tx = zrxVault.setStakingProxy.awaitTransactionSuccessAsync(newProxy, { + const tx = zrxVault.setStakingProxy(newProxy).awaitTransactionSuccessAsync({ from: notAuthorized, }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorized); expect(tx).to.revertWith(expectedError); - const actualAddress = await zrxVault.stakingProxyAddress.callAsync(); + const actualAddress = await zrxVault.stakingProxyAddress().callAsync(); expect(actualAddress).to.equal(stakingConstants.NIL_ADDRESS); }); }); @@ -175,26 +175,24 @@ blockchainTests.resets('ZrxVault unit tests', env => { before(async () => { [staker, stakingProxy] = nonOwnerAddresses; - await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy, { from: owner }); - await zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(10), { + await zrxVault.setStakingProxy(stakingProxy).awaitTransactionSuccessAsync({ from: owner }); + await zrxVault.depositFrom(staker, new BigNumber(10)).awaitTransactionSuccessAsync({ from: stakingProxy, }); }); beforeEach(async () => { - initialVaultBalance = await zrxVault.balanceOf.callAsync(staker); + initialVaultBalance = await zrxVault.balanceOf(staker).callAsync(); initialTokenBalance = await erc20Wrapper.getBalanceAsync(staker, zrxAssetData); }); describe('Deposit', () => { it('Staking proxy can deposit zero amount on behalf of staker', async () => { - const receipt = await zrxVault.depositFrom.awaitTransactionSuccessAsync( - staker, - constants.ZERO_AMOUNT, - { + const receipt = await zrxVault + .depositFrom(staker, constants.ZERO_AMOUNT) + .awaitTransactionSuccessAsync({ from: stakingProxy, - }, - ); + }); await verifyTransferPostconditionsAsync( ZrxTransfer.Deposit, staker, @@ -205,7 +203,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it('Staking proxy can deposit nonzero amount on behalf of staker', async () => { - const receipt = await zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), { + const receipt = await zrxVault.depositFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({ from: stakingProxy, }); await verifyTransferPostconditionsAsync( @@ -218,13 +216,11 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it('Staking proxy can deposit entire ZRX balance on behalf of staker', async () => { - const receipt = await zrxVault.depositFrom.awaitTransactionSuccessAsync( - staker, - initialTokenBalance, - { + const receipt = await zrxVault + .depositFrom(staker, initialTokenBalance) + .awaitTransactionSuccessAsync({ from: stakingProxy, - }, - ); + }); await verifyTransferPostconditionsAsync( ZrxTransfer.Deposit, staker, @@ -235,7 +231,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it("Reverts if attempting to deposit more than staker's ZRX balance", async () => { - const tx = zrxVault.depositFrom.sendTransactionAsync(staker, initialTokenBalance.plus(1), { + const tx = zrxVault.depositFrom(staker, initialTokenBalance.plus(1)).sendTransactionAsync({ from: stakingProxy, }); expectTransactionFailedAsync(tx, RevertReason.TransferFailed); @@ -243,13 +239,11 @@ blockchainTests.resets('ZrxVault unit tests', env => { }); describe('Withdrawal', () => { it('Staking proxy can withdraw zero amount on behalf of staker', async () => { - const receipt = await zrxVault.withdrawFrom.awaitTransactionSuccessAsync( - staker, - constants.ZERO_AMOUNT, - { + const receipt = await zrxVault + .withdrawFrom(staker, constants.ZERO_AMOUNT) + .awaitTransactionSuccessAsync({ from: stakingProxy, - }, - ); + }); await verifyTransferPostconditionsAsync( ZrxTransfer.Withdrawal, staker, @@ -260,7 +254,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it('Staking proxy can withdraw nonzero amount on behalf of staker', async () => { - const receipt = await zrxVault.withdrawFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), { + const receipt = await zrxVault.withdrawFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({ from: stakingProxy, }); await verifyTransferPostconditionsAsync( @@ -273,13 +267,11 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it('Staking proxy can withdraw entire vault balance on behalf of staker', async () => { - const receipt = await zrxVault.withdrawFrom.awaitTransactionSuccessAsync( - staker, - initialVaultBalance, - { + const receipt = await zrxVault + .withdrawFrom(staker, initialVaultBalance) + .awaitTransactionSuccessAsync({ from: stakingProxy, - }, - ); + }); await verifyTransferPostconditionsAsync( ZrxTransfer.Withdrawal, staker, @@ -290,7 +282,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it("Reverts if attempting to withdraw more than staker's vault balance", async () => { - const tx = zrxVault.withdrawFrom.awaitTransactionSuccessAsync(staker, initialVaultBalance.plus(1), { + const tx = zrxVault.withdrawFrom(staker, initialVaultBalance.plus(1)).awaitTransactionSuccessAsync({ from: stakingProxy, }); const expectedError = new SafeMathRevertErrors.Uint256BinOpError( @@ -316,38 +308,38 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); expect(eventArgs.length).to.equal(1); expect(eventArgs[0].sender).to.equal(sender); - expect(await zrxVault.isInCatastrophicFailure.callAsync()).to.be.true(); + expect(await zrxVault.isInCatastrophicFailure().callAsync()).to.be.true(); } it('Owner can turn on Catastrophic Failure Mode', async () => { - const receipt = await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ from: owner }); + const receipt = await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: owner }); await verifyCatastrophicFailureModeAsync(owner, receipt); }); it('Authorized address can turn on Catastrophic Failure Mode', async () => { const authorized = nonOwnerAddresses[0]; - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - const receipt = await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ + await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + const receipt = await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: authorized, }); await verifyCatastrophicFailureModeAsync(authorized, receipt); }); it('Non-authorized address cannot turn on Catastrophic Failure Mode', async () => { const notAuthorized = nonOwnerAddresses[0]; - const tx = zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ + const tx = zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: notAuthorized, }); const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorized); expect(tx).to.revertWith(expectedError); - expect(await zrxVault.isInCatastrophicFailure.callAsync()).to.be.false(); + expect(await zrxVault.isInCatastrophicFailure().callAsync()).to.be.false(); }); it('Catastrophic Failure Mode can only be turned on once', async () => { const authorized = nonOwnerAddresses[0]; - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ + await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: authorized, }); const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError(); - return expect(zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync()).to.revertWith( + return expect(zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync()).to.revertWith( expectedError, ); }); @@ -361,41 +353,41 @@ blockchainTests.resets('ZrxVault unit tests', env => { before(async () => { [staker, stakingProxy, ...nonOwnerAddresses] = nonOwnerAddresses; - await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy, { from: owner }); - await zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(10), { + await zrxVault.setStakingProxy(stakingProxy).awaitTransactionSuccessAsync({ from: owner }); + await zrxVault.depositFrom(staker, new BigNumber(10)).awaitTransactionSuccessAsync({ from: stakingProxy, }); - await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ from: owner }); + await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: owner }); }); beforeEach(async () => { - initialVaultBalance = await zrxVault.balanceOf.callAsync(staker); + initialVaultBalance = await zrxVault.balanceOf(staker).callAsync(); initialTokenBalance = await erc20Wrapper.getBalanceAsync(staker, zrxAssetData); }); it('Owner cannot set the ZRX proxy', async () => { const newProxy = nonOwnerAddresses[0]; - const tx = zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, { + const tx = zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({ from: owner, }); const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError(); expect(tx).to.revertWith(expectedError); - const actualAddress = await zrxVault.zrxAssetProxy.callAsync(); + const actualAddress = await zrxVault.zrxAssetProxy().callAsync(); expect(actualAddress).to.equal(zrxProxyAddress); }); it('Authorized address cannot set the ZRX proxy', async () => { const [authorized, newProxy] = nonOwnerAddresses; - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner }); - const tx = zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, { + await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner }); + const tx = zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({ from: authorized, }); const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError(); expect(tx).to.revertWith(expectedError); - const actualAddress = await zrxVault.zrxAssetProxy.callAsync(); + const actualAddress = await zrxVault.zrxAssetProxy().callAsync(); expect(actualAddress).to.equal(zrxProxyAddress); }); it('Staking proxy cannot deposit ZRX', async () => { - const tx = zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), { + const tx = zrxVault.depositFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({ from: stakingProxy, }); const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError(); @@ -404,14 +396,14 @@ blockchainTests.resets('ZrxVault unit tests', env => { describe('Withdrawal', () => { it('Staking proxy cannot call `withdrawFrom`', async () => { - const tx = zrxVault.withdrawFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), { + const tx = zrxVault.withdrawFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({ from: stakingProxy, }); const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError(); expect(tx).to.revertWith(expectedError); }); it('Staker can withdraw all their ZRX', async () => { - const receipt = await zrxVault.withdrawAllFrom.awaitTransactionSuccessAsync(staker, { + const receipt = await zrxVault.withdrawAllFrom(staker).awaitTransactionSuccessAsync({ from: staker, }); await verifyTransferPostconditionsAsync( @@ -424,7 +416,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it('Owner can withdraw ZRX on behalf of a staker', async () => { - const receipt = await zrxVault.withdrawAllFrom.awaitTransactionSuccessAsync(staker, { + const receipt = await zrxVault.withdrawAllFrom(staker).awaitTransactionSuccessAsync({ from: owner, }); await verifyTransferPostconditionsAsync( @@ -437,7 +429,7 @@ blockchainTests.resets('ZrxVault unit tests', env => { ); }); it('Non-owner address can withdraw ZRX on behalf of a staker', async () => { - const receipt = await zrxVault.withdrawAllFrom.awaitTransactionSuccessAsync(staker, { + const receipt = await zrxVault.withdrawAllFrom(staker).awaitTransactionSuccessAsync({ from: nonOwnerAddresses[0], }); await verifyTransferPostconditionsAsync( diff --git a/contracts/staking/test/utils/api_wrapper.ts b/contracts/staking/test/utils/api_wrapper.ts index f67c80bc84..3572168a40 100644 --- a/contracts/staking/test/utils/api_wrapper.ts +++ b/contracts/staking/test/utils/api_wrapper.ts @@ -36,7 +36,7 @@ export class StakingApiWrapper { fastForwardToNextEpochAsync: async (): Promise => { // increase timestamp of next block by how many seconds we need to // get to the next epoch. - const epochEndTime = await this.stakingContract.getCurrentEpochEarliestEndTimeInSeconds.callAsync(); + const epochEndTime = await this.stakingContract.getCurrentEpochEarliestEndTimeInSeconds().callAsync(); const lastBlockTime = await this._web3Wrapper.getBlockTimestampAsync('latest'); const dt = Math.max(0, epochEndTime.minus(lastBlockTime).toNumber()); await this._web3Wrapper.increaseTimeAsync(dt); @@ -49,7 +49,7 @@ export class StakingApiWrapper { const endOfEpochInfo = await this.utils.endEpochAsync(); const allLogs = [] as DecodedLogs; for (const poolId of endOfEpochInfo.activePoolIds) { - const receipt = await this.stakingContract.finalizePool.awaitTransactionSuccessAsync(poolId); + const receipt = await this.stakingContract.finalizePool(poolId).awaitTransactionSuccessAsync(); allLogs.splice(allLogs.length, 0, ...(receipt.logs as DecodedLogs)); } return allLogs; @@ -57,7 +57,7 @@ export class StakingApiWrapper { endEpochAsync: async (): Promise => { const activePoolIds = await this.utils.findActivePoolIdsAsync(); - const receipt = await this.stakingContract.endEpoch.awaitTransactionSuccessAsync(); + const receipt = await this.stakingContract.endEpoch().awaitTransactionSuccessAsync(); const [epochEndedEvent] = filterLogsToArguments( receipt.logs, TestStakingEvents.EpochEnded, @@ -72,7 +72,7 @@ export class StakingApiWrapper { }, findActivePoolIdsAsync: async (epoch?: number): Promise => { - const _epoch = epoch !== undefined ? epoch : await this.stakingContract.currentEpoch.callAsync(); + const _epoch = epoch !== undefined ? epoch : await this.stakingContract.currentEpoch().callAsync(); const events = filterLogsToArguments( await this.stakingContract.getLogsAsync( TestStakingEvents.StakingPoolEarnedRewardsInEpoch, @@ -90,18 +90,16 @@ export class StakingApiWrapper { operatorShare: number, addOperatorAsMaker: boolean, ): Promise => { - const txReceipt = await this.stakingContract.createStakingPool.awaitTransactionSuccessAsync( - operatorShare, - addOperatorAsMaker, - { from: operatorAddress }, - ); + const txReceipt = await this.stakingContract + .createStakingPool(operatorShare, addOperatorAsMaker) + .awaitTransactionSuccessAsync({ from: operatorAddress }); const createStakingPoolLog = txReceipt.logs[0]; const poolId = (createStakingPoolLog as any).args.poolId; return poolId; }, getZrxTokenBalanceOfZrxVaultAsync: async (): Promise => { - return this.zrxTokenContract.balanceOf.callAsync(this.zrxVaultContract.address); + return this.zrxTokenContract.balanceOf(this.zrxVaultContract.address).callAsync(); }, setParamsAsync: async (params: Partial): Promise => { @@ -109,20 +107,22 @@ export class StakingApiWrapper { ...stakingConstants.DEFAULT_PARAMS, ...params, }; - return this.stakingContract.setParams.awaitTransactionSuccessAsync( - new BigNumber(_params.epochDurationInSeconds), - new BigNumber(_params.rewardDelegatedStakeWeight), - new BigNumber(_params.minimumPoolStake), - new BigNumber(_params.cobbDouglasAlphaNumerator), - new BigNumber(_params.cobbDouglasAlphaDenominator), - ); + return this.stakingContract + .setParams( + new BigNumber(_params.epochDurationInSeconds), + new BigNumber(_params.rewardDelegatedStakeWeight), + new BigNumber(_params.minimumPoolStake), + new BigNumber(_params.cobbDouglasAlphaNumerator), + new BigNumber(_params.cobbDouglasAlphaDenominator), + ) + .awaitTransactionSuccessAsync(); }, getAvailableRewardsBalanceAsync: async (): Promise => { const [ethBalance, wethBalance, reservedRewards] = await Promise.all([ this._web3Wrapper.getBalanceInWeiAsync(this.stakingProxyContract.address), - this.wethContract.balanceOf.callAsync(this.stakingProxyContract.address), - this.stakingContract.wethReservedForPoolRewards.callAsync(), + this.wethContract.balanceOf(this.stakingProxyContract.address).callAsync(), + this.stakingContract.wethReservedForPoolRewards().callAsync(), ]); return BigNumber.sum(ethBalance, wethBalance).minus(reservedRewards); }, @@ -138,7 +138,7 @@ export class StakingApiWrapper { 'wethProxyAddress', 'zrxVaultAddress', ], - await this.stakingContract.getParams.callAsync(), + await this.stakingContract.getParams().callAsync(), ) as any) as StakingParams; }, @@ -150,15 +150,17 @@ export class StakingApiWrapper { totalStake: BigNumber, ): Promise => { const { cobbDouglasAlphaNumerator, cobbDouglasAlphaDenominator } = await this.utils.getParamsAsync(); - return this.cobbDouglasContract.cobbDouglas.callAsync( - totalRewards, - ownerFees, - totalFees, - ownerStake, - totalStake, - new BigNumber(cobbDouglasAlphaNumerator), - new BigNumber(cobbDouglasAlphaDenominator), - ); + return this.cobbDouglasContract + .cobbDouglas( + totalRewards, + ownerFees, + totalFees, + ownerStake, + totalStake, + new BigNumber(cobbDouglasAlphaNumerator), + new BigNumber(cobbDouglasAlphaDenominator), + ) + .callAsync(); }, }; @@ -232,7 +234,7 @@ export async function deployAndConfigureContractsAsync( zrxTokenContract.address, ); - await zrxVaultContract.addAuthorizedAddress.awaitTransactionSuccessAsync(ownerAddress); + await zrxVaultContract.addAuthorizedAddress(ownerAddress).awaitTransactionSuccessAsync(); // deploy staking contract const stakingContract = await TestStakingContract.deployFrom0xArtifactAsync( @@ -253,7 +255,7 @@ export async function deployAndConfigureContractsAsync( stakingContract.address, ); - await stakingProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(ownerAddress); + await stakingProxyContract.addAuthorizedAddress(ownerAddress).awaitTransactionSuccessAsync(); // deploy cobb douglas contract const cobbDouglasContract = await TestCobbDouglasContract.deployFrom0xArtifactAsync( @@ -264,9 +266,9 @@ export async function deployAndConfigureContractsAsync( ); // configure erc20 proxy to accept calls from zrx vault - await erc20ProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(zrxVaultContract.address); + await erc20ProxyContract.addAuthorizedAddress(zrxVaultContract.address).awaitTransactionSuccessAsync(); // set staking proxy contract in zrx vault - await zrxVaultContract.setStakingProxy.awaitTransactionSuccessAsync(stakingProxyContract.address); + await zrxVaultContract.setStakingProxy(stakingProxyContract.address).awaitTransactionSuccessAsync(); return new StakingApiWrapper( env, ownerAddress, diff --git a/contracts/staking/test/utils/cumulative_reward_tracking_simulation.ts b/contracts/staking/test/utils/cumulative_reward_tracking_simulation.ts index bcab706e61..e9208e71d5 100644 --- a/contracts/staking/test/utils/cumulative_reward_tracking_simulation.ts +++ b/contracts/staking/test/utils/cumulative_reward_tracking_simulation.ts @@ -74,9 +74,9 @@ export class CumulativeRewardTrackingSimulation { public async deployAndConfigureTestContractsAsync(env: BlockchainTestsEnvironment): Promise { // set exchange address - await this._stakingApiWrapper.stakingContract.addExchangeAddress.awaitTransactionSuccessAsync( - this._exchangeAddress, - ); + await this._stakingApiWrapper.stakingContract + .addExchangeAddress(this._exchangeAddress) + .awaitTransactionSuccessAsync(); this._testCumulativeRewardTrackingContract = await TestCumulativeRewardTrackingContract.deployFrom0xArtifactAsync( artifacts.TestCumulativeRewardTracking, env.provider, @@ -100,9 +100,9 @@ export class CumulativeRewardTrackingSimulation { expectedTestLogs: TestLog[], ): Promise { await this._executeActionsAsync(initActions); - await this._stakingApiWrapper.stakingProxyContract.attachStakingContract.awaitTransactionSuccessAsync( - this.getTestCumulativeRewardTrackingContract().address, - ); + await this._stakingApiWrapper.stakingProxyContract + .attachStakingContract(this.getTestCumulativeRewardTrackingContract().address) + .awaitTransactionSuccessAsync(); const testLogs = await this._executeActionsAsync(testActions); CumulativeRewardTrackingSimulation._assertTestLogs(expectedTestLogs, testLogs); } @@ -118,41 +118,38 @@ export class CumulativeRewardTrackingSimulation { break; case TestAction.Delegate: - await this._stakingApiWrapper.stakingContract.stake.sendTransactionAsync(this._amountToStake, { + await this._stakingApiWrapper.stakingContract.stake(this._amountToStake).sendTransactionAsync({ from: this._staker, }); - receipt = await this._stakingApiWrapper.stakingContract.moveStake.awaitTransactionSuccessAsync( - new StakeInfo(StakeStatus.Undelegated), - new StakeInfo(StakeStatus.Delegated, this._poolId), - this._amountToStake, - { from: this._staker }, - ); + receipt = await this._stakingApiWrapper.stakingContract + .moveStake( + new StakeInfo(StakeStatus.Undelegated), + new StakeInfo(StakeStatus.Delegated, this._poolId), + this._amountToStake, + ) + .awaitTransactionSuccessAsync({ from: this._staker }); break; case TestAction.Undelegate: - receipt = await this._stakingApiWrapper.stakingContract.moveStake.awaitTransactionSuccessAsync( - new StakeInfo(StakeStatus.Delegated, this._poolId), - new StakeInfo(StakeStatus.Undelegated), - this._amountToStake, - { from: this._staker }, - ); + receipt = await this._stakingApiWrapper.stakingContract + .moveStake( + new StakeInfo(StakeStatus.Delegated, this._poolId), + new StakeInfo(StakeStatus.Undelegated), + this._amountToStake, + ) + .awaitTransactionSuccessAsync({ from: this._staker }); break; case TestAction.PayProtocolFee: - receipt = await this._stakingApiWrapper.stakingContract.payProtocolFee.awaitTransactionSuccessAsync( - this._poolOperator, - this._takerAddress, - this._protocolFee, - { from: this._exchangeAddress, value: this._protocolFee }, - ); + receipt = await this._stakingApiWrapper.stakingContract + .payProtocolFee(this._poolOperator, this._takerAddress, this._protocolFee) + .awaitTransactionSuccessAsync({ from: this._exchangeAddress, value: this._protocolFee }); break; case TestAction.CreatePool: - receipt = await this._stakingApiWrapper.stakingContract.createStakingPool.awaitTransactionSuccessAsync( - 0, - true, - { from: this._poolOperator }, - ); + receipt = await this._stakingApiWrapper.stakingContract + .createStakingPool(0, true) + .awaitTransactionSuccessAsync({ from: this._poolOperator }); const createStakingPoolLog = receipt.logs[0]; // tslint:disable-next-line no-unnecessary-type-assertion this._poolId = (createStakingPoolLog as DecodedLogEntry).args.poolId; diff --git a/contracts/test-utils/CHANGELOG.json b/contracts/test-utils/CHANGELOG.json index a3bfaa5882..4616928b39 100644 --- a/contracts/test-utils/CHANGELOG.json +++ b/contracts/test-utils/CHANGELOG.json @@ -5,6 +5,10 @@ { "note": "Drastically reduced bundle size by adding .npmignore, only exporting specific artifacts/wrappers/utils", "pr": 2330 + }, + { + "note": "Remove TransactionHelper and MutatorContractFunction", + "pr": 2325 } ] }, diff --git a/contracts/test-utils/package.json b/contracts/test-utils/package.json index dc3ecef751..c6d4f2669b 100644 --- a/contracts/test-utils/package.json +++ b/contracts/test-utils/package.json @@ -42,6 +42,7 @@ "typescript": "3.0.1" }, "dependencies": { + "@0x/base-contract": "^5.5.0-beta.0", "@0x/dev-utils": "^2.4.0-beta.1", "@0x/order-utils": "^8.5.0-beta.1", "@0x/sol-coverage": "^3.1.0-beta.1", diff --git a/contracts/test-utils/src/index.ts b/contracts/test-utils/src/index.ts index a2ba137c0a..75d9f26840 100644 --- a/contracts/test-utils/src/index.ts +++ b/contracts/test-utils/src/index.ts @@ -26,7 +26,6 @@ export { randomAddress } from './address_utils'; export { OrderFactory } from './order_factory'; export { bytes32Values, testCombinatoriallyWithReferenceFunc, uint256Values } from './combinatorial_utils'; export { TransactionFactory } from './transaction_factory'; -export { MutatorContractFunction, TransactionHelper } from './transaction_helper'; export { testWithReferenceFuncAsync } from './test_with_reference'; export { hexConcat, diff --git a/contracts/test-utils/src/transaction_helper.ts b/contracts/test-utils/src/transaction_helper.ts deleted file mode 100644 index e861e389f7..0000000000 --- a/contracts/test-utils/src/transaction_helper.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { Web3Wrapper } from '@0x/web3-wrapper'; -import { ContractArtifact, TransactionReceipt } from 'ethereum-types'; - -import { LogDecoder } from './log_decoder'; - -type AsyncFunction = (...args: TArgs) => Promise; - -interface ContractArtifacts { - [contractName: string]: ContractArtifact; -} - -export interface MutatorContractFunction< - TCallAsyncArgs extends any[], - TAwaitTransactionSuccessAsyncArgs extends any[], - TCallAsyncResult -> { - callAsync: AsyncFunction; - sendTransactionAsync: AsyncFunction; -} - -/** - * Helper class for performing non-constant contract functions calls. - */ -export class TransactionHelper { - public readonly logDecoder: LogDecoder; - - constructor(web3Wrapper: Web3Wrapper, artifacts: ContractArtifacts) { - this.logDecoder = new LogDecoder(web3Wrapper, artifacts); - } - - /** - * Call a non-constant contract function `contractFunction`, passing `args`. - * This will first perform an 'eth_call' (read-only) call in order to - * retrieve the return value, then a 'sendTransaction' to actually modify - * the state. Returns a tuple of the return value amd receipt, with decoded - * logs. - */ - public async getResultAndReceiptAsync< - TCallAsyncArgs extends any[], - TAwaitTransactionSuccessAsyncArgs extends any[], - TCallAsyncResult - >( - contractFunction: MutatorContractFunction, - // tslint:disable-next-line: trailing-comma - ...args: TAwaitTransactionSuccessAsyncArgs - ): Promise<[TCallAsyncResult, TransactionReceipt]> { - // HACK(dorothy-zbornak): We take advantage of the general rule that - // the parameters for `callAsync()` are a subset of the - // parameters for `sendTransactionAsync()`. - const result = await contractFunction.callAsync(...((args as any) as TCallAsyncArgs)); - const receipt = await this.logDecoder.getTxWithDecodedLogsAsync( - await contractFunction.sendTransactionAsync(...args), - ); - return [result, receipt]; - } -} diff --git a/contracts/tests/test/dev-utils/lib_asset_data.ts b/contracts/tests/test/dev-utils/lib_asset_data.ts index 67c1277162..ea54360bc4 100644 --- a/contracts/tests/test/dev-utils/lib_asset_data.ts +++ b/contracts/tests/test/dev-utils/lib_asset_data.ts @@ -135,11 +135,11 @@ describe('LibAssetData', () => { artifacts, ); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(multiAssetProxy.address); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(staticCallProxy.address); + await exchange.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(multiAssetProxy.address).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(staticCallProxy.address).awaitTransactionSuccessAsync(); libAssetData = await LibAssetDataContract.deployFrom0xArtifactAsync( artifacts.LibAssetData, @@ -181,7 +181,7 @@ describe('LibAssetData', () => { const transactionMinedPromises = []; for (let i = 0; i < numberOfERC721Tokens; i++) { transactionMinedPromises.push( - erc721Token.mint.awaitTransactionSuccessAsync(tokenOwnerAddress, firstERC721TokenId.plus(i - 1)), + erc721Token.mint(tokenOwnerAddress, firstERC721TokenId.plus(i - 1)).awaitTransactionSuccessAsync(), ); } await Promise.all(transactionMinedPromises); @@ -195,16 +195,14 @@ describe('LibAssetData', () => { const logDecoder = new LogDecoder(web3Wrapper, erc1155Artifacts); const transactionReceipt = await logDecoder.getTxWithDecodedLogsAsync( - await erc1155Token.create.sendTransactionAsync('uri:Dummy', /*isNonFungible:*/ false), + await erc1155Token.create('uri:Dummy', /*isNonFungible:*/ false).sendTransactionAsync(), ); // tslint:disable-next-line no-unnecessary-type-assertion erc1155TokenId = (transactionReceipt.logs[0] as LogWithDecodedArgs).args.id; - await erc1155Token.mintFungible.awaitTransactionSuccessAsync( - erc1155TokenId, - [tokenOwnerAddress], - [new BigNumber(1)], - ); + await erc1155Token + .mintFungible(erc1155TokenId, [tokenOwnerAddress], [new BigNumber(1)]) + .awaitTransactionSuccessAsync(); }); after(async () => { @@ -232,17 +230,17 @@ describe('LibAssetData', () => { ]; for (const [assetData, proxyId] of assetDataScenarios) { - expect(await libAssetData.decodeAssetProxyId.callAsync(assetData)).to.equal(proxyId); + expect(await libAssetData.decodeAssetProxyId(assetData).callAsync()).to.equal(proxyId); } }); it('should encode ERC20 asset data', async () => { - expect(await libAssetData.encodeERC20AssetData.callAsync(KNOWN_ERC20_ENCODING.address)).to.equal( + expect(await libAssetData.encodeERC20AssetData(KNOWN_ERC20_ENCODING.address).callAsync()).to.equal( KNOWN_ERC20_ENCODING.assetData, ); }); it('should decode ERC20 asset data', async () => { - expect(await libAssetData.decodeERC20AssetData.callAsync(KNOWN_ERC20_ENCODING.assetData)).to.deep.equal([ + expect(await libAssetData.decodeERC20AssetData(KNOWN_ERC20_ENCODING.assetData).callAsync()).to.deep.equal([ AssetProxyId.ERC20, KNOWN_ERC20_ENCODING.address, ]); @@ -250,56 +248,57 @@ describe('LibAssetData', () => { it('should encode ERC721 asset data', async () => { expect( - await libAssetData.encodeERC721AssetData.callAsync( - KNOWN_ERC721_ENCODING.address, - KNOWN_ERC721_ENCODING.tokenId, - ), + await libAssetData + .encodeERC721AssetData(KNOWN_ERC721_ENCODING.address, KNOWN_ERC721_ENCODING.tokenId) + .callAsync(), ).to.equal(KNOWN_ERC721_ENCODING.assetData); }); it('should decode ERC721 asset data', async () => { - expect(await libAssetData.decodeERC721AssetData.callAsync(KNOWN_ERC721_ENCODING.assetData)).to.deep.equal([ - AssetProxyId.ERC721, - KNOWN_ERC721_ENCODING.address, - KNOWN_ERC721_ENCODING.tokenId, - ]); + expect(await libAssetData.decodeERC721AssetData(KNOWN_ERC721_ENCODING.assetData).callAsync()).to.deep.equal( + [AssetProxyId.ERC721, KNOWN_ERC721_ENCODING.address, KNOWN_ERC721_ENCODING.tokenId], + ); }); it('should encode ERC1155 asset data', async () => { expect( - await libAssetData.encodeERC1155AssetData.callAsync( - KNOWN_ERC1155_ENCODING.tokenAddress, - KNOWN_ERC1155_ENCODING.tokenIds, - KNOWN_ERC1155_ENCODING.tokenValues, - KNOWN_ERC1155_ENCODING.callbackData, - ), + await libAssetData + .encodeERC1155AssetData( + KNOWN_ERC1155_ENCODING.tokenAddress, + KNOWN_ERC1155_ENCODING.tokenIds, + KNOWN_ERC1155_ENCODING.tokenValues, + KNOWN_ERC1155_ENCODING.callbackData, + ) + .callAsync(), ).to.equal(KNOWN_ERC1155_ENCODING.assetData); }); it('should decode ERC1155 asset data', async () => { - expect(await libAssetData.decodeERC1155AssetData.callAsync(KNOWN_ERC1155_ENCODING.assetData)).to.deep.equal( - [ - AssetProxyId.ERC1155, - KNOWN_ERC1155_ENCODING.tokenAddress, - KNOWN_ERC1155_ENCODING.tokenIds, - KNOWN_ERC1155_ENCODING.tokenValues, - KNOWN_ERC1155_ENCODING.callbackData, - ], - ); + expect( + await libAssetData.decodeERC1155AssetData(KNOWN_ERC1155_ENCODING.assetData).callAsync(), + ).to.deep.equal([ + AssetProxyId.ERC1155, + KNOWN_ERC1155_ENCODING.tokenAddress, + KNOWN_ERC1155_ENCODING.tokenIds, + KNOWN_ERC1155_ENCODING.tokenValues, + KNOWN_ERC1155_ENCODING.callbackData, + ]); }); it('should encode multiasset data', async () => { expect( - await libAssetData.encodeMultiAssetData.callAsync( - KNOWN_MULTI_ASSET_ENCODING.amounts, - KNOWN_MULTI_ASSET_ENCODING.nestedAssetData, - ), + await libAssetData + .encodeMultiAssetData( + KNOWN_MULTI_ASSET_ENCODING.amounts, + KNOWN_MULTI_ASSET_ENCODING.nestedAssetData, + ) + .callAsync(), ).to.equal(KNOWN_MULTI_ASSET_ENCODING.assetData); }); it('should decode multiasset data', async () => { expect( - await libAssetData.decodeMultiAssetData.callAsync(KNOWN_MULTI_ASSET_ENCODING.assetData), + await libAssetData.decodeMultiAssetData(KNOWN_MULTI_ASSET_ENCODING.assetData).callAsync(), ).to.deep.equal([ AssetProxyId.MultiAsset, KNOWN_MULTI_ASSET_ENCODING.amounts, @@ -309,17 +308,19 @@ describe('LibAssetData', () => { it('should encode StaticCall data', async () => { expect( - await libAssetData.encodeStaticCallAssetData.callAsync( - KNOWN_STATIC_CALL_ENCODING.staticCallTargetAddress, - KNOWN_STATIC_CALL_ENCODING.staticCallData, - KNOWN_STATIC_CALL_ENCODING.expectedReturnDataHash, - ), + await libAssetData + .encodeStaticCallAssetData( + KNOWN_STATIC_CALL_ENCODING.staticCallTargetAddress, + KNOWN_STATIC_CALL_ENCODING.staticCallData, + KNOWN_STATIC_CALL_ENCODING.expectedReturnDataHash, + ) + .callAsync(), ).to.equal(KNOWN_STATIC_CALL_ENCODING.assetData); }); it('should decode StaticCall data', async () => { expect( - await libAssetData.decodeStaticCallAssetData.callAsync(KNOWN_STATIC_CALL_ENCODING.assetData), + await libAssetData.decodeStaticCallAssetData(KNOWN_STATIC_CALL_ENCODING.assetData).callAsync(), ).to.deep.equal([ AssetProxyId.StaticCall, KNOWN_STATIC_CALL_ENCODING.staticCallTargetAddress, @@ -339,14 +340,14 @@ describe('LibAssetData', () => { ]; for (const data of assetData) { - await libAssetData.revertIfInvalidAssetData.callAsync(data); + await libAssetData.revertIfInvalidAssetData(data).callAsync(); } return; }); it('should revert for invalid assetProxyId', async () => { const badAssetData = '0x' + crypto.randomBytes(4).toString('hex') + constants.NULL_ADDRESS; - await expect(libAssetData.revertIfInvalidAssetData.callAsync(badAssetData)).to.eventually.be.rejectedWith( + await expect(libAssetData.revertIfInvalidAssetData(badAssetData).callAsync()).to.eventually.be.rejectedWith( StringRevertError, ); }); @@ -357,7 +358,7 @@ describe('LibAssetData', () => { for (const data of assetData) { const badData = data.substring(0, data.length - 2); // drop one byte but retain assetProxyId - await expect(libAssetData.revertIfInvalidAssetData.callAsync(badData)).to.eventually.be.rejectedWith( + await expect(libAssetData.revertIfInvalidAssetData(badData).callAsync()).to.eventually.be.rejectedWith( InvalidByteOperationError, ); } @@ -366,98 +367,98 @@ describe('LibAssetData', () => { describe('getBalance', () => { it('should query ERC20 balance by asset data', async () => { - const assetData = await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address); - expect(await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData)).to.bignumber.equal( + const assetData = await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(); + expect(await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync()).to.bignumber.equal( erc20TokenTotalSupply, ); }); it('should return 0 if ERC20 token does not exist', async () => { - const assetData = await libAssetData.encodeERC20AssetData.callAsync(constants.NULL_ADDRESS); - const balance = await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData); + const assetData = await libAssetData.encodeERC20AssetData(constants.NULL_ADDRESS).callAsync(); + const balance = await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync(); expect(balance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should query ERC721 balance by asset data', async () => { - const assetData = await libAssetData.encodeERC721AssetData.callAsync( - erc721Token.address, - firstERC721TokenId, - ); - expect(await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData)).to.bignumber.equal(1); + const assetData = await libAssetData + .encodeERC721AssetData(erc721Token.address, firstERC721TokenId) + .callAsync(); + expect(await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync()).to.bignumber.equal(1); }); it('should return 0 if ERC721 token does not exist', async () => { - const assetData = await libAssetData.encodeERC721AssetData.callAsync( - constants.NULL_ADDRESS, - firstERC721TokenId, - ); - const balance = await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData); + const assetData = await libAssetData + .encodeERC721AssetData(constants.NULL_ADDRESS, firstERC721TokenId) + .callAsync(); + const balance = await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync(); expect(balance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should query ERC1155 balances by asset data', async () => { - const assetData = await libAssetData.encodeERC1155AssetData.callAsync( - erc1155Token.address, - [erc1155TokenId], - [new BigNumber(1)], - constants.NULL_BYTES, - ); - expect(await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData)).to.bignumber.equal(1); + const assetData = await libAssetData + .encodeERC1155AssetData( + erc1155Token.address, + [erc1155TokenId], + [new BigNumber(1)], + constants.NULL_BYTES, + ) + .callAsync(); + expect(await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync()).to.bignumber.equal(1); }); it('should return 0 if ERC1155 token does not exist', async () => { - const assetData = await libAssetData.encodeERC1155AssetData.callAsync( - constants.NULL_ADDRESS, - [erc1155TokenId], - [new BigNumber(1)], - constants.NULL_BYTES, - ); - const balance = await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData); + const assetData = await libAssetData + .encodeERC1155AssetData( + constants.NULL_ADDRESS, + [erc1155TokenId], + [new BigNumber(1)], + constants.NULL_BYTES, + ) + .callAsync(); + const balance = await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync(); expect(balance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should query multi-asset batch balance by asset data', async () => { - const assetData = await libAssetData.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [ - await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address), - await libAssetData.encodeERC721AssetData.callAsync(erc721Token.address, firstERC721TokenId), - ], - ); - expect(await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData)).to.bignumber.equal( + const assetData = await libAssetData + .encodeMultiAssetData( + [new BigNumber(1), new BigNumber(1)], + [ + await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(), + await libAssetData.encodeERC721AssetData(erc721Token.address, firstERC721TokenId).callAsync(), + ], + ) + .callAsync(); + expect(await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync()).to.bignumber.equal( Math.min(erc20TokenTotalSupply.toNumber(), numberOfERC721Tokens), ); }); it('should return a balance of 0 if the assetData does not correspond to an AssetProxy contract', async () => { const fakeAssetData = '0x01020304'; - const balance = await libAssetData.getBalance.callAsync(tokenOwnerAddress, fakeAssetData); + const balance = await libAssetData.getBalance(tokenOwnerAddress, fakeAssetData).callAsync(); expect(balance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return a balance of MAX_UINT256 if the the StaticCallProxy assetData contains data for a successful staticcall', async () => { - const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(1)); + const staticCallData = staticCallTarget.isOddNumber(new BigNumber(1)).getABIEncodedTransactionData(); const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001'); const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer)); - const assetData = await libAssetData.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - const balance = await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData); + const assetData = await libAssetData + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + const balance = await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync(); expect(balance).to.bignumber.equal(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); }); it('should return a balance of 0 if the the StaticCallProxy assetData contains data for an unsuccessful staticcall', async () => { - const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(0)); + const staticCallData = staticCallTarget.isOddNumber(new BigNumber(0)).getABIEncodedTransactionData(); const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001'); const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer)); - const assetData = await libAssetData.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - expectedResultHash, - ); - const balance = await libAssetData.getBalance.callAsync(tokenOwnerAddress, assetData); + const assetData = await libAssetData + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash) + .callAsync(); + const balance = await libAssetData.getBalance(tokenOwnerAddress, assetData).callAsync(); expect(balance).to.bignumber.equal(constants.ZERO_AMOUNT); }); }); @@ -465,104 +466,103 @@ describe('LibAssetData', () => { describe('getAssetProxyAllowance', () => { it('should query ERC20 allowances by asset data', async () => { const allowance = new BigNumber(1); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address); + const assetData = await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(); expect( - await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData), + await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(), ).to.bignumber.equal(allowance); }); it('should query ERC721 approval by asset data', async () => { - await erc721Token.approve.awaitTransactionSuccessAsync(erc721Proxy.address, firstERC721TokenId, { + await erc721Token.approve(erc721Proxy.address, firstERC721TokenId).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeERC721AssetData.callAsync( - erc721Token.address, - firstERC721TokenId, - ); + const assetData = await libAssetData + .encodeERC721AssetData(erc721Token.address, firstERC721TokenId) + .callAsync(); expect( - await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData), + await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(), ).to.bignumber.equal(1); }); it('should query ERC721 approvalForAll by assetData', async () => { - await erc721Token.setApprovalForAll.awaitTransactionSuccessAsync(erc721Proxy.address, true, { + await erc721Token.setApprovalForAll(erc721Proxy.address, true).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeERC721AssetData.callAsync( - erc721Token.address, - firstERC721TokenId, - ); + const assetData = await libAssetData + .encodeERC721AssetData(erc721Token.address, firstERC721TokenId) + .callAsync(); expect( - await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData), + await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(), ).to.bignumber.equal(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); }); it('should query ERC1155 allowances by asset data', async () => { - await erc1155Token.setApprovalForAll.awaitTransactionSuccessAsync(erc1155Proxy.address, true, { + await erc1155Token.setApprovalForAll(erc1155Proxy.address, true).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeERC1155AssetData.callAsync( - erc1155Token.address, - [erc1155TokenId], - [new BigNumber(1)], - constants.NULL_BYTES, - ); + const assetData = await libAssetData + .encodeERC1155AssetData( + erc1155Token.address, + [erc1155TokenId], + [new BigNumber(1)], + constants.NULL_BYTES, + ) + .callAsync(); expect( - await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData), + await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(), ).to.bignumber.equal(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); }); it('should query multi-asset allowances by asset data', async () => { const allowance = new BigNumber(1); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - await erc721Token.approve.awaitTransactionSuccessAsync(erc721Proxy.address, firstERC721TokenId, { + await erc721Token.approve(erc721Proxy.address, firstERC721TokenId).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [ - await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address), - await libAssetData.encodeERC721AssetData.callAsync(erc721Token.address, firstERC721TokenId), - ], - ); + const assetData = await libAssetData + .encodeMultiAssetData( + [new BigNumber(1), new BigNumber(1)], + [ + await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(), + await libAssetData.encodeERC721AssetData(erc721Token.address, firstERC721TokenId).callAsync(), + ], + ) + .callAsync(); expect( - await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData), + await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(), ).to.bignumber.equal(1); return; }); it('should return an allowance of 0 if the assetData does not correspond to an AssetProxy contract', async () => { const fakeAssetData = '0x01020304'; - const allowance = await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, fakeAssetData); + const allowance = await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, fakeAssetData).callAsync(); expect(allowance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return an allowance of MAX_UINT256 for any staticCallAssetData', async () => { const staticCallData = AssetProxyId.StaticCall; - const assetData = await libAssetData.encodeStaticCallAssetData.callAsync( - staticCallTarget.address, - staticCallData, - constants.KECCAK256_NULL, - ); - const allowance = await libAssetData.getAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData); + const assetData = await libAssetData + .encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL) + .callAsync(); + const allowance = await libAssetData.getAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(); expect(allowance).to.bignumber.equal(constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS); }); }); describe('getBatchBalances', () => { it('should query balances for a batch of asset data strings', async () => { - const erc20AssetData = await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address); - const erc721AssetData = await libAssetData.encodeERC721AssetData.callAsync( - erc721Token.address, - firstERC721TokenId, - ); + const erc20AssetData = await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(); + const erc721AssetData = await libAssetData + .encodeERC721AssetData(erc721Token.address, firstERC721TokenId) + .callAsync(); expect( - await libAssetData.getBatchBalances.callAsync(tokenOwnerAddress, [erc20AssetData, erc721AssetData]), + await libAssetData.getBatchBalances(tokenOwnerAddress, [erc20AssetData, erc721AssetData]).callAsync(), ).to.deep.equal([new BigNumber(erc20TokenTotalSupply), new BigNumber(1)]); }); }); @@ -570,24 +570,24 @@ describe('LibAssetData', () => { describe('getBalanceAndAllowance', () => { it('should query balance and allowance together, from asset data', async () => { const allowance = new BigNumber(1); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address); + const assetData = await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(); expect( - await libAssetData.getBalanceAndAssetProxyAllowance.callAsync(tokenOwnerAddress, assetData), + await libAssetData.getBalanceAndAssetProxyAllowance(tokenOwnerAddress, assetData).callAsync(), ).to.deep.equal([new BigNumber(erc20TokenTotalSupply), allowance]); }); }); describe('getBatchBalancesAndAllowances', () => { it('should query balances and allowances together, from an asset data array', async () => { const allowance = new BigNumber(1); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const assetData = await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address); + const assetData = await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(); expect( - await libAssetData.getBatchBalancesAndAssetProxyAllowances.callAsync(tokenOwnerAddress, [assetData]), + await libAssetData.getBatchBalancesAndAssetProxyAllowances(tokenOwnerAddress, [assetData]).callAsync(), ).to.deep.equal([[new BigNumber(erc20TokenTotalSupply)], [allowance]]); }); }); @@ -595,22 +595,20 @@ describe('LibAssetData', () => { describe('getBatchAssetProxyAllowances', () => { it('should query allowances for a batch of asset data strings', async () => { const allowance = new BigNumber(1); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - await erc721Token.approve.awaitTransactionSuccessAsync(erc721Proxy.address, firstERC721TokenId, { + await erc721Token.approve(erc721Proxy.address, firstERC721TokenId).awaitTransactionSuccessAsync({ from: tokenOwnerAddress, }); - const erc20AssetData = await libAssetData.encodeERC20AssetData.callAsync(erc20Token.address); - const erc721AssetData = await libAssetData.encodeERC721AssetData.callAsync( - erc721Token.address, - firstERC721TokenId, - ); + const erc20AssetData = await libAssetData.encodeERC20AssetData(erc20Token.address).callAsync(); + const erc721AssetData = await libAssetData + .encodeERC721AssetData(erc721Token.address, firstERC721TokenId) + .callAsync(); expect( - await libAssetData.getBatchAssetProxyAllowances.callAsync(tokenOwnerAddress, [ - erc20AssetData, - erc721AssetData, - ]), + await libAssetData + .getBatchAssetProxyAllowances(tokenOwnerAddress, [erc20AssetData, erc721AssetData]) + .callAsync(), ).to.deep.equal([new BigNumber(1), new BigNumber(1)]); }); }); diff --git a/contracts/tests/test/dev-utils/lib_transaction_decoder.ts b/contracts/tests/test/dev-utils/lib_transaction_decoder.ts index 37ad8fac86..5e23eda5c8 100644 --- a/contracts/tests/test/dev-utils/lib_transaction_decoder.ts +++ b/contracts/tests/test/dev-utils/lib_transaction_decoder.ts @@ -47,8 +47,8 @@ describe('LibTransactionDecoder', () => { }); it('should decode an Exchange.batchCancelOrders() transaction', async () => { - const input = exchangeInterface.batchCancelOrders.getABIEncodedTransactionData([order, order]); - expect(await libTxDecoder.decodeZeroExTransactionData.callAsync(input)).to.deep.equal([ + const input = exchangeInterface.batchCancelOrders([order, order]).getABIEncodedTransactionData(); + expect(await libTxDecoder.decodeZeroExTransactionData(input).callAsync()).to.deep.equal([ 'batchCancelOrders', [order, order], [], @@ -57,13 +57,11 @@ describe('LibTransactionDecoder', () => { }); for (const func of ['batchFillOrders', 'batchFillOrdersNoThrow', 'batchFillOrKillOrders']) { - const input = (exchangeInterface as any)[func].getABIEncodedTransactionData( - [order, order], - [takerAssetFillAmount, takerAssetFillAmount], - [signature, signature], - ); + const input = (exchangeInterface as any) + [func]([order, order], [takerAssetFillAmount, takerAssetFillAmount], [signature, signature]) + .getABIEncodedTransactionData(); it(`should decode an Exchange.${func}() transaction`, async () => { - expect(await libTxDecoder.decodeZeroExTransactionData.callAsync(input)).to.deep.equal([ + expect(await libTxDecoder.decodeZeroExTransactionData(input).callAsync()).to.deep.equal([ func, [order, order], [takerAssetFillAmount, takerAssetFillAmount], @@ -73,8 +71,8 @@ describe('LibTransactionDecoder', () => { } it('should decode an Exchange.cancelOrder() transaction', async () => { - const input = exchangeInterface.cancelOrder.getABIEncodedTransactionData(order); - expect(await libTxDecoder.decodeZeroExTransactionData.callAsync(input)).to.deep.equal([ + const input = exchangeInterface.cancelOrder(order).getABIEncodedTransactionData(); + expect(await libTxDecoder.decodeZeroExTransactionData(input).callAsync()).to.deep.equal([ 'cancelOrder', [order], [], @@ -83,13 +81,11 @@ describe('LibTransactionDecoder', () => { }); for (const func of ['fillOrder', 'fillOrKillOrder']) { - const input = (exchangeInterface as any)[func].getABIEncodedTransactionData( - order, - takerAssetFillAmount, - signature, - ); + const input = (exchangeInterface as any) + [func](order, takerAssetFillAmount, signature) + .getABIEncodedTransactionData(); it(`should decode an Exchange.${func}() transaction`, async () => { - expect(await libTxDecoder.decodeZeroExTransactionData.callAsync(input)).to.deep.equal([ + expect(await libTxDecoder.decodeZeroExTransactionData(input).callAsync()).to.deep.equal([ func, [order], [takerAssetFillAmount], @@ -104,13 +100,11 @@ describe('LibTransactionDecoder', () => { 'marketBuyOrdersFillOrKill', 'marketSellOrdersFillOrKill', ]) { - const input = (exchangeInterface as any)[func].getABIEncodedTransactionData( - [order, order], - takerAssetFillAmount, - [signature, signature], - ); + const input = (exchangeInterface as any) + [func]([order, order], takerAssetFillAmount, [signature, signature]) + .getABIEncodedTransactionData(); it(`should decode an Exchange.${func}() transaction`, async () => { - expect(await libTxDecoder.decodeZeroExTransactionData.callAsync(input)).to.deep.equal([ + expect(await libTxDecoder.decodeZeroExTransactionData(input).callAsync()).to.deep.equal([ func, [order, order], [takerAssetFillAmount], @@ -133,13 +127,10 @@ describe('LibTransactionDecoder', () => { makerFeeAssetData: order.takerFeeAssetData, takerFeeAssetData: order.makerFeeAssetData, }; - const input = exchangeInterface.matchOrders.getABIEncodedTransactionData( - order, - complementaryOrder, - signature, - signature, - ); - expect(await libTxDecoder.decodeZeroExTransactionData.callAsync(input)).to.deep.equal([ + const input = exchangeInterface + .matchOrders(order, complementaryOrder, signature, signature) + .getABIEncodedTransactionData(); + expect(await libTxDecoder.decodeZeroExTransactionData(input).callAsync()).to.deep.equal([ 'matchOrders', [order, complementaryOrder], [order.takerAssetAmount, complementaryOrder.takerAssetAmount], diff --git a/contracts/tests/test/dev-utils/order_validation_utils.ts b/contracts/tests/test/dev-utils/order_validation_utils.ts index 29a9ea9049..282040e9b7 100644 --- a/contracts/tests/test/dev-utils/order_validation_utils.ts +++ b/contracts/tests/test/dev-utils/order_validation_utils.ts @@ -93,17 +93,12 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { txDefaults, artifacts, ); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { - from: owner, - }); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { - from: owner, - }); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(multiAssetProxy.address, { - from: owner, - }); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); + + await exchange.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner }); + await exchange.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner }); + await exchange.registerAssetProxy(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner }); + await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); devUtils = await DevUtilsContract.deployFrom0xArtifactAsync( artifacts.DevUtils, @@ -113,10 +108,10 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { exchange.address, ); - feeAssetData = await devUtils.encodeERC20AssetData.callAsync(feeErc20Token.address); - erc20AssetData = await devUtils.encodeERC20AssetData.callAsync(erc20Token.address); - erc20AssetData2 = await devUtils.encodeERC20AssetData.callAsync(erc20Token2.address); - erc721AssetData = await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, tokenId); + feeAssetData = await devUtils.encodeERC20AssetData(feeErc20Token.address).callAsync(); + erc20AssetData = await devUtils.encodeERC20AssetData(erc20Token.address).callAsync(); + erc20AssetData2 = await devUtils.encodeERC20AssetData(erc20Token2.address).callAsync(); + erc721AssetData = await devUtils.encodeERC721AssetData(erc721Token.address, tokenId).callAsync(); const defaultOrderParams = { ...constants.STATIC_ORDER_PARAMS, makerAddress, @@ -143,48 +138,44 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { it('should return the balance when balance < allowance', async () => { const balance = new BigNumber(123); const allowance = new BigNumber(456); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, balance); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.setBalance(makerAddress, balance).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: makerAddress, }); - const transferableAmount = await devUtils.getTransferableAssetAmount.callAsync( - makerAddress, - erc20AssetData, - ); + const transferableAmount = await devUtils + .getTransferableAssetAmount(makerAddress, erc20AssetData) + .callAsync(); expect(transferableAmount).to.bignumber.equal(balance); }); it('should return the allowance when allowance < balance', async () => { const balance = new BigNumber(456); const allowance = new BigNumber(123); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, balance); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, allowance, { + await erc20Token.setBalance(makerAddress, balance).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, allowance).awaitTransactionSuccessAsync({ from: makerAddress, }); - const transferableAmount = await devUtils.getTransferableAssetAmount.callAsync( - makerAddress, - erc20AssetData, - ); + const transferableAmount = await devUtils + .getTransferableAssetAmount(makerAddress, erc20AssetData) + .callAsync(); expect(transferableAmount).to.bignumber.equal(allowance); }); it('should return the correct transferable amount for multiAssetData', async () => { - const multiAssetData = await devUtils.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [erc20AssetData, erc20AssetData2], - ); + const multiAssetData = await devUtils + .encodeMultiAssetData([new BigNumber(1), new BigNumber(1)], [erc20AssetData, erc20AssetData2]) + .callAsync(); const transferableAmount1 = new BigNumber(10); const transferableAmount2 = new BigNumber(5); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, transferableAmount1); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, transferableAmount1, { + await erc20Token.setBalance(makerAddress, transferableAmount1).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, transferableAmount1).awaitTransactionSuccessAsync({ from: makerAddress, }); - await erc20Token2.setBalance.awaitTransactionSuccessAsync(makerAddress, transferableAmount2); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, transferableAmount2, { + await erc20Token2.setBalance(makerAddress, transferableAmount2).awaitTransactionSuccessAsync(); + await erc20Token2.approve(erc20Proxy.address, transferableAmount2).awaitTransactionSuccessAsync({ from: makerAddress, }); - const transferableAmount = await devUtils.getTransferableAssetAmount.callAsync( - makerAddress, - multiAssetData, - ); + const transferableAmount = await devUtils + .getTransferableAssetAmount(makerAddress, multiAssetData) + .callAsync(); expect(transferableAmount).to.bignumber.equal(transferableAmount2); }); }); @@ -193,160 +184,143 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { signedOrder = await orderFactory.newSignedOrderAsync(); }); it('should return the correct orderInfo when the order is valid', async () => { - const [orderInfo] = await devUtils.getOrderRelevantState.callAsync(signedOrder, signedOrder.signature); + const [orderInfo] = await devUtils.getOrderRelevantState(signedOrder, signedOrder.signature).callAsync(); expect(orderInfo.orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder)); expect(orderInfo.orderStatus).to.equal(OrderStatus.Fillable); expect(orderInfo.orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return isValidSignature=true when the signature is valid', async () => { - const [, , isValidSignature] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, , isValidSignature] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(isValidSignature).to.equal(true); }); it('should return isValidSignature=false when the signature is invalid', async () => { const invalidSignature = '0x01'; - const [, , isValidSignature] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - invalidSignature, - ); + const [, , isValidSignature] = await devUtils + .getOrderRelevantState(signedOrder, invalidSignature) + .callAsync(); expect(isValidSignature).to.equal(false); }); it('should return a fillableTakerAssetAmount of 0 when balances or allowances are insufficient', async () => { - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return a fillableTakerAssetAmount of 0 when fee balances/allowances are insufficient', async () => { - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return a fillableTakerAssetAmount of 0 when balances/allowances of one asset within a multiAssetData are insufficient', async () => { - const multiAssetData = await devUtils.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [erc20AssetData, erc20AssetData2], - ); + const multiAssetData = await devUtils + .encodeMultiAssetData([new BigNumber(1), new BigNumber(1)], [erc20AssetData, erc20AssetData2]) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: multiAssetData }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return the correct fillableTakerAssetAmount when fee balances/allowances are partially sufficient', async () => { - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); const divisor = 4; - await feeErc20Token.setBalance.awaitTransactionSuccessAsync( - makerAddress, - signedOrder.makerFee.dividedToIntegerBy(divisor), - ); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token + .setBalance(makerAddress, signedOrder.makerFee.dividedToIntegerBy(divisor)) + .awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal( signedOrder.takerAssetAmount.dividedToIntegerBy(divisor), ); }); it('should return the correct fillableTakerAssetAmount when non-fee balances/allowances are partially sufficient', async () => { const divisor = 4; - await erc20Token.setBalance.awaitTransactionSuccessAsync( - makerAddress, - signedOrder.makerAssetAmount.dividedToIntegerBy(divisor), - ); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token + .setBalance(makerAddress, signedOrder.makerAssetAmount.dividedToIntegerBy(divisor)) + .awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal( signedOrder.takerAssetAmount.dividedToIntegerBy(divisor), ); }); it('should return the correct fillableTakerAssetAmount when balances/allowances of one asset within a multiAssetData are partially sufficient', async () => { - const multiAssetData = await devUtils.encodeMultiAssetData.callAsync( - [new BigNumber(1), new BigNumber(1)], - [erc20AssetData, erc20AssetData2], - ); + const multiAssetData = await devUtils + .encodeMultiAssetData([new BigNumber(1), new BigNumber(1)], [erc20AssetData, erc20AssetData2]) + .callAsync(); signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: multiAssetData }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); const divisor = 4; - await erc20Token2.setBalance.awaitTransactionSuccessAsync( - makerAddress, - signedOrder.makerAssetAmount.dividedToIntegerBy(divisor), - ); - await erc20Token2.approve.awaitTransactionSuccessAsync( - erc20Proxy.address, - signedOrder.makerAssetAmount.dividedToIntegerBy(divisor), - { + await erc20Token2 + .setBalance(makerAddress, signedOrder.makerAssetAmount.dividedToIntegerBy(divisor)) + .awaitTransactionSuccessAsync(); + await erc20Token2 + .approve(erc20Proxy.address, signedOrder.makerAssetAmount.dividedToIntegerBy(divisor)) + .awaitTransactionSuccessAsync({ from: makerAddress, - }, - ); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + }); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal( signedOrder.takerAssetAmount.dividedToIntegerBy(divisor), ); }); it('should return a fillableTakerAssetAmount of 0 when non-fee balances/allowances are insufficient', async () => { - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should return a fillableTakerAssetAmount equal to the takerAssetAmount when the order is unfilled and balances/allowances are sufficient', async () => { - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(signedOrder.takerAssetAmount); }); it('should return the correct fillableTakerAssetAmount when balances/allowances are partially sufficient and makerAsset=makerFeeAsset', async () => { @@ -357,60 +331,54 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { makerFee: new BigNumber(40), }); const transferableMakerAssetAmount = new BigNumber(10); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, transferableMakerAssetAmount); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, transferableMakerAssetAmount, { + await feeErc20Token.setBalance(makerAddress, transferableMakerAssetAmount).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, transferableMakerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); const expectedFillableTakerAssetAmount = transferableMakerAssetAmount .times(signedOrder.takerAssetAmount) .dividedToIntegerBy(signedOrder.makerAssetAmount.plus(signedOrder.makerFee)); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(expectedFillableTakerAssetAmount); }); it('should return the correct fillabeTakerassetAmount when makerAsset balances/allowances are sufficient and there are no maker fees', async () => { signedOrder = await orderFactory.newSignedOrderAsync({ makerFee: constants.ZERO_AMOUNT }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal(signedOrder.takerAssetAmount); }); it('should return a fillableTakerAssetAmount when the remaining takerAssetAmount is less than the transferable amount', async () => { - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + await erc20Token2.setBalance(takerAddress, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee); + await feeErc20Token.setBalance(takerAddress, signedOrder.takerFee).awaitTransactionSuccessAsync(); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: takerAddress, }); const takerAssetFillAmount = signedOrder.takerAssetAmount.dividedToIntegerBy(4); - await exchange.fillOrder.awaitTransactionSuccessAsync( - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - { from: takerAddress }, - ); - const [, fillableTakerAssetAmount] = await devUtils.getOrderRelevantState.callAsync( - signedOrder, - signedOrder.signature, - ); + await exchange + .fillOrder(signedOrder, takerAssetFillAmount, signedOrder.signature) + .awaitTransactionSuccessAsync({ from: takerAddress }); + const [, fillableTakerAssetAmount] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(fillableTakerAssetAmount).to.bignumber.equal( signedOrder.takerAssetAmount.minus(takerAssetFillAmount), ); @@ -422,15 +390,13 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { makerFeeAssetData: '0x', takerFeeAssetData: '0x', }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [ - orderInfo, - fillableTakerAssetAmount, - isValidSignature, - ] = await devUtils.getOrderRelevantState.callAsync(signedOrder, signedOrder.signature); + const [orderInfo, fillableTakerAssetAmount, isValidSignature] = await devUtils + .getOrderRelevantState(signedOrder, signedOrder.signature) + .callAsync(); expect(orderInfo.orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder)); expect(orderInfo.orderStatus).to.equal(OrderStatus.Fillable); expect(orderInfo.orderTakerAssetFilledAmount).to.bignumber.equal(constants.ZERO_AMOUNT); @@ -441,25 +407,20 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { describe('getOrderRelevantStates', async () => { it('should return the correct information for multiple orders', async () => { signedOrder = await orderFactory.newSignedOrderAsync(); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync(); + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync(); + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); const signedOrder2 = await orderFactory.newSignedOrderAsync({ makerAssetData: erc721AssetData }); const invalidSignature = '0x01'; - await exchange.cancelOrder.awaitTransactionSuccessAsync(signedOrder2, { from: makerAddress }); - const [ - ordersInfo, - fillableTakerAssetAmounts, - isValidSignature, - ] = await devUtils.getOrderRelevantStates.callAsync( - [signedOrder, signedOrder2], - [signedOrder.signature, invalidSignature], - ); + await exchange.cancelOrder(signedOrder2).awaitTransactionSuccessAsync({ from: makerAddress }); + const [ordersInfo, fillableTakerAssetAmounts, isValidSignature] = await devUtils + .getOrderRelevantStates([signedOrder, signedOrder2], [signedOrder.signature, invalidSignature]) + .callAsync(); expect(ordersInfo[0].orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder)); expect(ordersInfo[1].orderHash).to.equal(orderHashUtils.getOrderHashHex(signedOrder2)); expect(ordersInfo[0].orderStatus).to.equal(OrderStatus.Fillable); @@ -477,177 +438,162 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { signedOrder = await orderFactory.newSignedOrderAsync(); }); it('should return TakerAssetDataFailed if the takerAsset transfer fails', async () => { - const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync( - signedOrder, - takerAddress, - signedOrder.takerAssetAmount, - ); + const orderTransferResults = await devUtils + .getSimulatedOrderTransferResults(signedOrder, takerAddress, signedOrder.takerAssetAmount) + .callAsync(); expect(orderTransferResults).to.equal(OrderTransferResults.TakerAssetDataFailed); }); it('should return MakerAssetDataFailed if the makerAsset transfer fails', async () => { - await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, { + await erc20Token2.setBalance(takerAddress, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync( - signedOrder, - takerAddress, - signedOrder.takerAssetAmount, - ); + const orderTransferResults = await devUtils + .getSimulatedOrderTransferResults(signedOrder, takerAddress, signedOrder.takerAssetAmount) + .callAsync(); expect(orderTransferResults).to.equal(OrderTransferResults.MakerAssetDataFailed); }); it('should return TakerFeeAssetDataFailed if the takerFeeAsset transfer fails', async () => { - await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, { + await erc20Token2.setBalance(takerAddress, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync( - signedOrder, - takerAddress, - signedOrder.takerAssetAmount, - ); + const orderTransferResults = await devUtils + .getSimulatedOrderTransferResults(signedOrder, takerAddress, signedOrder.takerAssetAmount) + .callAsync(); expect(orderTransferResults).to.equal(OrderTransferResults.TakerFeeAssetDataFailed); }); it('should return MakerFeeAssetDataFailed if the makerFeeAsset transfer fails', async () => { - await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, { + await erc20Token2.setBalance(takerAddress, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, { + await feeErc20Token.setBalance(takerAddress, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: takerAddress, }); - const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync( - signedOrder, - takerAddress, - signedOrder.takerAssetAmount, - ); + const orderTransferResults = await devUtils + .getSimulatedOrderTransferResults(signedOrder, takerAddress, signedOrder.takerAssetAmount) + .callAsync(); expect(orderTransferResults).to.equal(OrderTransferResults.MakerFeeAssetDataFailed); }); it('should return TransfersSuccessful if all transfers succeed', async () => { - await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, { + await erc20Token2.setBalance(takerAddress, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, { + await feeErc20Token.setBalance(takerAddress, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: takerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync( - signedOrder, - takerAddress, - signedOrder.takerAssetAmount, - ); + const orderTransferResults = await devUtils + .getSimulatedOrderTransferResults(signedOrder, takerAddress, signedOrder.takerAssetAmount) + .callAsync(); expect(orderTransferResults).to.equal(OrderTransferResults.TransfersSuccessful); }); it('should return TransfersSuccessful for a partial fill when taker has ample assets for the fill but not for the whole order', async () => { - await erc20Token2.setBalance.awaitTransactionSuccessAsync( - takerAddress, - signedOrder.takerAssetAmount.dividedBy(2), - { + await erc20Token2 + .setBalance(takerAddress, signedOrder.takerAssetAmount.dividedBy(2)) + .awaitTransactionSuccessAsync({ from: owner, - }, - ); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + }); + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, { + await feeErc20Token.setBalance(takerAddress, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: takerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const orderTransferResults = await devUtils.getSimulatedOrderTransferResults.callAsync( - signedOrder, - takerAddress, - signedOrder.takerAssetAmount.dividedBy(2), - ); + const orderTransferResults = await devUtils + .getSimulatedOrderTransferResults(signedOrder, takerAddress, signedOrder.takerAssetAmount.dividedBy(2)) + .callAsync(); expect(orderTransferResults).to.equal(OrderTransferResults.TransfersSuccessful); }); }); describe('getSimulatedOrdersTransferResults', async () => { it('should simulate the transfers of each order independently from one another', async () => { // Set balances and allowances to exactly enough to fill a single order - await erc20Token2.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerAssetAmount, { + await erc20Token2.setBalance(takerAddress, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token2.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerAssetAmount, { + await erc20Token2.approve(erc20Proxy.address, signedOrder.takerAssetAmount).awaitTransactionSuccessAsync({ from: takerAddress, }); - await erc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerAssetAmount, { + await erc20Token.setBalance(makerAddress, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: owner, }); - await erc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerAssetAmount, { + await erc20Token.approve(erc20Proxy.address, signedOrder.makerAssetAmount).awaitTransactionSuccessAsync({ from: makerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(takerAddress, signedOrder.takerFee, { + await feeErc20Token.setBalance(takerAddress, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.takerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.takerFee).awaitTransactionSuccessAsync({ from: takerAddress, }); - await feeErc20Token.setBalance.awaitTransactionSuccessAsync(makerAddress, signedOrder.makerFee, { + await feeErc20Token.setBalance(makerAddress, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: owner, }); - await feeErc20Token.approve.awaitTransactionSuccessAsync(erc20Proxy.address, signedOrder.makerFee, { + await feeErc20Token.approve(erc20Proxy.address, signedOrder.makerFee).awaitTransactionSuccessAsync({ from: makerAddress, }); - const [ - orderTransferResults1, - orderTransferResults2, - ] = await devUtils.getSimulatedOrdersTransferResults.callAsync( - [signedOrder, signedOrder], - [takerAddress, takerAddress], - [signedOrder.takerAssetAmount, signedOrder.takerAssetAmount], - ); + const [orderTransferResults1, orderTransferResults2] = await devUtils + .getSimulatedOrdersTransferResults( + [signedOrder, signedOrder], + [takerAddress, takerAddress], + [signedOrder.takerAssetAmount, signedOrder.takerAssetAmount], + ) + .callAsync(); expect(orderTransferResults1).to.equal(OrderTransferResults.TransfersSuccessful); expect(orderTransferResults2).to.equal(OrderTransferResults.TransfersSuccessful); }); diff --git a/contracts/utils/test/authorizable.ts b/contracts/utils/test/authorizable.ts index 5a7df0c885..a7069200b8 100644 --- a/contracts/utils/test/authorizable.ts +++ b/contracts/utils/test/authorizable.ts @@ -47,68 +47,68 @@ describe('Authorizable', () => { describe('addAuthorizedAddress', () => { it('should revert if not called by owner', async () => { const expectedError = new OwnableRevertErrors.OnlyOwnerError(notOwner, owner); - const tx = authorizable.addAuthorizedAddress.sendTransactionAsync(notOwner, { from: notOwner }); + const tx = authorizable.addAuthorizedAddress(notOwner).sendTransactionAsync({ from: notOwner }); return expect(tx).to.revertWith(expectedError); }); it('should allow owner to add an authorized address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const isAuthorized = await authorizable.authorized.callAsync(address); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const isAuthorized = await authorizable.authorized(address).callAsync(); expect(isAuthorized).to.be.true(); }); it('should revert if owner attempts to authorize the zero address', async () => { const expectedError = new AuthorizableRevertErrors.ZeroCantBeAuthorizedError(); - const tx = authorizable.addAuthorizedAddress.sendTransactionAsync(constants.NULL_ADDRESS, { from: owner }); + const tx = authorizable.addAuthorizedAddress(constants.NULL_ADDRESS).sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); it('should revert if owner attempts to authorize a duplicate address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const expectedError = new AuthorizableRevertErrors.TargetAlreadyAuthorizedError(address); - const tx = authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }); + const tx = authorizable.addAuthorizedAddress(address).sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); }); describe('removeAuthorizedAddress', () => { it('should revert if not called by owner', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const expectedError = new OwnableRevertErrors.OnlyOwnerError(notOwner, owner); - const tx = authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: notOwner }); + const tx = authorizable.removeAuthorizedAddress(address).sendTransactionAsync({ from: notOwner }); return expect(tx).to.revertWith(expectedError); }); it('should allow owner to remove an authorized address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const isAuthorized = await authorizable.authorized.callAsync(address); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const isAuthorized = await authorizable.authorized(address).callAsync(); expect(isAuthorized).to.be.false(); }); it('should revert if owner attempts to remove an address that is not authorized', async () => { const expectedError = new AuthorizableRevertErrors.TargetNotAuthorizedError(address); - const tx = authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: owner }); + const tx = authorizable.removeAuthorizedAddress(address).sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); }); describe('removeAuthorizedAddressAtIndex', () => { it('should revert if not called by owner', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const index = new BigNumber(0); const expectedError = new OwnableRevertErrors.OnlyOwnerError(notOwner, owner); - const tx = authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { + const tx = authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({ from: notOwner, }); return expect(tx).to.revertWith(expectedError); }); it('should revert if index is >= authorities.length', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const index = new BigNumber(1); const expectedError = new AuthorizableRevertErrors.IndexOutOfBoundsError(index, index); - const tx = authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { + const tx = authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({ from: owner, }); return expect(tx).to.revertWith(expectedError); @@ -117,7 +117,7 @@ describe('Authorizable', () => { it('should revert if owner attempts to remove an address that is not authorized', async () => { const index = new BigNumber(0); const expectedError = new AuthorizableRevertErrors.TargetNotAuthorizedError(address); - const tx = authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, { + const tx = authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({ from: owner, }); return expect(tx).to.revertWith(expectedError); @@ -126,37 +126,37 @@ describe('Authorizable', () => { it('should revert if address at index does not match target', async () => { const address1 = address; const address2 = notOwner; - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address1, { from: owner }); - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address2, { from: owner }); + await authorizable.addAuthorizedAddress(address1).awaitTransactionSuccessAsync({ from: owner }); + await authorizable.addAuthorizedAddress(address2).awaitTransactionSuccessAsync({ from: owner }); const address1Index = new BigNumber(0); const expectedError = new AuthorizableRevertErrors.AuthorizedAddressMismatchError(address1, address2); - const tx = authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address2, address1Index, { + const tx = authorizable.removeAuthorizedAddressAtIndex(address2, address1Index).sendTransactionAsync({ from: owner, }); return expect(tx).to.revertWith(expectedError); }); it('should allow owner to remove an authorized address', async () => { - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); const index = new BigNumber(0); - await authorizable.removeAuthorizedAddressAtIndex.awaitTransactionSuccessAsync(address, index, { + await authorizable.removeAuthorizedAddressAtIndex(address, index).awaitTransactionSuccessAsync({ from: owner, }); - const isAuthorized = await authorizable.authorized.callAsync(address); + const isAuthorized = await authorizable.authorized(address).callAsync(); expect(isAuthorized).to.be.false(); }); }); describe('getAuthorizedAddresses', () => { it('should return all authorized addresses', async () => { - const initial = await authorizable.getAuthorizedAddresses.callAsync(); + const initial = await authorizable.getAuthorizedAddresses().callAsync(); expect(initial).to.have.length(0); - await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const afterAdd = await authorizable.getAuthorizedAddresses.callAsync(); + await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const afterAdd = await authorizable.getAuthorizedAddresses().callAsync(); expect(afterAdd).to.have.length(1); expect(afterAdd).to.include(address); - await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner }); - const afterRemove = await authorizable.getAuthorizedAddresses.callAsync(); + await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner }); + const afterRemove = await authorizable.getAuthorizedAddresses().callAsync(); expect(afterRemove).to.have.length(0); }); }); diff --git a/contracts/utils/test/lib_address.ts b/contracts/utils/test/lib_address.ts index 32f2742142..72a67f6a65 100644 --- a/contracts/utils/test/lib_address.ts +++ b/contracts/utils/test/lib_address.ts @@ -31,12 +31,12 @@ describe('LibAddress', () => { describe('isContract', () => { it('should return false for a non-contract address', async () => { - const isContract = await lib.externalIsContract.callAsync(nonContract); + const isContract = await lib.externalIsContract(nonContract).callAsync(); expect(isContract).to.be.false(); }); it('should return true for a non-contract address', async () => { - const isContract = await lib.externalIsContract.callAsync(lib.address); + const isContract = await lib.externalIsContract(lib.address).callAsync(); expect(isContract).to.be.true(); }); }); diff --git a/contracts/utils/test/lib_address_array.ts b/contracts/utils/test/lib_address_array.ts index 0999ba506a..df4116b661 100644 --- a/contracts/utils/test/lib_address_array.ts +++ b/contracts/utils/test/lib_address_array.ts @@ -31,7 +31,7 @@ describe('LibAddressArray', () => { describe('append', () => { it('should append to empty array', async () => { const addr = randomAddress(); - const result = await lib.publicAppend.callAsync([], addr); + const result = await lib.publicAppend([], addr).callAsync(); const expected = [addr]; expect(result).to.deep.equal(expected); }); @@ -40,7 +40,7 @@ describe('LibAddressArray', () => { const arr = _.times(3, () => randomAddress()); const addr = randomAddress(); const expected = [...arr, addr]; - const result = await lib.publicAppend.callAsync(arr, addr); + const result = await lib.publicAppend(arr, addr).callAsync(); expect(result).to.deep.equal(expected); }); @@ -53,7 +53,7 @@ describe('LibAddressArray', () => { addressArrayEndPtr.plus(freeMemOffset), addressArrayEndPtr, ); - return expect(lib.testAppendRealloc.callAsync(arr, freeMemOffset, addr)).to.revertWith(expectedError); + return expect(lib.testAppendRealloc(arr, freeMemOffset, addr).callAsync()).to.revertWith(expectedError); }); it('should keep the same memory address if free memory pointer does not move', async () => { @@ -61,11 +61,9 @@ describe('LibAddressArray', () => { const addr = randomAddress(); const freeMemOffset = new BigNumber(0); const expected = [...arr, addr]; - const [result, oldArrayMemStart, newArrayMemStart] = await lib.testAppendRealloc.callAsync( - arr, - freeMemOffset, - addr, - ); + const [result, oldArrayMemStart, newArrayMemStart] = await lib + .testAppendRealloc(arr, freeMemOffset, addr) + .callAsync(); expect(result).to.deep.equal(expected); expect(newArrayMemStart).bignumber.to.be.equal(oldArrayMemStart); }); @@ -75,11 +73,9 @@ describe('LibAddressArray', () => { const addr = randomAddress(); const freeMemOffset = new BigNumber(1); const expectedArray = [...arr, addr]; - const [result, oldArrayMemStart, newArrayMemStart] = await lib.testAppendRealloc.callAsync( - arr, - freeMemOffset, - addr, - ); + const [result, oldArrayMemStart, newArrayMemStart] = await lib + .testAppendRealloc(arr, freeMemOffset, addr) + .callAsync(); // The new location should be the end of the old array + freeMemOffset. const expectedNewArrayMemStart = oldArrayMemStart.plus((arr.length + 1) * 32).plus(freeMemOffset); expect(result).to.deep.equal(expectedArray); @@ -90,27 +86,27 @@ describe('LibAddressArray', () => { describe('contains', () => { it('should return false on an empty array', async () => { const addr = randomAddress(); - const isFound = await lib.publicContains.callAsync([], addr); + const isFound = await lib.publicContains([], addr).callAsync(); expect(isFound).to.equal(false); }); it('should return false on a missing item', async () => { const arr = _.times(3, () => randomAddress()); const addr = randomAddress(); - const isFound = await lib.publicContains.callAsync(arr, addr); + const isFound = await lib.publicContains(arr, addr).callAsync(); expect(isFound).to.equal(false); }); it('should return true on an included item', async () => { const arr = _.times(4, () => randomAddress()); const addr = _.sample(arr) as string; - const isFound = await lib.publicContains.callAsync(arr, addr); + const isFound = await lib.publicContains(arr, addr).callAsync(); expect(isFound).to.equal(true); }); it('should return true on the only item in the array', async () => { const arr = _.times(1, () => randomAddress()); - const isFound = await lib.publicContains.callAsync(arr, arr[0]); + const isFound = await lib.publicContains(arr, arr[0]).callAsync(); expect(isFound).to.equal(true); }); }); @@ -118,14 +114,14 @@ describe('LibAddressArray', () => { describe('indexOf', () => { it('should fail on an empty array', async () => { const addr = randomAddress(); - const [isSuccess] = await lib.publicIndexOf.callAsync([], addr); + const [isSuccess] = await lib.publicIndexOf([], addr).callAsync(); expect(isSuccess).to.equal(false); }); it('should fail on a missing item', async () => { const arr = _.times(3, () => randomAddress()); const addr = randomAddress(); - const [isSuccess] = await lib.publicIndexOf.callAsync(arr, addr); + const [isSuccess] = await lib.publicIndexOf(arr, addr).callAsync(); expect(isSuccess).to.equal(false); }); @@ -133,14 +129,14 @@ describe('LibAddressArray', () => { const arr = _.times(4, () => randomAddress()); const expectedIndexOf = _.random(0, arr.length - 1); const addr = arr[expectedIndexOf]; - const [isSuccess, index] = await lib.publicIndexOf.callAsync(arr, addr); + const [isSuccess, index] = await lib.publicIndexOf(arr, addr).callAsync(); expect(isSuccess).to.equal(true); expect(index).bignumber.to.equal(expectedIndexOf); }); it('should succeed on the only item in the array', async () => { const arr = _.times(1, () => randomAddress()); - const [isSuccess, index] = await lib.publicIndexOf.callAsync(arr, arr[0]); + const [isSuccess, index] = await lib.publicIndexOf(arr, arr[0]).callAsync(); expect(isSuccess).to.equal(true); expect(index).bignumber.to.equal(0); }); diff --git a/contracts/utils/test/lib_bytes.ts b/contracts/utils/test/lib_bytes.ts index c0498f4430..e8feeb61d0 100644 --- a/contracts/utils/test/lib_bytes.ts +++ b/contracts/utils/test/lib_bytes.ts @@ -60,17 +60,17 @@ blockchainTests('LibBytes', env => { constants.ZERO_AMOUNT, constants.ZERO_AMOUNT, ); - return expect(libBytes.publicPopLastByte.callAsync(constants.NULL_BYTES)).to.revertWith(expectedError); + return expect(libBytes.publicPopLastByte(constants.NULL_BYTES).callAsync()).to.revertWith(expectedError); }); it('should pop the last byte from the input and return it when array holds more than 1 byte', async () => { - const [newBytes, poppedByte] = await libBytes.publicPopLastByte.callAsync(byteArrayLongerThan32Bytes); + const [newBytes, poppedByte] = await libBytes.publicPopLastByte(byteArrayLongerThan32Bytes).callAsync(); const expectedNewBytes = byteArrayLongerThan32Bytes.slice(0, -2); const expectedPoppedByte = `0x${byteArrayLongerThan32Bytes.slice(-2)}`; expect(newBytes).to.equal(expectedNewBytes); expect(poppedByte).to.equal(expectedPoppedByte); }); it('should pop the last byte from the input and return it when array is exactly 1 byte', async () => { - const [newBytes, poppedByte] = await libBytes.publicPopLastByte.callAsync(testByte); + const [newBytes, poppedByte] = await libBytes.publicPopLastByte(testByte).callAsync(); const expectedNewBytes = '0x'; expect(newBytes).to.equal(expectedNewBytes); return expect(poppedByte).to.be.equal(testByte); @@ -79,51 +79,45 @@ blockchainTests('LibBytes', env => { describe('equals', () => { it('should return true if byte arrays are equal (both arrays < 32 bytes)', async () => { - const isEqual = await libBytes.publicEquals.callAsync( - byteArrayShorterThan32Bytes, - byteArrayShorterThan32Bytes, - ); + const isEqual = await libBytes + .publicEquals(byteArrayShorterThan32Bytes, byteArrayShorterThan32Bytes) + .callAsync(); return expect(isEqual).to.be.true(); }); it('should return true if byte arrays are equal (both arrays > 32 bytes)', async () => { - const isEqual = await libBytes.publicEquals.callAsync( - byteArrayLongerThan32Bytes, - byteArrayLongerThan32Bytes, - ); + const isEqual = await libBytes + .publicEquals(byteArrayLongerThan32Bytes, byteArrayLongerThan32Bytes) + .callAsync(); return expect(isEqual).to.be.true(); }); it('should return false if byte arrays are not equal (first array < 32 bytes, second array > 32 bytes)', async () => { - const isEqual = await libBytes.publicEquals.callAsync( - byteArrayShorterThan32Bytes, - byteArrayLongerThan32Bytes, - ); + const isEqual = await libBytes + .publicEquals(byteArrayShorterThan32Bytes, byteArrayLongerThan32Bytes) + .callAsync(); return expect(isEqual).to.be.false(); }); it('should return false if byte arrays are not equal (first array > 32 bytes, second array < 32 bytes)', async () => { - const isEqual = await libBytes.publicEquals.callAsync( - byteArrayLongerThan32Bytes, - byteArrayShorterThan32Bytes, - ); + const isEqual = await libBytes + .publicEquals(byteArrayLongerThan32Bytes, byteArrayShorterThan32Bytes) + .callAsync(); return expect(isEqual).to.be.false(); }); it('should return false if byte arrays are not equal (same length, but a byte in first word differs)', async () => { - const isEqual = await libBytes.publicEquals.callAsync( - byteArrayLongerThan32BytesFirstBytesSwapped, - byteArrayLongerThan32Bytes, - ); + const isEqual = await libBytes + .publicEquals(byteArrayLongerThan32BytesFirstBytesSwapped, byteArrayLongerThan32Bytes) + .callAsync(); return expect(isEqual).to.be.false(); }); it('should return false if byte arrays are not equal (same length, but a byte in last word differs)', async () => { - const isEqual = await libBytes.publicEquals.callAsync( - byteArrayLongerThan32BytesLastBytesSwapped, - byteArrayLongerThan32Bytes, - ); + const isEqual = await libBytes + .publicEquals(byteArrayLongerThan32BytesLastBytesSwapped, byteArrayLongerThan32Bytes) + .callAsync(); return expect(isEqual).to.be.false(); }); describe('should ignore trailing data', () => { it('should return true when both < 32 bytes', async () => { - const isEqual = await libBytes.publicEqualsPop1.callAsync('0x0102', '0x0103'); + const isEqual = await libBytes.publicEqualsPop1('0x0102', '0x0103').callAsync(); return expect(isEqual).to.be.true(); }); }); @@ -133,7 +127,7 @@ blockchainTests('LibBytes', env => { it('should successfully read address when the address takes up the whole array', async () => { const byteArray = ethUtil.addHexPrefix(testAddress); const testAddressOffset = new BigNumber(0); - const address = await libBytes.publicReadAddress.callAsync(byteArray, testAddressOffset); + const address = await libBytes.publicReadAddress(byteArray, testAddressOffset).callAsync(); return expect(address).to.be.equal(testAddress); }); it('should successfully read address when it is offset in the array', async () => { @@ -142,7 +136,7 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, addressByteArrayBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testAddressOffset = new BigNumber(prefixByteArrayBuffer.byteLength); - const address = await libBytes.publicReadAddress.callAsync(combinedByteArray, testAddressOffset); + const address = await libBytes.publicReadAddress(combinedByteArray, testAddressOffset).callAsync(); return expect(address).to.be.equal(testAddress); }); it('should fail if the byte array is too short to hold an address', async () => { @@ -153,7 +147,7 @@ blockchainTests('LibBytes', env => { new BigNumber(3), new BigNumber(20), ); - return expect(libBytes.publicReadAddress.callAsync(shortByteArray, offset)).to.revertWith(expectedError); + return expect(libBytes.publicReadAddress(shortByteArray, offset).callAsync()).to.revertWith(expectedError); }); it('should fail if the length between the offset and end of the byte array is too short to hold an address', async () => { const byteArray = testAddress; @@ -163,7 +157,7 @@ blockchainTests('LibBytes', env => { new BigNumber(20), new BigNumber(40), ); - return expect(libBytes.publicReadAddress.callAsync(byteArray, badOffset)).to.revertWith(expectedError); + return expect(libBytes.publicReadAddress(byteArray, badOffset).callAsync()).to.revertWith(expectedError); }); }); @@ -171,11 +165,9 @@ blockchainTests('LibBytes', env => { it('should successfully write address when the address takes up the whole array', async () => { const byteArray = testAddress; const testAddressOffset = new BigNumber(0); - const newByteArray = await libBytes.publicWriteAddress.callAsync( - byteArray, - testAddressOffset, - testAddressB, - ); + const newByteArray = await libBytes + .publicWriteAddress(byteArray, testAddressOffset, testAddressB) + .callAsync(); return expect(newByteArray).to.be.equal(testAddressB); }); it('should successfully write address when it is offset in the array', async () => { @@ -184,11 +176,9 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, addressByteArrayBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testAddressOffset = new BigNumber(prefixByteArrayBuffer.byteLength); - const newByteArray = await libBytes.publicWriteAddress.callAsync( - combinedByteArray, - testAddressOffset, - testAddressB, - ); + const newByteArray = await libBytes + .publicWriteAddress(combinedByteArray, testAddressOffset, testAddressB) + .callAsync(); const newByteArrayBuffer = ethUtil.toBuffer(newByteArray); const addressFromOffsetBuffer = newByteArrayBuffer.slice(prefixByteArrayBuffer.byteLength); const addressFromOffset = ethUtil.addHexPrefix(ethUtil.bufferToHex(addressFromOffsetBuffer)); @@ -203,7 +193,7 @@ blockchainTests('LibBytes', env => { new BigNumber(20), ); return expect( - libBytes.publicWriteAddress.callAsync(byteArrayShorterThan20Bytes, offset, testAddress), + libBytes.publicWriteAddress(byteArrayShorterThan20Bytes, offset, testAddress).callAsync(), ).to.revertWith(expectedError); }); it('should fail if the length between the offset and end of the byte array is too short to hold an address', async () => { @@ -214,7 +204,7 @@ blockchainTests('LibBytes', env => { badOffset, badOffset.plus(new BigNumber(20)), ); - return expect(libBytes.publicWriteAddress.callAsync(byteArray, badOffset, testAddress)).to.revertWith( + return expect(libBytes.publicWriteAddress(byteArray, badOffset, testAddress).callAsync()).to.revertWith( expectedError, ); }); @@ -223,7 +213,7 @@ blockchainTests('LibBytes', env => { describe('readBytes32', () => { it('should successfully read bytes32 when the bytes32 takes up the whole array', async () => { const testBytes32Offset = new BigNumber(0); - const bytes32 = await libBytes.publicReadBytes32.callAsync(testBytes32, testBytes32Offset); + const bytes32 = await libBytes.publicReadBytes32(testBytes32, testBytes32Offset).callAsync(); return expect(bytes32).to.be.equal(testBytes32); }); it('should successfully read bytes32 when it is offset in the array', async () => { @@ -232,7 +222,7 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, bytes32ByteArrayBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testBytes32Offset = new BigNumber(prefixByteArrayBuffer.byteLength); - const bytes32 = await libBytes.publicReadBytes32.callAsync(combinedByteArray, testBytes32Offset); + const bytes32 = await libBytes.publicReadBytes32(combinedByteArray, testBytes32Offset).callAsync(); return expect(bytes32).to.be.equal(testBytes32); }); it('should fail if the byte array is too short to hold a bytes32', async () => { @@ -243,7 +233,7 @@ blockchainTests('LibBytes', env => { byteLen, new BigNumber(32), ); - return expect(libBytes.publicReadBytes32.callAsync(byteArrayShorterThan32Bytes, offset)).to.revertWith( + return expect(libBytes.publicReadBytes32(byteArrayShorterThan32Bytes, offset).callAsync()).to.revertWith( expectedError, ); }); @@ -254,7 +244,7 @@ blockchainTests('LibBytes', env => { badOffset, badOffset.plus(new BigNumber(32)), ); - return expect(libBytes.publicReadBytes32.callAsync(testBytes32, badOffset)).to.revertWith(expectedError); + return expect(libBytes.publicReadBytes32(testBytes32, badOffset).callAsync()).to.revertWith(expectedError); }); }); @@ -262,11 +252,9 @@ blockchainTests('LibBytes', env => { it('should successfully write bytes32 when the address takes up the whole array', async () => { const byteArray = testBytes32; const testBytes32Offset = new BigNumber(0); - const newByteArray = await libBytes.publicWriteBytes32.callAsync( - byteArray, - testBytes32Offset, - testBytes32B, - ); + const newByteArray = await libBytes + .publicWriteBytes32(byteArray, testBytes32Offset, testBytes32B) + .callAsync(); return expect(newByteArray).to.be.equal(testBytes32B); }); it('should successfully write bytes32 when it is offset in the array', async () => { @@ -275,11 +263,9 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, bytes32ByteArrayBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testBytes32Offset = new BigNumber(prefixByteArrayBuffer.byteLength); - const newByteArray = await libBytes.publicWriteBytes32.callAsync( - combinedByteArray, - testBytes32Offset, - testBytes32B, - ); + const newByteArray = await libBytes + .publicWriteBytes32(combinedByteArray, testBytes32Offset, testBytes32B) + .callAsync(); const newByteArrayBuffer = ethUtil.toBuffer(newByteArray); const bytes32FromOffsetBuffer = newByteArrayBuffer.slice(prefixByteArrayBuffer.byteLength); const bytes32FromOffset = ethUtil.addHexPrefix(ethUtil.bufferToHex(bytes32FromOffsetBuffer)); @@ -294,7 +280,7 @@ blockchainTests('LibBytes', env => { new BigNumber(32), ); return expect( - libBytes.publicWriteBytes32.callAsync(byteArrayShorterThan32Bytes, offset, testBytes32), + libBytes.publicWriteBytes32(byteArrayShorterThan32Bytes, offset, testBytes32).callAsync(), ).to.revertWith(expectedError); }); it('should fail if the length between the offset and end of the byte array is too short to hold a bytes32', async () => { @@ -305,7 +291,7 @@ blockchainTests('LibBytes', env => { badOffset, badOffset.plus(new BigNumber(32)), ); - return expect(libBytes.publicWriteBytes32.callAsync(byteArray, badOffset, testBytes32)).to.revertWith( + return expect(libBytes.publicWriteBytes32(byteArray, badOffset, testBytes32).callAsync()).to.revertWith( expectedError, ); }); @@ -317,7 +303,7 @@ blockchainTests('LibBytes', env => { const testUint256AsBuffer = ethUtil.toBuffer(formattedTestUint256); const byteArray = ethUtil.bufferToHex(testUint256AsBuffer); const testUint256Offset = new BigNumber(0); - const uint256 = await libBytes.publicReadUint256.callAsync(byteArray, testUint256Offset); + const uint256 = await libBytes.publicReadUint256(byteArray, testUint256Offset).callAsync(); return expect(uint256).to.bignumber.equal(testUint256); }); it('should successfully read uint256 when it is offset in the array', async () => { @@ -327,7 +313,7 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, testUint256AsBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testUint256Offset = new BigNumber(prefixByteArrayBuffer.byteLength); - const uint256 = await libBytes.publicReadUint256.callAsync(combinedByteArray, testUint256Offset); + const uint256 = await libBytes.publicReadUint256(combinedByteArray, testUint256Offset).callAsync(); return expect(uint256).to.bignumber.equal(testUint256); }); it('should fail if the byte array is too short to hold a uint256', async () => { @@ -338,7 +324,7 @@ blockchainTests('LibBytes', env => { byteLen, new BigNumber(32), ); - return expect(libBytes.publicReadUint256.callAsync(byteArrayShorterThan32Bytes, offset)).to.revertWith( + return expect(libBytes.publicReadUint256(byteArrayShorterThan32Bytes, offset).callAsync()).to.revertWith( expectedError, ); }); @@ -352,7 +338,7 @@ blockchainTests('LibBytes', env => { badOffset, badOffset.plus(new BigNumber(32)), ); - return expect(libBytes.publicReadUint256.callAsync(byteArray, badOffset)).to.revertWith(expectedError); + return expect(libBytes.publicReadUint256(byteArray, badOffset).callAsync()).to.revertWith(expectedError); }); }); @@ -360,11 +346,9 @@ blockchainTests('LibBytes', env => { it('should successfully write uint256 when the address takes up the whole array', async () => { const byteArray = testBytes32; const testUint256Offset = new BigNumber(0); - const newByteArray = await libBytes.publicWriteUint256.callAsync( - byteArray, - testUint256Offset, - testUint256B, - ); + const newByteArray = await libBytes + .publicWriteUint256(byteArray, testUint256Offset, testUint256B) + .callAsync(); const newByteArrayAsUint256 = new BigNumber(newByteArray, 16); return expect(newByteArrayAsUint256).to.be.bignumber.equal(testUint256B); }); @@ -374,11 +358,9 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, bytes32ByteArrayBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testUint256Offset = new BigNumber(prefixByteArrayBuffer.byteLength); - const newByteArray = await libBytes.publicWriteUint256.callAsync( - combinedByteArray, - testUint256Offset, - testUint256B, - ); + const newByteArray = await libBytes + .publicWriteUint256(combinedByteArray, testUint256Offset, testUint256B) + .callAsync(); const newByteArrayBuffer = ethUtil.toBuffer(newByteArray); const uint256FromOffsetBuffer = newByteArrayBuffer.slice(prefixByteArrayBuffer.byteLength); const uint256FromOffset = new BigNumber( @@ -396,7 +378,7 @@ blockchainTests('LibBytes', env => { new BigNumber(32), ); return expect( - libBytes.publicWriteUint256.callAsync(byteArrayShorterThan32Bytes, offset, testUint256), + libBytes.publicWriteUint256(byteArrayShorterThan32Bytes, offset, testUint256).callAsync(), ).to.revertWith(expectedError); }); it('should fail if the length between the offset and end of the byte array is too short to hold a uint256', async () => { @@ -407,7 +389,7 @@ blockchainTests('LibBytes', env => { badOffset, badOffset.plus(new BigNumber(32)), ); - return expect(libBytes.publicWriteUint256.callAsync(byteArray, badOffset, testUint256)).to.revertWith( + return expect(libBytes.publicWriteUint256(byteArray, badOffset, testUint256).callAsync()).to.revertWith( expectedError, ); }); @@ -424,18 +406,20 @@ blockchainTests('LibBytes', env => { new BigNumber(byteLen), // length of byteArrayLessThan4Bytes new BigNumber(4), ); - return expect(libBytes.publicReadBytes4.callAsync(byteArrayLessThan4Bytes, offset)).to.revertWith( + return expect(libBytes.publicReadBytes4(byteArrayLessThan4Bytes, offset).callAsync()).to.revertWith( expectedError, ); }); it('should return the first 4 bytes of a byte array of arbitrary length', async () => { - const first4Bytes = await libBytes.publicReadBytes4.callAsync(byteArrayLongerThan32Bytes, new BigNumber(0)); + const first4Bytes = await libBytes + .publicReadBytes4(byteArrayLongerThan32Bytes, new BigNumber(0)) + .callAsync(); const expectedFirst4Bytes = byteArrayLongerThan32Bytes.slice(0, 10); expect(first4Bytes).to.equal(expectedFirst4Bytes); }); it('should successfully read bytes4 when the bytes4 takes up the whole array', async () => { const testBytes4Offset = new BigNumber(0); - const bytes4 = await libBytes.publicReadBytes4.callAsync(testBytes4, testBytes4Offset); + const bytes4 = await libBytes.publicReadBytes4(testBytes4, testBytes4Offset).callAsync(); return expect(bytes4).to.be.equal(testBytes4); }); it('should successfully read bytes4 when it is offset in the array', async () => { @@ -444,7 +428,7 @@ blockchainTests('LibBytes', env => { const combinedByteArrayBuffer = Buffer.concat([prefixByteArrayBuffer, bytes4ByteArrayBuffer]); const combinedByteArray = ethUtil.bufferToHex(combinedByteArrayBuffer); const testBytes4Offset = new BigNumber(prefixByteArrayBuffer.byteLength); - const bytes4 = await libBytes.publicReadBytes4.callAsync(combinedByteArray, testBytes4Offset); + const bytes4 = await libBytes.publicReadBytes4(combinedByteArray, testBytes4Offset).callAsync(); return expect(bytes4).to.be.equal(testBytes4); }); it('should fail if the length between the offset and end of the byte array is too short to hold a bytes4', async () => { @@ -455,7 +439,7 @@ blockchainTests('LibBytes', env => { byteLen, badOffset.plus(new BigNumber(4)), ); - return expect(libBytes.publicReadBytes4.callAsync(testBytes4, badOffset)).to.revertWith(expectedError); + return expect(libBytes.publicReadBytes4(testBytes4, badOffset).callAsync()).to.revertWith(expectedError); }); }); @@ -477,12 +461,9 @@ blockchainTests('LibBytes', env => { tests.forEach(([dest, source, length, job]) => it(job, async () => { const expected = refMemcpy(memory, dest, source, length); - const resultStr = await libBytes.testMemcpy.callAsync( - memHex, - new BigNumber(dest), - new BigNumber(source), - new BigNumber(length), - ); + const resultStr = await libBytes + .testMemcpy(memHex, new BigNumber(dest), new BigNumber(source), new BigNumber(length)) + .callAsync(); const result = fromHex(resultStr); expect(result).to.deep.equal(expected); }), @@ -634,14 +615,14 @@ blockchainTests('LibBytes', env => { from, to, ); - return expect(libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to)).to.revertWith( + return expect(libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync()).to.revertWith( expectedError, ); }); it('should return a byte array of length 0 if from == to', async () => { const from = new BigNumber(0); const to = from; - const [result, original] = await libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result, original] = await libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync(); expect(original).to.eq(byteArrayLongerThan32Bytes); expect(result).to.eq(constants.NULL_BYTES); }); @@ -649,7 +630,7 @@ blockchainTests('LibBytes', env => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const from = new BigNumber(byteLen); const to = from; - const [result, original] = await libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result, original] = await libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync(); expect(original).to.eq(byteArrayLongerThan32Bytes); expect(result).to.eq(constants.NULL_BYTES); }); @@ -662,14 +643,14 @@ blockchainTests('LibBytes', env => { to, new BigNumber(byteLen), ); - return expect(libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to)).to.revertWith( + return expect(libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync()).to.revertWith( expectedError, ); }); it('should slice a section of the input', async () => { const from = new BigNumber(1); const to = new BigNumber(2); - const [result, original] = await libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result, original] = await libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync(); const expectedResult = `0x${byteArrayLongerThan32Bytes.slice(4, 6)}`; expect(original).to.eq(byteArrayLongerThan32Bytes); expect(result).to.eq(expectedResult); @@ -678,7 +659,7 @@ blockchainTests('LibBytes', env => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const from = new BigNumber(0); const to = new BigNumber(byteLen); - const [result, original] = await libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result, original] = await libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync(); expect(original).to.eq(byteArrayLongerThan32Bytes); expect(result).to.eq(byteArrayLongerThan32Bytes); }); @@ -693,21 +674,21 @@ blockchainTests('LibBytes', env => { from, to, ); - return expect(libBytes.publicSlice.callAsync(byteArrayLongerThan32Bytes, from, to)).to.revertWith( + return expect(libBytes.publicSlice(byteArrayLongerThan32Bytes, from, to).callAsync()).to.revertWith( expectedError, ); }); it('should return a byte array of length 0 if from == to', async () => { const from = new BigNumber(0); const to = from; - const [result] = await libBytes.publicSliceDestructive.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result] = await libBytes.publicSliceDestructive(byteArrayLongerThan32Bytes, from, to).callAsync(); expect(result).to.eq(constants.NULL_BYTES); }); it('should return a byte array of length 0 if from == to == b.length', async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const from = new BigNumber(byteLen); const to = from; - const [result] = await libBytes.publicSliceDestructive.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result] = await libBytes.publicSliceDestructive(byteArrayLongerThan32Bytes, from, to).callAsync(); expect(result).to.eq(constants.NULL_BYTES); }); it('should revert if to > input.length', async () => { @@ -720,13 +701,13 @@ blockchainTests('LibBytes', env => { new BigNumber(byteLen), ); return expect( - libBytes.publicSliceDestructive.callAsync(byteArrayLongerThan32Bytes, from, to), + libBytes.publicSliceDestructive(byteArrayLongerThan32Bytes, from, to).callAsync(), ).to.revertWith(expectedError); }); it('should slice a section of the input', async () => { const from = new BigNumber(1); const to = new BigNumber(2); - const [result] = await libBytes.publicSliceDestructive.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result] = await libBytes.publicSliceDestructive(byteArrayLongerThan32Bytes, from, to).callAsync(); const expectedResult = `0x${byteArrayLongerThan32Bytes.slice(4, 6)}`; expect(result).to.eq(expectedResult); }); @@ -734,37 +715,31 @@ blockchainTests('LibBytes', env => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const from = new BigNumber(0); const to = new BigNumber(byteLen); - const [result] = await libBytes.publicSliceDestructive.callAsync(byteArrayLongerThan32Bytes, from, to); + const [result] = await libBytes.publicSliceDestructive(byteArrayLongerThan32Bytes, from, to).callAsync(); expect(result).to.eq(byteArrayLongerThan32Bytes); }); }); describe('writeLength', () => { it('should return a null byte array if length is set to 0', async () => { - const result = await libBytes.publicWriteLength.callAsync( - byteArrayLongerThan32Bytes, - constants.ZERO_AMOUNT, - constants.NULL_BYTES, - ); + const result = await libBytes + .publicWriteLength(byteArrayLongerThan32Bytes, constants.ZERO_AMOUNT, constants.NULL_BYTES) + .callAsync(); expect(result).to.eq(constants.NULL_BYTES); }); it('should return the same byte array if length is unchanged', async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; - const result = await libBytes.publicWriteLength.callAsync( - byteArrayLongerThan32Bytes, - new BigNumber(byteLen), - constants.NULL_BYTES, - ); + const result = await libBytes + .publicWriteLength(byteArrayLongerThan32Bytes, new BigNumber(byteLen), constants.NULL_BYTES) + .callAsync(); expect(result).to.eq(byteArrayLongerThan32Bytes); }); it('should shave off lower order bytes if new length is less than original', async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const newLen = new BigNumber(byteLen).dividedToIntegerBy(2); - const result = await libBytes.publicWriteLength.callAsync( - byteArrayLongerThan32Bytes, - newLen, - constants.NULL_BYTES, - ); + const result = await libBytes + .publicWriteLength(byteArrayLongerThan32Bytes, newLen, constants.NULL_BYTES) + .callAsync(); expect(result).to.eq( byteArrayLongerThan32Bytes.slice( 0, @@ -778,35 +753,31 @@ blockchainTests('LibBytes', env => { it("should right pad with 0's if new length is greater than original and no extra bytes are appended", async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const newLen = new BigNumber(byteLen).multipliedBy(2); - const result = await libBytes.publicWriteLength.callAsync( - byteArrayLongerThan32Bytes, - newLen, - constants.NULL_BYTES, - ); + const result = await libBytes + .publicWriteLength(byteArrayLongerThan32Bytes, newLen, constants.NULL_BYTES) + .callAsync(); expect(result).to.eq(`${byteArrayLongerThan32Bytes}${'0'.repeat(byteArrayLongerThan32Bytes.length - 2)}`); }); it('should right pad with extra bytes if specified', async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const newLen = new BigNumber(byteLen).multipliedBy(2); - const result = await libBytes.publicWriteLength.callAsync( - byteArrayLongerThan32Bytes, - newLen, - byteArrayLongerThan32Bytes, - ); + const result = await libBytes + .publicWriteLength(byteArrayLongerThan32Bytes, newLen, byteArrayLongerThan32Bytes) + .callAsync(); expect(result).to.eq(`${byteArrayLongerThan32Bytes}${byteArrayLongerThan32Bytes.slice(2)}`); }); it('should result in the same byte array if length is reduced and reset', async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const tempByteLen = new BigNumber(byteLen).dividedToIntegerBy(2); return expect( - libBytes.assertBytesUnchangedAfterLengthReset.callAsync(byteArrayLongerThan32Bytes, tempByteLen), + libBytes.assertBytesUnchangedAfterLengthReset(byteArrayLongerThan32Bytes, tempByteLen).callAsync(), ).to.be.fulfilled(''); }); it('should result in the same byte array if length is increased and reset', async () => { const byteLen = fromHex(byteArrayLongerThan32Bytes).length; const tempByteLen = new BigNumber(byteLen).multipliedBy(2); return expect( - libBytes.assertBytesUnchangedAfterLengthReset.callAsync(byteArrayLongerThan32Bytes, tempByteLen), + libBytes.assertBytesUnchangedAfterLengthReset(byteArrayLongerThan32Bytes, tempByteLen).callAsync(), ).to.be.fulfilled(''); }); }); diff --git a/contracts/utils/test/lib_eip712.ts b/contracts/utils/test/lib_eip712.ts index 75c559091c..0dc1c9b53f 100644 --- a/contracts/utils/test/lib_eip712.ts +++ b/contracts/utils/test/lib_eip712.ts @@ -45,12 +45,9 @@ describe('LibEIP712', () => { chainId, verifyingContract, }); - const actualHash = await lib.externalHashEIP712DomainSeperator.callAsync( - name, - version, - new BigNumber(chainId), - verifyingContract, - ); + const actualHash = await lib + .externalHashEIP712DomainSeperator(name, version, new BigNumber(chainId), verifyingContract) + .callAsync(); expect(actualHash).to.be.eq(hexConcat(expectedHash)); } @@ -84,7 +81,7 @@ describe('LibEIP712', () => { const expectedHash = '0x'.concat(ethUtil.sha3(input).toString('hex')); // Get the actual hash by calling the smart contract - const actualHash = await lib.externalHashEIP712Message.callAsync(domainHash, hashStruct); + const actualHash = await lib.externalHashEIP712Message(domainHash, hashStruct).callAsync(); // Verify that the actual hash matches the expected hash expect(actualHash).to.be.eq(expectedHash); diff --git a/contracts/utils/test/lib_rich_errors.ts b/contracts/utils/test/lib_rich_errors.ts index 7d5ed539d7..d63fe8a959 100644 --- a/contracts/utils/test/lib_rich_errors.ts +++ b/contracts/utils/test/lib_rich_errors.ts @@ -21,7 +21,7 @@ blockchainTests('LibRichErrors', env => { it('should correctly revert the extra bytes', async () => { const extraBytes = hexRandom(100); try { - await lib.externalRRevert.callAsync(extraBytes); + await lib.externalRRevert(extraBytes).callAsync(); } catch (err) { const revertError = coerceThrownErrorAsRevertError(err); return expect(revertError.encode()).to.eq(extraBytes); @@ -33,7 +33,7 @@ blockchainTests('LibRichErrors', env => { it('should correctly revert a StringRevertError', async () => { const error = new StringRevertError('foo'); - return expect(lib.externalRRevert.callAsync(error.encode())).to.revertWith(error); + return expect(lib.externalRRevert(error.encode()).callAsync()).to.revertWith(error); }); }); }); diff --git a/contracts/utils/test/lib_safe_math.ts b/contracts/utils/test/lib_safe_math.ts index 8724479a62..f6a34c391f 100644 --- a/contracts/utils/test/lib_safe_math.ts +++ b/contracts/utils/test/lib_safe_math.ts @@ -30,17 +30,17 @@ blockchainTests('SafeMath', env => { const a = ONE_ETHER; const b = ONE_ETHER.times(2); const expected = ReferenceFunctions.safeMul(a, b); - const actual = await safeMath.externalSafeMul.callAsync(a, b); + const actual = await safeMath.externalSafeMul(a, b).callAsync(); expect(actual).bignumber.to.be.eq(expected); }); it('should return zero if first argument is zero', async () => { - const result = await safeMath.externalSafeMul.callAsync(constants.ZERO_AMOUNT, toBigNumber(1)); + const result = await safeMath.externalSafeMul(constants.ZERO_AMOUNT, toBigNumber(1)).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); it('should return zero if second argument is zero', async () => { - const result = await safeMath.externalSafeMul.callAsync(toBigNumber(1), constants.ZERO_AMOUNT); + const result = await safeMath.externalSafeMul(toBigNumber(1), constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); @@ -52,11 +52,11 @@ blockchainTests('SafeMath', env => { a, b, ); - return expect(safeMath.externalSafeMul.callAsync(a, b)).to.revertWith(expectedError); + return expect(safeMath.externalSafeMul(a, b).callAsync()).to.revertWith(expectedError); }); it("should calculate correct value for values that don't overflow", async () => { - const result = await safeMath.externalSafeMul.callAsync(toBigNumber(15), toBigNumber(13)); + const result = await safeMath.externalSafeMul(toBigNumber(15), toBigNumber(13)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(195)); }); }); @@ -66,27 +66,27 @@ blockchainTests('SafeMath', env => { const a = ONE_ETHER; const b = ONE_ETHER.times(2); const expected = ReferenceFunctions.safeDiv(a, b); - const actual = await safeMath.externalSafeDiv.callAsync(a, b); + const actual = await safeMath.externalSafeDiv(a, b).callAsync(); expect(actual).bignumber.to.be.eq(expected); }); it('should return the correct value if both values are the same', async () => { - const result = await safeMath.externalSafeDiv.callAsync(toBigNumber(1), toBigNumber(1)); + const result = await safeMath.externalSafeDiv(toBigNumber(1), toBigNumber(1)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(1)); }); it('should return the correct value if the values are different', async () => { - const result = await safeMath.externalSafeDiv.callAsync(toBigNumber(3), toBigNumber(2)); + const result = await safeMath.externalSafeDiv(toBigNumber(3), toBigNumber(2)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(1)); }); it('should return zero if the numerator is smaller than the denominator', async () => { - const result = await safeMath.externalSafeDiv.callAsync(toBigNumber(2), toBigNumber(3)); + const result = await safeMath.externalSafeDiv(toBigNumber(2), toBigNumber(3)).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); it('should return zero if first argument is zero', async () => { - const result = await safeMath.externalSafeDiv.callAsync(constants.ZERO_AMOUNT, toBigNumber(1)); + const result = await safeMath.externalSafeDiv(constants.ZERO_AMOUNT, toBigNumber(1)).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); @@ -98,7 +98,7 @@ blockchainTests('SafeMath', env => { a, b, ); - return expect(safeMath.externalSafeDiv.callAsync(a, b)).to.revertWith(expectedError); + return expect(safeMath.externalSafeDiv(a, b).callAsync()).to.revertWith(expectedError); }); }); @@ -107,7 +107,7 @@ blockchainTests('SafeMath', env => { const a = ONE_ETHER; const b = ONE_ETHER.dividedToIntegerBy(2); const expected = ReferenceFunctions.safeSub(a, b); - const actual = await safeMath.externalSafeSub.callAsync(a, b); + const actual = await safeMath.externalSafeSub(a, b).callAsync(); expect(actual).bignumber.to.be.eq(expected); }); @@ -119,16 +119,16 @@ blockchainTests('SafeMath', env => { a, b, ); - return expect(safeMath.externalSafeSub.callAsync(a, b)).to.revertWith(expectedError); + return expect(safeMath.externalSafeSub(a, b).callAsync()).to.revertWith(expectedError); }); it('should calculate correct value for values that are equal', async () => { - const result = await safeMath.externalSafeMul.callAsync(constants.ZERO_AMOUNT, constants.ZERO_AMOUNT); + const result = await safeMath.externalSafeMul(constants.ZERO_AMOUNT, constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); it('should calculate correct value for values that are not equal', async () => { - const result = await safeMath.externalSafeSub.callAsync(toBigNumber(15), toBigNumber(13)); + const result = await safeMath.externalSafeSub(toBigNumber(15), toBigNumber(13)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(2)); }); }); @@ -138,7 +138,7 @@ blockchainTests('SafeMath', env => { const a = ONE_ETHER; const b = ONE_ETHER.dividedToIntegerBy(2); const expected = ReferenceFunctions.safeAdd(a, b); - const actual = await safeMath.externalSafeAdd.callAsync(a, b); + const actual = await safeMath.externalSafeAdd(a, b).callAsync(); expect(actual).bignumber.to.be.eq(expected); }); @@ -150,55 +150,55 @@ blockchainTests('SafeMath', env => { a, b, ); - return expect(safeMath.externalSafeAdd.callAsync(a, b)).to.revertWith(expectedError); + return expect(safeMath.externalSafeAdd(a, b).callAsync()).to.revertWith(expectedError); }); it('should calculate correct value if addition does not overflow', async () => { - const result = await safeMath.externalSafeAdd.callAsync(toBigNumber(15), toBigNumber(13)); + const result = await safeMath.externalSafeAdd(toBigNumber(15), toBigNumber(13)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(28)); }); it('should calculate correct value if first argument is zero', async () => { - const result = await safeMath.externalSafeAdd.callAsync(constants.ZERO_AMOUNT, toBigNumber(13)); + const result = await safeMath.externalSafeAdd(constants.ZERO_AMOUNT, toBigNumber(13)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(13)); }); it('should calculate correct value if second argument is zero', async () => { - const result = await safeMath.externalSafeAdd.callAsync(toBigNumber(13), constants.ZERO_AMOUNT); + const result = await safeMath.externalSafeAdd(toBigNumber(13), constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(13)); }); }); describe('maxUint256', () => { it('should return first argument if it is greater than the second', async () => { - const result = await safeMath.externalMaxUint256.callAsync(toBigNumber(13), constants.ZERO_AMOUNT); + const result = await safeMath.externalMaxUint256(toBigNumber(13), constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(13)); }); it('should return first argument if it is equal the second', async () => { - const result = await safeMath.externalMaxUint256.callAsync(constants.ZERO_AMOUNT, constants.ZERO_AMOUNT); + const result = await safeMath.externalMaxUint256(constants.ZERO_AMOUNT, constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); it('should return second argument if it is greater than the first', async () => { - const result = await safeMath.externalMaxUint256.callAsync(constants.ZERO_AMOUNT, toBigNumber(13)); + const result = await safeMath.externalMaxUint256(constants.ZERO_AMOUNT, toBigNumber(13)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(13)); }); }); describe('minUint256', () => { it('should return first argument if it is less than the second', async () => { - const result = await safeMath.externalMaxUint256.callAsync(constants.ZERO_AMOUNT, toBigNumber(13)); + const result = await safeMath.externalMaxUint256(constants.ZERO_AMOUNT, toBigNumber(13)).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(13)); }); it('should return first argument if it is equal the second', async () => { - const result = await safeMath.externalMaxUint256.callAsync(constants.ZERO_AMOUNT, constants.ZERO_AMOUNT); + const result = await safeMath.externalMaxUint256(constants.ZERO_AMOUNT, constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(constants.ZERO_AMOUNT); }); it('should return second argument if it is less than the first', async () => { - const result = await safeMath.externalMaxUint256.callAsync(toBigNumber(13), constants.ZERO_AMOUNT); + const result = await safeMath.externalMaxUint256(toBigNumber(13), constants.ZERO_AMOUNT).callAsync(); expect(result).bignumber.to.be.eq(toBigNumber(13)); }); }); diff --git a/contracts/utils/test/log_decoding.ts b/contracts/utils/test/log_decoding.ts index ebf3e3b533..c73fb2a089 100644 --- a/contracts/utils/test/log_decoding.ts +++ b/contracts/utils/test/log_decoding.ts @@ -49,19 +49,25 @@ describe('TestLogDecoding', () => { describe('Decoding Log Arguments', () => { it('should decode locally emitted event args when no dependencies are passed into wrapper', async () => { - const txReceipt = await testLogDecodingDeployedWithoutDependencies.emitEvent.awaitTransactionSuccessAsync(); + const txReceipt = await testLogDecodingDeployedWithoutDependencies + .emitEvent() + .awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.be.equal(1); // tslint:disable no-unnecessary-type-assertion expect((txReceipt.logs[0] as LogWithDecodedArgs).args).to.be.deep.equal(expectedEvent); }); it('should not decode event args when no dependencies are passed into wrapper', async () => { - const txReceipt = await testLogDecodingDeployedWithoutDependencies.emitEventDownstream.awaitTransactionSuccessAsync(); + const txReceipt = await testLogDecodingDeployedWithoutDependencies + .emitEventDownstream() + .awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.be.equal(1); // tslint:disable no-unnecessary-type-assertion expect((txReceipt.logs[0] as LogWithDecodedArgs).args).to.be.undefined(); }); it('should decode args for local but not downstream event when no dependencies are passed into wrapper', async () => { - const txReceipt = await testLogDecodingDeployedWithoutDependencies.emitEventsLocalAndDownstream.awaitTransactionSuccessAsync(); + const txReceipt = await testLogDecodingDeployedWithoutDependencies + .emitEventsLocalAndDownstream() + .awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.be.equal(2); // tslint:disable no-unnecessary-type-assertion expect((txReceipt.logs[0] as LogWithDecodedArgs).args).to.be.deep.equal(expectedEvent); @@ -69,13 +75,15 @@ describe('TestLogDecoding', () => { expect((txReceipt.logs[1] as LogWithDecodedArgs).args).to.be.undefined(); }); it('should decode locally emitted event args when dependencies are passed into wrapper', async () => { - const txReceipt = await testLogDecodingWithDependencies.emitEvent.awaitTransactionSuccessAsync(); + const txReceipt = await testLogDecodingWithDependencies.emitEvent().awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.be.equal(1); // tslint:disable no-unnecessary-type-assertion expect((txReceipt.logs[0] as LogWithDecodedArgs).args).to.be.deep.equal(expectedEvent); }); it('should decode downstream event args when dependencies are passed into wrapper', async () => { - const txReceipt = await testLogDecodingWithDependencies.emitEventDownstream.awaitTransactionSuccessAsync(); + const txReceipt = await testLogDecodingWithDependencies + .emitEventDownstream() + .awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.be.equal(1); // tslint:disable no-unnecessary-type-assertion expect((txReceipt.logs[0] as LogWithDecodedArgs).args).to.be.deep.equal( @@ -83,7 +91,9 @@ describe('TestLogDecoding', () => { ); }); it('should decode args for both local and downstream events when dependencies are passed into wrapper', async () => { - const txReceipt = await testLogDecodingWithDependencies.emitEventsLocalAndDownstream.awaitTransactionSuccessAsync(); + const txReceipt = await testLogDecodingWithDependencies + .emitEventsLocalAndDownstream() + .awaitTransactionSuccessAsync(); expect(txReceipt.logs.length).to.be.equal(2); // tslint:disable no-unnecessary-type-assertion expect((txReceipt.logs[0] as LogWithDecodedArgs).args).to.be.deep.equal(expectedEvent); diff --git a/contracts/utils/test/ownable.ts b/contracts/utils/test/ownable.ts index 76bc98f55e..471edcd9a5 100644 --- a/contracts/utils/test/ownable.ts +++ b/contracts/utils/test/ownable.ts @@ -24,11 +24,11 @@ blockchainTests.resets('Ownable', env => { describe('onlyOwner', () => { it('should revert if sender is not the owner', async () => { const expectedError = new OwnableRevertErrors.OnlyOwnerError(nonOwner, owner); - return expect(ownable.externalOnlyOwner.callAsync({ from: nonOwner })).to.revertWith(expectedError); + return expect(ownable.externalOnlyOwner().callAsync({ from: nonOwner })).to.revertWith(expectedError); }); it('should succeed if sender is the owner', async () => { - const isSuccessful = await ownable.externalOnlyOwner.callAsync({ from: owner }); + const isSuccessful = await ownable.externalOnlyOwner().callAsync({ from: owner }); expect(isSuccessful).to.be.true(); }); }); @@ -36,12 +36,12 @@ blockchainTests.resets('Ownable', env => { describe('transferOwnership', () => { it('should revert if the specified new owner is the zero address', async () => { const expectedError = new OwnableRevertErrors.TransferOwnerToZeroError(); - const tx = ownable.transferOwnership.sendTransactionAsync(constants.NULL_ADDRESS, { from: owner }); + const tx = ownable.transferOwnership(constants.NULL_ADDRESS).sendTransactionAsync({ from: owner }); return expect(tx).to.revertWith(expectedError); }); it('should transfer ownership if the specified new owner is not the zero address', async () => { - const receipt = await ownable.transferOwnership.awaitTransactionSuccessAsync(nonOwner, { from: owner }); + const receipt = await ownable.transferOwnership(nonOwner).awaitTransactionSuccessAsync({ from: owner }); // Ensure that the correct logs were emitted. expect(receipt.logs.length).to.be.eq(1); @@ -52,7 +52,7 @@ blockchainTests.resets('Ownable', env => { expect(event).to.be.deep.eq({ previousOwner: owner, newOwner: nonOwner }); // Ensure that the owner was actually updated - const updatedOwner = await ownable.owner.callAsync(); + const updatedOwner = await ownable.owner().callAsync(); expect(updatedOwner).to.be.eq(nonOwner); }); }); diff --git a/contracts/utils/test/reentrancy_guard.ts b/contracts/utils/test/reentrancy_guard.ts index 6356e27cf0..186549500f 100644 --- a/contracts/utils/test/reentrancy_guard.ts +++ b/contracts/utils/test/reentrancy_guard.ts @@ -32,11 +32,11 @@ describe('ReentrancyGuard', () => { describe('nonReentrant', () => { it('should revert if reentrancy occurs', async () => { const expectedError = new ReentrancyGuardRevertErrors.IllegalReentrancyError(); - return expect(guard.guarded.sendTransactionAsync(true)).to.revertWith(expectedError); + return expect(guard.guarded(true).sendTransactionAsync()).to.revertWith(expectedError); }); it('should succeed if reentrancy does not occur', async () => { - const isSuccessful = await guard.guarded.callAsync(false); + const isSuccessful = await guard.guarded(false).callAsync(); expect(isSuccessful).to.be.true(); }); }); diff --git a/contracts/utils/test/refundable.ts b/contracts/utils/test/refundable.ts index 497a1f0f32..2a6ce57df6 100644 --- a/contracts/utils/test/refundable.ts +++ b/contracts/utils/test/refundable.ts @@ -36,14 +36,14 @@ blockchainTests('Refundable', env => { blockchainTests.resets('refundNonzeroBalance', () => { it('should not send a refund when no value is sent', async () => { // Send 100 wei to the refundable contract that should be refunded. - await receiver.testRefundNonZeroBalance.awaitTransactionSuccessAsync(refundable.address, { + await receiver.testRefundNonZeroBalance(refundable.address).awaitTransactionSuccessAsync({ value: constants.ZERO_AMOUNT, }); }); it('should send a full refund when nonzero value is sent', async () => { // Send 100 wei to the refundable contract that should be refunded. - await receiver.testRefundNonZeroBalance.awaitTransactionSuccessAsync(refundable.address, { + await receiver.testRefundNonZeroBalance(refundable.address).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); @@ -54,7 +54,7 @@ blockchainTests('Refundable', env => { blockchainTests.resets('refundFinalBalance', () => { it('should fully refund the sender when `shouldNotRefund` is false', async () => { // Send 100 wei to the refundable contract that should be refunded to the receiver contract. - await receiver.testRefundFinalBalance.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testRefundFinalBalance(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); @@ -62,19 +62,19 @@ blockchainTests('Refundable', env => { // This test may not be necessary, but it is included here as a sanity check. it('should fully refund the sender when `shouldNotRefund` is false for two calls in a row', async () => { // Send 100 wei to the refundable contract that should be refunded to the receiver contract. - await receiver.testRefundFinalBalance.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testRefundFinalBalance(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); // Send 1000 wei to the refundable contract that should be refunded to the receiver contract. - await receiver.testRefundFinalBalance.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testRefundFinalBalance(refundable.address, false).awaitTransactionSuccessAsync({ value: new BigNumber(1000), }); }); it('should not refund the sender if `shouldNotRefund` is true', async () => { /// Send 100 wei to the refundable contract that should not be refunded. - await receiver.testRefundFinalBalance.awaitTransactionSuccessAsync(refundable.address, true, { + await receiver.testRefundFinalBalance(refundable.address, true).awaitTransactionSuccessAsync({ value: new BigNumber(1000), }); }); @@ -85,7 +85,7 @@ blockchainTests('Refundable', env => { blockchainTests.resets('disableRefundUntilEnd', () => { it('should fully refund the sender when `shouldNotRefund` is false', async () => { // Send 100 wei to the refundable contract that should be refunded to the receiver contract. - await receiver.testDisableRefundUntilEnd.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testDisableRefundUntilEnd(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); @@ -93,47 +93,47 @@ blockchainTests('Refundable', env => { // This test may not be necessary, but it is included here as a sanity check. it('should fully refund the sender when `shouldNotRefund` is false for two calls in a row', async () => { // Send 100 wei to the refundable contract that should be refunded to the receiver contract. - await receiver.testDisableRefundUntilEnd.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testDisableRefundUntilEnd(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); // Send 1000 wei to the refundable contract that should be refunded to the receiver contract. - await receiver.testDisableRefundUntilEnd.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testDisableRefundUntilEnd(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_THOUSAND, }); }); it('should not refund the sender if `shouldNotRefund` is true', async () => { /// Send 100 wei to the refundable contract that should not be refunded. - await receiver.testDisableRefundUntilEnd.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testDisableRefundUntilEnd(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); it('should disable the `disableRefundUntilEnd` modifier and refund when `shouldNotRefund` is false', async () => { /// Send 100 wei to the refundable contract that should be refunded. - await receiver.testNestedDisableRefundUntilEnd.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testNestedDisableRefundUntilEnd(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); it('should disable the `refundFinalBalance` modifier and send no refund when `shouldNotRefund` is true', async () => { /// Send 100 wei to the refundable contract that should not be refunded. - await receiver.testNestedDisableRefundUntilEnd.awaitTransactionSuccessAsync(refundable.address, true, { + await receiver.testNestedDisableRefundUntilEnd(refundable.address, true).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); it('should disable the `refundFinalBalance` modifier and refund when `shouldNotRefund` is false', async () => { /// Send 100 wei to the refundable contract that should be refunded. - await receiver.testMixedRefunds.awaitTransactionSuccessAsync(refundable.address, false, { + await receiver.testMixedRefunds(refundable.address, false).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); it('should disable the `refundFinalBalance` modifier and send no refund when `shouldNotRefund` is true', async () => { /// Send 100 wei to the refundable contract that should not be refunded. - await receiver.testMixedRefunds.awaitTransactionSuccessAsync(refundable.address, true, { + await receiver.testMixedRefunds(refundable.address, true).awaitTransactionSuccessAsync({ value: ONE_HUNDRED, }); }); diff --git a/packages/0x.js/CHANGELOG.json b/packages/0x.js/CHANGELOG.json index 4526832f38..a60813ba14 100644 --- a/packages/0x.js/CHANGELOG.json +++ b/packages/0x.js/CHANGELOG.json @@ -10,6 +10,10 @@ "note": "ContractWrappers no longer exposes `erc20Proxy`, `erc721Proxy` and `dutchAuction` wrappers", "pr": 2324 }, + { + "note": "[Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details", + "pr": 2325 + }, { "note": "Remove IWallet and IValidator contract wrappers", "pr": 2337 diff --git a/packages/0x.js/src/index.ts b/packages/0x.js/src/index.ts index 6d0cb656c6..9eeba88af5 100644 --- a/packages/0x.js/src/index.ts +++ b/packages/0x.js/src/index.ts @@ -41,6 +41,15 @@ export { ExchangeTransactionExecutionEventArgs, } from '@0x/abi-gen-wrappers'; +export { + ContractEvent, + SendTransactionOpts, + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SubscriptionErrors, +} from '@0x/base-contract'; + export import Web3ProviderEngine = require('web3-provider-engine'); export { @@ -76,8 +85,6 @@ export { SimpleEvmOutput, SimpleEvmBytecodeOutput, EIP712DomainWithDefaultSchema, - AwaitTransactionSuccessOpts, - SendTransactionOpts, EventCallback, IndexedFilterValues, DecodedLogEvent, diff --git a/packages/abi-gen-wrappers/CHANGELOG.json b/packages/abi-gen-wrappers/CHANGELOG.json index acaf15522e..63054c7c58 100644 --- a/packages/abi-gen-wrappers/CHANGELOG.json +++ b/packages/abi-gen-wrappers/CHANGELOG.json @@ -5,6 +5,10 @@ { "note": "[Breaking] Remove `erc20Proxy`, `multiAssetProxy`, `erc1155Proxy`, `staticCallProxy`, `erc721Proxy`, `assetProxyOwner`, `ZRXToken` and `dutchAuction` wrappers", "pr": 2324 + }, + { + "note": "[Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details", + "pr": 2325 } ] }, diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts index 238bc768c9..66167d9d99 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -38,703 +40,7 @@ export class CoordinatorContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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 encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('getSignerAddress(bytes32,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getTransactionHash((uint256,address,bytes))'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.executeTransaction.callAsync( - transaction, - txOrigin, - transactionSignature, - approvalExpirationTimeSeconds, - approvalSignatures, - txDataWithDefaults, - ); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as CoordinatorContract; - const abiEncoder = self._lookupAbiEncoder( - 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - /** - * 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 encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('EIP712_COORDINATOR_DOMAIN_HASH()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -1110,6 +416,655 @@ export class CoordinatorContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = CoordinatorContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as CoordinatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Recovers the address of a signer given a hash and signature. + * @param hash Any 32 byte hash. + * @param signature Proof that the hash has been signed by signer. + */ + public getSignerAddress(hash: string, signature: string): ContractFunctionObj { + const self = (this as any) as CoordinatorContract; + assert.isString('hash', hash); + assert.isString('signature', signature); + + return { + 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 encodedData = self._strictEncodeArguments('getSignerAddress(bytes32,bytes)', [hash, signature]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getSignerAddress(bytes32,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getSignerAddress(bytes32,bytes)', [ + hash, + signature, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calculates the EIP712 hash of a 0x transaction using the domain separator of the Exchange contract. + * @param transaction 0x transaction containing salt, signerAddress, and data. + * @returns EIP712 hash of the transaction with the domain separator of this contract. + */ + public getTransactionHash(transaction: { + salt: BigNumber; + signerAddress: string; + data: string; + }): ContractFunctionObj { + const self = (this as any) as CoordinatorContract; + + return { + 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 encodedData = self._strictEncodeArguments('getTransactionHash((uint256,address,bytes))', [ + transaction, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTransactionHash((uint256,address,bytes))'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTransactionHash((uint256,address,bytes))', + [transaction], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calculated the EIP712 hash of the Coordinator approval mesasage using the domain separator of this contract. + * @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. + */ + public getCoordinatorApprovalHash(approval: { + txOrigin: string; + transactionHash: string; + transactionSignature: string; + approvalExpirationTimeSeconds: BigNumber; + }): ContractFunctionObj { + const self = (this as any) as CoordinatorContract; + + return { + 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 encodedData = self._strictEncodeArguments( + 'getCoordinatorApprovalHash((address,bytes32,bytes,uint256))', + [approval], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getCoordinatorApprovalHash((address,bytes32,bytes,uint256))', + [approval], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes a 0x transaction that has been signed by the feeRecipients that correspond to each order in the transaction's Exchange calldata. + * @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. + */ + public executeTransaction( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + ): ContractTxFunctionObj { + const self = (this as any) as CoordinatorContract; + + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'executeTransaction((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + return abiEncodedTransactionData; + }, + }; + } + public EIP712_EXCHANGE_DOMAIN_HASH(): ContractFunctionObj { + const self = (this as any) as CoordinatorContract; + + return { + 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 encodedData = self._strictEncodeArguments('EIP712_EXCHANGE_DOMAIN_HASH()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('EIP712_EXCHANGE_DOMAIN_HASH()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Validates that the 0x transaction has been approved by all of the feeRecipients + * that correspond to each order in the transaction's Exchange calldata. + * @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. + */ + public assertValidCoordinatorApprovals( + transaction: { salt: BigNumber; signerAddress: string; data: string }, + txOrigin: string, + transactionSignature: string, + approvalExpirationTimeSeconds: BigNumber[], + approvalSignatures: string[], + ): ContractFunctionObj { + const self = (this as any) as CoordinatorContract; + + assert.isString('txOrigin', txOrigin); + assert.isString('transactionSignature', transactionSignature); + assert.isArray('approvalExpirationTimeSeconds', approvalExpirationTimeSeconds); + assert.isArray('approvalSignatures', approvalSignatures); + + return { + 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 encodedData = self._strictEncodeArguments( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'assertValidCoordinatorApprovals((uint256,address,bytes),address,bytes,uint256[],bytes[])', + [ + transaction, + txOrigin.toLowerCase(), + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decodes the orders from Exchange calldata representing any fill method. + * @param data Exchange calldata representing a fill method. + * @returns The orders from the Exchange calldata. + */ + public decodeOrdersFromFillData( + data: string, + ): ContractFunctionObj< + 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; + assert.isString('data', data); + + return { + async callAsync( + 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.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeOrdersFromFillData(bytes)', [data]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeOrdersFromFillData(bytes)', [ + data, + ]); + return abiEncodedTransactionData; + }, + }; + } + public EIP712_COORDINATOR_DOMAIN_HASH(): ContractFunctionObj { + const self = (this as any) as CoordinatorContract; + + return { + 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 encodedData = self._strictEncodeArguments('EIP712_COORDINATOR_DOMAIN_HASH()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP712_COORDINATOR_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('EIP712_COORDINATOR_DOMAIN_HASH()', []); + return abiEncodedTransactionData; + }, + }; + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -1127,6 +1082,12 @@ export class CoordinatorContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + CoordinatorContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 57abe22dc0..bcb482e3d3 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/coordinator_registry.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/coordinator_registry.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -50,222 +53,7 @@ export class CoordinatorRegistryContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.setCoordinatorEndpoint.callAsync(coordinatorEndpoint, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('coordinatorEndpoint', coordinatorEndpoint); - const self = (this as any) as CoordinatorRegistryContract; - const txHashPromise = self.setCoordinatorEndpoint.sendTransactionAsync(coordinatorEndpoint, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(coordinatorEndpoint: string): string { - assert.isString('coordinatorEndpoint', coordinatorEndpoint); - const self = (this as any) as CoordinatorRegistryContract; - const abiEncodedTransactionData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [ - coordinatorEndpoint, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as CoordinatorRegistryContract; - const abiEncoder = self._lookupAbiEncoder('setCoordinatorEndpoint(string)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getCoordinatorEndpoint(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -403,6 +191,209 @@ export class CoordinatorRegistryContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = CoordinatorRegistryContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as CoordinatorRegistryContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Called by a Coordinator operator to set the endpoint of their Coordinator. + * @param coordinatorEndpoint endpoint of the Coordinator. + */ + public setCoordinatorEndpoint(coordinatorEndpoint: string): ContractTxFunctionObj { + const self = (this as any) as CoordinatorRegistryContract; + assert.isString('coordinatorEndpoint', coordinatorEndpoint); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [ + coordinatorEndpoint, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setCoordinatorEndpoint(string)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('setCoordinatorEndpoint(string)', [ + coordinatorEndpoint, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets the endpoint for a Coordinator. + * @param coordinatorOperator operator of the Coordinator endpoint. + */ + public getCoordinatorEndpoint(coordinatorOperator: string): ContractFunctionObj { + const self = (this as any) as CoordinatorRegistryContract; + assert.isString('coordinatorOperator', coordinatorOperator); + + return { + 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 encodedData = self._strictEncodeArguments('getCoordinatorEndpoint(address)', [ + coordinatorOperator.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getCoordinatorEndpoint(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getCoordinatorEndpoint(address)', [ + coordinatorOperator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the CoordinatorRegistry contract. * @param eventName The CoordinatorRegistry contract event you would like to subscribe to. @@ -492,6 +483,12 @@ export class CoordinatorRegistryContract extends BaseContract { CoordinatorRegistryContract.ABI(), this._web3Wrapper, ); + CoordinatorRegistryContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/dev_utils.ts b/packages/abi-gen-wrappers/src/generated-wrappers/dev_utils.ts index 0d6ca74e75..4d18ea0ae6 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/dev_utils.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/dev_utils.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -39,2682 +41,86 @@ export class DevUtilsContract extends BaseContract { */ public static deployedBytecode = '0x608060405234801561001057600080fd5b50600436106102c85760003560e01c80639a7e75261161017b578063cafd3a07116100d8578063d46950281161008c578063e4e6e7da11610071578063e4e6e7da14610711578063e77286eb14610732578063ee4f5a9414610754576102c8565b8063d4695028146106cf578063e25cabf7146106ef576102c8565b8063d186037f116100bd578063d186037f14610689578063d36379051461069c578063d3d862d1146106bc576102c8565b8063cafd3a0714610655578063d001c5dc14610676576102c8565b8063acaedc741161012f578063bbb2dcf611610114578063bbb2dcf6146105ef578063bc03f96414610611578063ca49f47c14610632576102c8565b8063acaedc74146105b9578063b43cffe1146105dc576102c8565b8063a0901e5111610160578063a0901e5114610573578063a5cd62ba14610586578063a6627e9f146105a6576102c8565b80639a7e75261461052c5780639eadc8351461054f576102c8565b806346eb65cb116102295780636f83188e116101dd5780637b66ad34116101c25780637b66ad34146104e55780637d727512146105065780638f4ce47914610519576102c8565b80636f83188e146104a15780637914b2ec146104c4576102c8565b8063590aa8751161020e578063590aa8751461044c57806363eb39921461046c578063651290421461047f576102c8565b806346eb65cb146104175780634dfdac201461042c576102c8565b8063314853ff1161028057806332aae3ad1161026557806332aae3ad146103b15780633db6dc61146103d3578063459be5e2146103f6576102c8565b8063314853ff1461037c578063327d30541461039e576102c8565b80630d7b7d76116102b15780630d7b7d7614610319578063165979e11461033a5780632322cf761461035c576102c8565b806302d0aec3146102cd57806304a5618a146102f7575b600080fd5b6102e06102db366004614f2d565b610776565b6040516102ee929190615836565b60405180910390f35b61030a610305366004614f2d565b6107d2565b6040516102ee93929190615931565b61032c610327366004614a5e565b610880565b6040516102ee9291906157e4565b61034d610348366004614f2d565b6108a2565b6040516102ee93929190615a6e565b61036f61036a366004614a5e565b6108ff565b6040516102ee9190615cdc565b61038f61038a366004614f2d565b610927565b6040516102ee9392919061580b565b61032c6103ac366004614f2d565b61096e565b6103c46103bf366004614f2d565b6109b0565b6040516102ee939291906159e2565b6103e66103e1366004614f2d565b610a03565b6040516102ee94939291906157aa565b610409610404366004614f2d565b610a4d565b6040516102ee929190615a56565b61042a610425366004614f2d565b610aa3565b005b61043f61043a366004614985565b610c36565b6040516102ee9190615744565b61045f61045a3660046147fe565b610cb9565b6040516102ee9190615991565b61045f61047a366004614aa2565b610d3d565b61049261048d366004614f2d565b610dc8565b6040516102ee93929190615511565b6104b46104af366004614f2d565b610e02565b6040516102ee9493929190615ae0565b6104d76104d2366004614f2d565b611943565b6040516102ee929190615868565b6104f86104f3366004614f2d565b61197b565b6040516102ee9291906154f7565b61036f610514366004614a5e565b6119b3565b6104d7610527366004614f2d565b6120c8565b61053f61053a366004614f2d565b612158565b6040516102ee9493929190615a9c565b61056261055d366004614f2d565b6121b9565b6040516102ee95949392919061588b565b61043f610581366004614b24565b612264565b610599610594366004614b8a565b6122dd565b6040516102ee919061565d565b61045f6105b4366004614af9565b6123a0565b6105cc6105c7366004614f2d565b612427565b6040516102ee94939291906155b9565b61045f6105ea3660046149d3565b612463565b6106026105fd366004614f2d565b6124f0565b6040516102ee9392919061595c565b61062461061f366004614f2d565b61259d565b6040516102ee9291906157f2565b610645610640366004614f2d565b6125d6565b6040516102ee94939291906158ee565b610668610663366004614f2d565b612687565b6040516102ee929190615ad3565b61043f610684366004614985565b6126d5565b61036f610697366004614a5e565b612743565b6106af6106aa366004614fe4565b612d86565b6040516102ee9190615a89565b61045f6106ca366004614d32565b613323565b6106e26106dd366004614f2d565b61335b565b6040516102ee9190615853565b6107026106fd366004614c0e565b6134a7565b6040516102ee939291906156a9565b61072461071f366004614985565b6135df565b6040516102ee929190615785565b61074561074036600461503c565b6135f8565b6040516102ee93929190615c80565b610767610762366004614f2d565b613832565b6040516102ee93929190615a2c565b60008061078a8361078561386f565b613893565b60006107a360048551866138ed9092919063ffffffff16565b8060200190516107b69190810190614ee0565b909350905060ff811660068111156107ca57fe5b915050915091565b600080806107e6848263ffffffff61393016565b92506001600160e01b031983167f025717920000000000000000000000000000000000000000000000000000000014610854576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b60405180910390fd5b61086584601063ffffffff61396416565b915061087884602463ffffffff61399716565b929491935050565b60008061088d84846119b3565b91506108998484612743565b90509250929050565b60008060006108b3846107856139a3565b60006108cc60048651876138ed9092919063ffffffff16565b8060200190516108df9190810190615270565b9094509250905060ff811660028111156108f557fe5b9350509193909250565b600080600061090e8585610880565b9150915061091c82826139c7565b925050505b92915050565b6000606080610938846107856139dd565b835161094e90859060049063ffffffff6138ed16565b8060200190516109619190810190614e80565b9196909550909350915050565b60008061097d83610785613a01565b825161099390849060049063ffffffff6138ed16565b8060200190516109a69190810190614e22565b9094909350915050565b60008060606109c184610785613a25565b60006109da60048651876138ed9092919063ffffffff16565b8060200190516109ed9190810190615224565b9094509250905060ff811660018111156108f557fe5b600080606080610a1585610785613a49565b8451610a2b90869060049063ffffffff6138ed16565b806020019051610a3e9190810190614dde565b92989197509550909350915050565b600080610a5c83610785613a6d565b6000610a7560048551866138ed9092919063ffffffff16565b806020019051610a889190810190615157565b9250905060ff81166003811115610a9b57fe5b925050915091565b6000610ab5828263ffffffff61393016565b90506001600160e01b031981167ff47261b0000000000000000000000000000000000000000000000000000000001415610af957610af2826120c8565b5050610c32565b6001600160e01b031981167f02571792000000000000000000000000000000000000000000000000000000001415610b3c57610b34826107d2565b505050610c32565b6001600160e01b031981167fa7cb5fb7000000000000000000000000000000000000000000000000000000001415610b8157610b77826121b9565b5050505050610c32565b6001600160e01b031981167f94cfcdd7000000000000000000000000000000000000000000000000000000001415610bbc57610b34826124f0565b6001600160e01b031981167fc339d10a000000000000000000000000000000000000000000000000000000001415610c0057610bf7826125d6565b50505050610c32565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b5050565b606060008251905080604051908082528060200260200182016040528015610c68578160200160208202803883390190505b50915060005b818114610cb157610c9285858381518110610c8557fe5b6020026020010151612743565b838281518110610c9e57fe5b6020908102919091010152600101610c6e565b505092915050565b6040516060907ff47261b00000000000000000000000000000000000000000000000000000000090610cef9084906024016154e3565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b0319909316929092179091529050919050565b6040516060907fc339d10a0000000000000000000000000000000000000000000000000000000090610d7790869086908690602401615587565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b03199093169290921790915290505b9392505050565b6000806000610dd984610785613a91565b8351610def90859060049063ffffffff6138ed16565b8060200190516109619190810190614853565b60608080806000610e19868263ffffffff61393016565b90506001600160e01b031981167fdedfc1f1000000000000000000000000000000000000000000000000000000001415610e8a576040518060400160405280601181526020017f626174636843616e63656c4f72646572730000000000000000000000000000008152509450611419565b6001600160e01b031981167f9694a402000000000000000000000000000000000000000000000000000000001415610ef9576040518060400160405280600f81526020017f626174636846696c6c4f726465727300000000000000000000000000000000008152509450611419565b6001600160e01b031981167f8ea8dfe4000000000000000000000000000000000000000000000000000000001415610f68576040518060400160405280601681526020017f626174636846696c6c4f72646572734e6f5468726f77000000000000000000008152509450611419565b6001600160e01b031981167fbeee2e14000000000000000000000000000000000000000000000000000000001415610fd7576040518060400160405280601581526020017f626174636846696c6c4f724b696c6c4f726465727300000000000000000000008152509450611419565b6001600160e01b031981167f2da62987000000000000000000000000000000000000000000000000000000001415611046576040518060400160405280600b81526020017f63616e63656c4f726465720000000000000000000000000000000000000000008152509450611419565b6001600160e01b031981167f9b44d5560000000000000000000000000000000000000000000000000000000014156110b5576040518060400160405280600981526020017f66696c6c4f7264657200000000000000000000000000000000000000000000008152509450611419565b6001600160e01b031981167fe14b58c4000000000000000000000000000000000000000000000000000000001415611124576040518060400160405280600f81526020017f66696c6c4f724b696c6c4f7264657200000000000000000000000000000000008152509450611419565b6001600160e01b031981167f78d29ac1000000000000000000000000000000000000000000000000000000001415611193576040518060400160405280601681526020017f6d61726b65744275794f72646572734e6f5468726f77000000000000000000008152509450611419565b6001600160e01b031981167f369da099000000000000000000000000000000000000000000000000000000001415611202576040518060400160405280601781526020017f6d61726b657453656c6c4f72646572734e6f5468726f770000000000000000008152509450611419565b6001600160e01b031981167f8bc8efb3000000000000000000000000000000000000000000000000000000001415611271576040518060400160405280601981526020017f6d61726b65744275794f726465727346696c6c4f724b696c6c000000000000008152509450611419565b6001600160e01b031981167fa6c3bf330000000000000000000000000000000000000000000000000000000014156112e0576040518060400160405280601a81526020017f6d61726b657453656c6c4f726465727346696c6c4f724b696c6c0000000000008152509450611419565b6001600160e01b031981167f88ec79fb00000000000000000000000000000000000000000000000000000000141561134f576040518060400160405280600b81526020017f6d617463684f72646572730000000000000000000000000000000000000000008152509450611419565b6001600160e01b031981167f4f9559b10000000000000000000000000000000000000000000000000000000014806113b057506001600160e01b031981167f2280c91000000000000000000000000000000000000000000000000000000000145b156113e7576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615bdb565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615ba4565b6001600160e01b031981167fdedfc1f10000000000000000000000000000000000000000000000000000000014156114be57855161146190879060049063ffffffff613ab516565b8060200190516114749190810190614b57565b604080516000808252602082019092529195505b50604080516000808252602082019092529194506114b6565b60608152602001906001900390816114a15790505b50915061193b565b6001600160e01b031981167fbeee2e1400000000000000000000000000000000000000000000000000000000148061151f57506001600160e01b031981167f9694a40200000000000000000000000000000000000000000000000000000000145b8061155357506001600160e01b031981167f8ea8dfe400000000000000000000000000000000000000000000000000000000145b1561156d5761156186613b35565b9195509350915061193b565b6001600160e01b031981167f2da629870000000000000000000000000000000000000000000000000000000014156116555760408051600180825281830190925290816020015b6115bc614131565b8152602001906001900390816115b457505086519094506115e790879060049063ffffffff613ab516565b8060200190516115fa9190810190614fb1565b8460008151811061160757fe5b602002602001018190525060006040519080825280602002602001820160405280156114885781602001602082028038833901905050604080516000808252602082019092529194506114b6565b6001600160e01b031981167fe14b58c40000000000000000000000000000000000000000000000000000000014806116b657506001600160e01b031981167f9b44d55600000000000000000000000000000000000000000000000000000000145b156116c45761156186613b64565b6001600160e01b031981167f78d29ac100000000000000000000000000000000000000000000000000000000148061172557506001600160e01b031981167f369da09900000000000000000000000000000000000000000000000000000000145b8061175957506001600160e01b031981167f8bc8efb300000000000000000000000000000000000000000000000000000000145b8061178d57506001600160e01b031981167fa6c3bf3300000000000000000000000000000000000000000000000000000000145b1561179b5761156186613c5e565b6001600160e01b031981167f88ec79fb00000000000000000000000000000000000000000000000000000000141561193b576117d5614131565b6117dd614131565b6060806117f760048b518c613ab59092919063ffffffff16565b80602001905161180a9190810190615093565b604080516002808252606082019092529498509296509094509250816020015b611832614131565b81526020019060019003908161182a579050509750838860008151811061185557fe5b6020026020010181905250828860018151811061186e57fe5b602090810291909101015260408051600280825260608201909252908160200160208202803883390190505096508360a00151876000815181106118ae57fe5b6020026020010181815250508260a00151876001815181106118cc57fe5b60209081029190910101526040805160028082526060820190925290816020015b60608152602001906001900390816118ed579050509550818660008151811061191257fe5b6020026020010181905250808660018151811061192b57fe5b6020026020010181905250505050505b509193509193565b60008061195283610785613cd2565b825161196890849060049063ffffffff6138ed16565b8060200190516109a69190810190614f04565b60008061198a83610785613cf6565b82516119a090849060049063ffffffff6138ed16565b8060200190516109a6919081019061481a565b6000806119c6838263ffffffff61393016565b90506001600160e01b031981167ff47261b0000000000000000000000000000000000000000000000000000000001415611b3b576000611a0d84601063ffffffff61396416565b6040519091506060907f70a082310000000000000000000000000000000000000000000000000000000090611a469088906024016154e3565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060006060836001600160a01b031683604051611ac191906154c7565b600060405180830381855afa9150503d8060008114611afc576040519150601f19603f3d011682016040523d82523d6000602084013e611b01565b606091505b5091509150818015611b14575080516020145b611b1f576000611b30565b611b3081600063ffffffff61399716565b9550505050506120c1565b6001600160e01b031981167f02571792000000000000000000000000000000000000000000000000000000001415611cd657600080611b79856107d2565b6040519194509250606091507f6352211e0000000000000000000000000000000000000000000000000000000090611bb5908490602401615cdc565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060006060846001600160a01b031683604051611c3091906154c7565b600060405180830381855afa9150503d8060008114611c6b576040519150601f19603f3d011682016040523d82523d6000602084013e611c70565b606091505b50915091506000828015611c85575081516020145b611c90576000611ca1565b611ca182600c63ffffffff61396416565b9050896001600160a01b0316816001600160a01b031614611cc3576000611cc6565b60015b60ff1697505050505050506120c1565b6001600160e01b031981167fa7cb5fb7000000000000000000000000000000000000000000000000000000001415611eb9576000606080611d16866121b9565b5081519296509094509250905060005b818114611eaf5783516060907efdd58e00000000000000000000000000000000000000000000000000000000908b90879085908110611d6157fe5b6020026020010151604051602401611d7a9291906155ed565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060006060876001600160a01b031683604051611df591906154c7565b600060405180830381855afa9150503d8060008114611e30576040519150601f19603f3d011682016040523d82523d6000602084013e611e35565b606091505b50915091506000828015611e4a575081516020145b611e55576000611e66565b611e6682600063ffffffff61399716565b90506000878681518110611e7657fe5b60200260200101518281611e8657fe5b0490508b811080611e9557508b155b15611e9e57809b505b505060019093019250611d26915050565b50505050506120c1565b6001600160e01b031981167fc339d10a00000000000000000000000000000000000000000000000000000000141561200a576040516060907fa85e59e40000000000000000000000000000000000000000000000000000000090611f28908690600090819081906024016159a4565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b03199094169390931790925260045491519092506000916001600160a01b031690611f8f9084906154c7565b600060405180830381855afa9150503d8060008114611fca576040519150601f19603f3d011682016040523d82523d6000602084013e611fcf565b606091505b5050905080611fdf576000612001565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff5b935050506120c1565b6001600160e01b031981167f94cfcdd70000000000000000000000000000000000000000000000000000000014156120c157606080612048856124f0565b80519194509250905060005b8181146120bc57600061207a8985848151811061206d57fe5b60200260200101516119b3565b9050600085838151811061208a57fe5b6020026020010151828161209a57fe5b049050878110806120a9575087155b156120b2578097505b5050600101612054565b505050505b5092915050565b6000806120db838263ffffffff61393016565b91506001600160e01b031982167ff47261b00000000000000000000000000000000000000000000000000000000014612140576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b61215183601063ffffffff61396416565b9050915091565b6000806000606061216b85610785613d1a565b600061218460048751886138ed9092919063ffffffff16565b80602001905161219791908101906151c6565b91965094509250905060ff811660068111156121af57fe5b9450509193509193565b600080606080806121d0868563ffffffff61393016565b94506001600160e01b031985167fa7cb5fb70000000000000000000000000000000000000000000000000000000014612235576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b505050506024828101516044840151606485015160848601519496929591820184019490820184019391010190565b6060808251604051908082528060200260200182016040528015612292578160200160208202803883390190505b50905060005b835181146120c1578381815181106122ac57fe5b60200260200101516001600160a01b0316318282815181106122ca57fe5b6020908102919091010152600101612298565b60606000845190508060405190808252806020026020018201604052801561230f578160200160208202803883390190505b50915060005b8181146123975761236086828151811061232b57fe5b602002602001015186838151811061233f57fe5b602002602001015186848151811061235357fe5b6020026020010151612d86565b83828151811061236c57fe5b6020026020010190600481111561237f57fe5b9081600481111561238c57fe5b905250600101612315565b50509392505050565b6040516060907f0257179200000000000000000000000000000000000000000000000000000000906123d890859085906024016155ed565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b031990931692909217909152905092915050565b6000606080606061243a85610785613d3e565b845161245090869060049063ffffffff6138ed16565b806020019051610a3e91908101906148ed565b6040516060907fa7cb5fb7000000000000000000000000000000000000000000000000000000009061249f908790879087908790602401615535565b60408051601f198184030181529190526020810180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b0319909316929092179091529050949350505050565b6000606080612505848463ffffffff61393016565b92506001600160e01b031983167f94cfcdd7000000000000000000000000000000000000000000000000000000001461256a576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b835161258090859060049063ffffffff613ab516565b8060200190516125939190810190614d67565b9395909450915050565b600060606125ad83610785613d62565b82516125c390849060049063ffffffff6138ed16565b8060200190516109a69190810190614e45565b6000806060816125ec858263ffffffff61393016565b93506001600160e01b031984167fc339d10a0000000000000000000000000000000000000000000000000000000014612651576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b845161266790869060049063ffffffff613ab516565b80602001905161267a9190810190614895565b9597919650949350915050565b60008061269683610785613d86565b60006126af60048551866138ed9092919063ffffffff16565b8060200190516126c29190810190615157565b9250905060ff81166001811115610a9b57fe5b606060008251905080604051908082528060200260200182016040528015612707578160200160208202803883390190505b50915060005b818114610cb1576127248585838151811061206d57fe5b83828151811061273057fe5b602090810291909101015260010161270d565b600080612756838263ffffffff61393016565b90506001600160e01b031981167f94cfcdd700000000000000000000000000000000000000000000000000000000141561280857606080612796856124f0565b80519194509250905060005b8181146127fd5760006127bb89858481518110610c8557fe5b905060008583815181106127cb57fe5b602002602001015182816127db57fe5b049050878110806127ea575087155b156127f3578097505b50506001016127a2565b506109219350505050565b6001600160e01b031981167ff47261b000000000000000000000000000000000000000000000000000000000141561289357600061284d84601063ffffffff61396416565b6001546040519192506060917fdd62ed3e0000000000000000000000000000000000000000000000000000000091611a469189916001600160a01b0316906024016154f7565b6001600160e01b031981167f02571792000000000000000000000000000000000000000000000000000000001415612b83576000806128d1856107d2565b600254604051929550909350606092507fe985e9c5000000000000000000000000000000000000000000000000000000009161291d918a916001600160a01b03909116906024016154f7565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060006060846001600160a01b03168360405161299891906154c7565b600060405180830381855afa9150503d80600081146129d3576040519150601f19603f3d011682016040523d82523d6000602084013e6129d8565b606091505b50915091508115806129ec57508051602014155b80612a085750612a0381600063ffffffff61399716565b600114155b15612b56576040516060907f081812fc0000000000000000000000000000000000000000000000000000000090612a43908790602401615cdc565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff83818316178352505050509050856001600160a01b031681604051612aba91906154c7565b600060405180830381855afa9150503d8060008114612af5576040519150601f19603f3d011682016040523d82523d6000602084013e612afa565b606091505b509093509150828015612b0e575081516020145b8015612b3d57506002546001600160a01b0316612b3283600c63ffffffff61396416565b6001600160a01b0316145b612b48576000612b4b565b60015b60ff16975050611eaf565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff965050505050506120c1565b6001600160e01b031981167fa7cb5fb7000000000000000000000000000000000000000000000000000000001415612d2b576000612bc0846121b9565b5050600354604051929450606093507fe985e9c50000000000000000000000000000000000000000000000000000000092612c0a925089916001600160a01b0316906024016154f7565b604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff8381831617835250505050905060006060836001600160a01b031683604051612c8591906154c7565b600060405180830381855afa9150503d8060008114612cc0576040519150601f19603f3d011682016040523d82523d6000602084013e612cc5565b606091505b5091509150818015612cd8575080516020145b8015612cf45750612cf081600063ffffffff61399716565b6001145b612cff576000611b30565b7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9550505050506120c1565b6001600160e01b031981167fc339d10a0000000000000000000000000000000000000000000000000000000014156120c157507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff9392505050565b6000612d906141c4565b612e218584600560009054906101000a90046001600160a01b03166001600160a01b0316631ce4c78b6040518163ffffffff1660e01b815260040160206040518083038186803b158015612de357600080fd5b505afa158015612df7573d6000803e3d6000fd5b505050506040513d601f19601f82011682018060405250612e1b919081019061513f565b3a613daa565b60408051600480825260a0820190925291925060609190816020015b6060815260200190600190039081612e3d57505060408051600480825260a082019092529192506060919060208201608080388339505060408051600480825260a08201909252929350606092915060208201608080388339505060408051600480825260a0820190925292935060609291506020820160808038833901905050905088610160015184600081518110612ed357fe5b60200260200101819052508783600081518110612eec57fe5b60200260200101906001600160a01b031690816001600160a01b031681525050886000015182600081518110612f1e57fe5b60200260200101906001600160a01b031690816001600160a01b0316815250508681600081518110612f4c57fe5b60200260200101818152505088610140015184600181518110612f6b57fe5b6020026020010181905250886000015183600181518110612f8857fe5b60200260200101906001600160a01b031690816001600160a01b0316815250508782600181518110612fb657fe5b60200260200101906001600160a01b031690816001600160a01b031681525050846000015181600181518110612fe857fe5b602002602001018181525050886101a001518460028151811061300757fe5b6020026020010181905250878360028151811061302057fe5b60200260200101906001600160a01b031690816001600160a01b03168152505088604001518260028151811061305257fe5b60200260200101906001600160a01b031690816001600160a01b03168152505084606001518160028151811061308457fe5b602002602001018181525050886101800151846003815181106130a357fe5b60200260200101819052508860000151836003815181106130c057fe5b60200260200101906001600160a01b031690816001600160a01b0316815250508860400151826003815181106130f257fe5b60200260200101906001600160a01b031690816001600160a01b03168152505084604001518160038151811061312457fe5b60209081029190910101526040516060907fb04fbddd000000000000000000000000000000000000000000000000000000009061316b908790879087908790602401615606565b60408051601f198184030181529181526020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff166001600160e01b03199094169390931790925260055491519092506060916001600160a01b0316906131d29084906154c7565b6000604051808303816000865af19150503d806000811461320f576040519150601f19603f3d011682016040523d82523d6000602084013e613214565b606091505b5091506000905061322b828263ffffffff61393016565b9050613235613a25565b6001600160e01b031982811691161415613277576000613254836109b0565b5091505060ff8116600481111561326757fe5b9950505050505050505050610dc1565b61327f6139dd565b6001600160e01b0319828116911614156132b257600061329e83610927565b509091505060ff8116600481111561326757fe5b815160208301207ff43f26ea5a94b478394a975e856464913dc1a8a1ca70939d974aa7c238aa0ce014156132f157600498505050505050505050610dc1565b6040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615b6d565b6040516060907f94cfcdd700000000000000000000000000000000000000000000000000000000906123d89085908590602401615757565b600061336d828263ffffffff61393016565b90506001600160e01b031981167ff47261b00000000000000000000000000000000000000000000000000000000014806133d057506001600160e01b031981167f0257179200000000000000000000000000000000000000000000000000000000145b8061340457506001600160e01b031981167fa7cb5fb700000000000000000000000000000000000000000000000000000000145b8061343857506001600160e01b031981167f94cfcdd700000000000000000000000000000000000000000000000000000000145b8061346c57506001600160e01b031981167fc339d10a00000000000000000000000000000000000000000000000000000000145b6134a2576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c49565b919050565b6060806060600085519050806040519080825280602002602001820160405280156134ec57816020015b6134d96141f3565b8152602001906001900390816134d15790505b50935080604051908082528060200260200182016040528015613519578160200160208202803883390190505b50925080604051908082528060200260200182016040528015613546578160200160208202803883390190505b50915060005b8181146135d65761358387828151811061356257fe5b602002602001015187838151811061357657fe5b60200260200101516135f8565b875188908590811061359157fe5b602002602001018785815181106135a457fe5b602002602001018786815181106135b757fe5b931515602094850291909101909301929092529190525260010161354c565b50509250925092565b6060806135ec84846126d5565b91506108998484610c36565b6136006141f3565b600080546040517f9d3fa4b900000000000000000000000000000000000000000000000000000000815282916001600160a01b031690639d3fa4b99061364a908890600401615ca4565b60606040518083038186803b15801561366257600080fd5b505afa158015613676573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061369a9190810190614f60565b85516000546040517fa12dcc6f00000000000000000000000000000000000000000000000000000000815292955090916001600160a01b039091169063a12dcc6f906136ec9089908990600401615cb7565b60206040518083038186803b15801561370457600080fd5b505afa158015613718573d6000803e3d6000fd5b505050506040513d601f19601f8201168201806040525061373c9190810190614dbe565b9150600061374f828861014001516108ff565b60a088015160c08901516101808a01516101408b01519394509192909160009161377e9163ffffffff613e2116565b156137ab576137a48461379e848d60800151613e4690919063ffffffff16565b85613e62565b9050613804565b816137bf576137a4848b6080015185613e62565b60006137d0868c61018001516108ff565b905060006137e3868d6080015187613e62565b905060006137f2838688613e62565b90506137fe82826139c7565b93505050505b61382461381e896040015185613e8c90919063ffffffff16565b826139c7565b965050505050509250925092565b600080600061384384610785613eab565b600061385c60048651876138ed9092919063ffffffff16565b8060200190516108df9190810190615184565b7ffdb6ca8d0000000000000000000000000000000000000000000000000000000090565b60006138a0836000613930565b90506001600160e01b0319808216908316146138e8576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040161084b90615c12565b505050565b60608183111561390b5761390b61390660008585613ecf565b613eee565b8351821115613924576139246139066001848751613ecf565b50819003910190815290565b60008160040183511015613951576139516139066003855185600401613ecf565b5001602001516001600160e01b03191690565b60008160140183511015613985576139856139066004855185601401613ecf565b5001601401516001600160a01b031690565b6000610dc18383613ef6565b7f18e4b1410000000000000000000000000000000000000000000000000000000090565b60008183106139d65781610dc1565b5090919050565b7f4678472b0000000000000000000000000000000000000000000000000000000090565b7fb6555d6f0000000000000000000000000000000000000000000000000000000090565b7f488219a60000000000000000000000000000000000000000000000000000000090565b7f1b8388f70000000000000000000000000000000000000000000000000000000090565b7fe94a7ed00000000000000000000000000000000000000000000000000000000090565b7f4ad312750000000000000000000000000000000000000000000000000000000090565b606081831115613ace57613ace61390660008585613ecf565b8351821115613ae757613ae76139066001848751613ecf565b8282036040519080825280601f01601f191660200182016040528015613b14576020820181803883390190505b509050610dc1613b2382613f20565b84613b2d87613f20565b018351613f26565b6060806060613b516004855186613ab59092919063ffffffff16565b8060200190516109619190810190614c65565b60408051600180825281830190925260609182918291816020015b613b87614131565b815260200190600190039081613b7f5750506040805160018082528183019092529194506020808301908038833901905050604080516001808252818301909252919350816020015b6060815260200190600190039081613bd05750508451909150613bfd90859060049063ffffffff613ab516565b806020019051613c1091908101906150ec565b85600081518110613c1d57fe5b6020026020010185600081518110613c3157fe5b6020026020010185600081518110613c4557fe5b6020908102919091010192909252919052529193909250565b604080516001808252818301909252606091829182916020808301908038833950508551919350613c9a9186915060049063ffffffff613ab516565b806020019051613cad9190810190614cdf565b84518590600090613cba57fe5b60209081029190910101919091529095929450925050565b7f11c7b7200000000000000000000000000000000000000000000000000000000090565b7fa15c0d060000000000000000000000000000000000000000000000000000000090565b7f7e5a23180000000000000000000000000000000000000000000000000000000090565b7f5bd0428d0000000000000000000000000000000000000000000000000000000090565b7f20d11f610000000000000000000000000000000000000000000000000000000090565b7ff59851840000000000000000000000000000000000000000000000000000000090565b613db26141c4565b6020810184905260a08501516080860151613dce918691613fcb565b815260a085015160c0860151613de5918691613fcb565b604082015260a085015160e0860151613dff918691613fcb565b6060820152613e14828463ffffffff613fff16565b6080820152949350505050565b600081518351148015610dc15750508051602091820120825192909101919091201490565b600082820183811015610dc157610dc16139066000868661402c565b6000613e8483613e78868563ffffffff613fff16565b9063ffffffff61404b16565b949350505050565b600082821115613ea557613ea56139066002858561402c565b50900390565b7fe53c76c80000000000000000000000000000000000000000000000000000000090565b6060632800659560e01b848484604051602401610d7793929190615a7b565b805160208201fd5b60008160200183511015613f1757613f176139066005855185602001613ecf565b50016020015190565b60200190565b6020811015613f50576001816020036101000a0380198351168185511680821786525050506138e8565b82821415613f5d576138e8565b82821115613f975760208103905080820181840181515b82851015613f8f578451865260209586019590940193613f74565b9052506138e8565b60208103905080820181840183515b81861215613fc25782518252601f199283019290910190613fa6565b85525050505050565b6000613fd8848484614075565b15613feb57613feb6139068585856140db565b613e8483613e78868563ffffffff613fff16565b60008261400e57506000610921565b8282028284828161401b57fe5b0414610dc157610dc1613906600186865b606063e946c1bb60e01b848484604051602401610d7793929190615a0a565b600081614061576140616139066003858561402c565b600082848161406c57fe5b04949350505050565b600082614087576140876139066140fa565b811580614092575083155b1561409f57506000610dc1565b600083806140a957fe5b85840990506140be858463ffffffff613fff16565b6140d0826103e863ffffffff613fff16565b101595945050505050565b606063339f3de260e01b848484604051602401610d7793929190615ce5565b60408051808201909152600481527fa791837c00000000000000000000000000000000000000000000000000000000602082015290565b604051806101c0016040528060006001600160a01b0316815260200160006001600160a01b0316815260200160006001600160a01b0316815260200160006001600160a01b03168152602001600081526020016000815260200160008152602001600081526020016000815260200160008152602001606081526020016060815260200160608152602001606081525090565b6040518060a0016040528060008152602001600081526020016000815260200160008152602001600081525090565b604080516060810182526000808252602082018190529181019190915290565b803561092181615dc1565b805161092181615dc1565b600082601f830112614239578081fd5b813561424c61424782615d22565b615cfb565b81815291506020808301908481018184028601820187101561426d57600080fd5b60005b848110156120bc57813561428381615dc1565b84529282019290820190600101614270565b600082601f8301126142a5578081fd5b81516142b361424782615d22565b8181529150602080830190840160005b838110156142f0576142db8760208451890101614515565b835260209283019291909101906001016142c3565b5050505092915050565b600082601f83011261430a578081fd5b813561431861424782615d22565b8181529150602080830190840160005b838110156142f05761434087602084358901016144c7565b83526020928301929190910190600101614328565b600082601f830112614365578081fd5b815161437361424782615d22565b8181529150602080830190840160005b838110156142f05761439b87602084518901016146aa565b83526020928301929190910190600101614383565b600082601f8301126143c0578081fd5b81356143ce61424782615d22565b8181529150602080830190840160005b838110156142f0576143f6876020843589010161455b565b835260209283019291909101906001016143de565b600082601f83011261441b578081fd5b815161442961424782615d22565b81815291506020808301908481018184028601820187101561444a57600080fd5b60005b848110156120bc5781518452928201929082019060010161444d565b600082601f830112614479578081fd5b813561448761424782615d22565b8181529150602080830190848101818402860182018710156144a857600080fd5b60005b848110156120bc578135845292820192908201906001016144ab565b600082601f8301126144d7578081fd5b81356144e561424782615d42565b91508082528360208285010111156144fc57600080fd5b8060208401602084013760009082016020015292915050565b600082601f830112614525578081fd5b815161453361424782615d42565b915080825283602082850101111561454a57600080fd5b6120c1816020840160208601615d66565b60006101c080838503121561456e578182fd5b61457781615cfb565b9150506145848383614213565b81526145938360208401614213565b60208201526145a58360408401614213565b60408201526145b78360608401614213565b60608201526080820135608082015260a082013560a082015260c082013560c082015260e082013560e08201526101008083013581830152506101208083013581830152506101408083013567ffffffffffffffff8082111561461957600080fd5b614625868387016144c7565b8385015261016092508285013591508082111561464157600080fd5b61464d868387016144c7565b8385015261018092508285013591508082111561466957600080fd5b614675868387016144c7565b838501526101a092508285013591508082111561469157600080fd5b5061469e858286016144c7565b82840152505092915050565b60006101c08083850312156146bd578182fd5b6146c681615cfb565b9150506146d3838361421e565b81526146e2836020840161421e565b60208201526146f4836040840161421e565b6040820152614706836060840161421e565b60608201526080820151608082015260a082015160a082015260c082015160c082015260e082015160e08201526101008083015181830152506101208083015181830152506101408083015167ffffffffffffffff8082111561476857600080fd5b61477486838701614515565b8385015261016092508285015191508082111561479057600080fd5b61479c86838701614515565b838501526101809250828501519150808211156147b857600080fd5b6147c486838701614515565b838501526101a09250828501519150808211156147e057600080fd5b5061469e85828601614515565b805160ff8116811461092157600080fd5b60006020828403121561480f578081fd5b8135610dc181615dc1565b6000806040838503121561482c578081fd5b825161483781615dc1565b602084015190925061484881615dc1565b809150509250929050565b600080600060608486031215614867578081fd5b835161487281615dc1565b602085015190935061488381615dc1565b80925050604084015190509250925092565b6000806000606084860312156148a9578081fd5b83516148b481615dc1565b602085015190935067ffffffffffffffff8111156148d0578182fd5b6148dc86828701614515565b925050604084015190509250925092565b60008060008060808587031215614902578182fd5b845161490d81615dc1565b602086015190945067ffffffffffffffff8082111561492a578384fd5b61493688838901614515565b9450604087015191508082111561494b578384fd5b61495788838901614515565b9350606087015191508082111561496c578283fd5b5061497987828801614515565b91505092959194509250565b60008060408385031215614997578182fd5b82356149a281615dc1565b9150602083013567ffffffffffffffff8111156149bd578182fd5b6149c9858286016142fa565b9150509250929050565b600080600080608085870312156149e8578182fd5b84356149f381615dc1565b9350602085013567ffffffffffffffff80821115614a0f578384fd5b614a1b88838901614469565b94506040870135915080821115614a30578384fd5b614a3c88838901614469565b93506060870135915080821115614a51578283fd5b50614979878288016144c7565b60008060408385031215614a70578182fd5b8235614a7b81615dc1565b9150602083013567ffffffffffffffff811115614a96578182fd5b6149c9858286016144c7565b600080600060608486031215614ab6578081fd5b8335614ac181615dc1565b9250602084013567ffffffffffffffff811115614adc578182fd5b614ae8868287016144c7565b925050604084013590509250925092565b60008060408385031215614b0b578182fd5b8235614b1681615dc1565b946020939093013593505050565b600060208284031215614b35578081fd5b813567ffffffffffffffff811115614b4b578182fd5b613e8484828501614229565b600060208284031215614b68578081fd5b815167ffffffffffffffff811115614b7e578182fd5b613e8484828501614355565b600080600060608486031215614b9e578081fd5b833567ffffffffffffffff80821115614bb5578283fd5b614bc1878388016143b0565b94506020860135915080821115614bd6578283fd5b614be287838801614229565b93506040860135915080821115614bf7578283fd5b50614c0486828701614469565b9150509250925092565b60008060408385031215614c20578182fd5b823567ffffffffffffffff80821115614c37578384fd5b614c43868387016143b0565b93506020850135915080821115614c58578283fd5b506149c9858286016142fa565b600080600060608486031215614c79578081fd5b835167ffffffffffffffff80821115614c90578283fd5b614c9c87838801614355565b94506020860151915080821115614cb1578283fd5b614cbd8783880161440b565b93506040860151915080821115614cd2578283fd5b50614c0486828701614295565b600080600060608486031215614cf3578081fd5b835167ffffffffffffffff80821115614d0a578283fd5b614d1687838801614355565b9450602086015193506040860151915080821115614cd2578283fd5b60008060408385031215614d44578182fd5b823567ffffffffffffffff80821115614d5b578384fd5b614c4386838701614469565b60008060408385031215614d79578182fd5b825167ffffffffffffffff80821115614d90578384fd5b614d9c8683870161440b565b93506020850151915080821115614db1578283fd5b506149c985828601614295565b600060208284031215614dcf578081fd5b81518015158114610dc1578182fd5b60008060008060808587031215614df3578182fd5b845193506020850151614e0581615dc1565b604086015190935067ffffffffffffffff8082111561494b578384fd5b60008060408385031215614e34578182fd5b505080516020909101519092909150565b60008060408385031215614e57578182fd5b82519150602083015167ffffffffffffffff811115614e74578182fd5b6149c985828601614515565b600080600060608486031215614e94578081fd5b83519250602084015167ffffffffffffffff80821115614eb2578283fd5b614ebe87838801614515565b93506040860151915080821115614ed3578283fd5b50614c0486828701614515565b60008060408385031215614ef2578182fd5b82519150602083015161484881615dd6565b60008060408385031215614f16578182fd5b82516001600160e01b031981168114614837578283fd5b600060208284031215614f3e578081fd5b813567ffffffffffffffff811115614f54578182fd5b613e84848285016144c7565b60006060828403128015614f72578182fd5b8015614f7c578182fd5b50614f876060615cfb565b614f9184846147ed565b815260208301516020820152604083015160408201528091505092915050565b600060208284031215614fc2578081fd5b815167ffffffffffffffff811115614fd8578182fd5b613e84848285016146aa565b600080600060608486031215614ff8578081fd5b833567ffffffffffffffff81111561500e578182fd5b61501a8682870161455b565b935050602084013561502b81615dc1565b929592945050506040919091013590565b6000806040838503121561504e578182fd5b823567ffffffffffffffff80821115615065578384fd5b6150718683870161455b565b93506020850135915080821115615086578283fd5b506149c9858286016144c7565b600080600080608085870312156150a8578182fd5b845167ffffffffffffffff808211156150bf578384fd5b6150cb888389016146aa565b955060208701519150808211156150e0578384fd5b614936888389016146aa565b600080600060608486031215615100578081fd5b835167ffffffffffffffff80821115615117578283fd5b615123878388016146aa565b9450602086015193506040860151915080821115614ed3578283fd5b600060208284031215615150578081fd5b5051919050565b60008060408385031215615169578182fd5b825161517481615dd6565b6020939093015192949293505050565b600080600060608486031215615198578081fd5b83516151a381615dd6565b6020850151604086015191945092506151bb81615dc1565b809150509250925092565b600080600080608085870312156151db578182fd5b6151e586866147ed565b93506020850151925060408501516151fc81615dc1565b606086015190925067ffffffffffffffff811115615218578182fd5b61497987828801614515565b600080600060608486031215615238578081fd5b61524285856147ed565b925060208401519150604084015167ffffffffffffffff811115615264578182fd5b614c0486828701614515565b600080600060608486031215615284578081fd5b61528e85856147ed565b925060208401519150604084015190509250925092565b6001600160a01b03169052565b6000815180845260208401935060208301825b828110156152ec5781516001600160a01b03168652602095860195909101906001016152c5565b5093949350505050565b600081518084526020840180819550602083028101915060208501845b8481101561534157828403885261532b84835161537e565b6020988901989094509190910190600101615313565b50919695505050505050565b6000815180845260208401935060208301825b828110156152ec578151865260209586019590910190600101615360565b60008151808452615396816020860160208601615d66565b601f01601f19169290920160200192915050565b805160ff16825260208082015190830152604090810151910152565b60006101c06153d68484516152a5565b60208301516153e860208601826152a5565b5060408301516153fb60408601826152a5565b50606083015161540e60608601826152a5565b506080830151608085015260a083015160a085015260c083015160c085015260e083015160e08501526101008084015181860152506101208084015181860152506101408084015182828701526154678387018261537e565b91505061016091508184015185820383870152615484828261537e565b9250505061018080840151858303828701526154a0838261537e565b9150506101a0915081840151858203838701526154bd828261537e565b9695505050505050565b600082516154d9818460208701615d66565b9190910192915050565b6001600160a01b0391909116815260200190565b6001600160a01b0392831681529116602082015260400190565b6001600160a01b039384168152919092166020820152604081019190915260600190565b60006001600160a01b038616825260806020830152615557608083018661534d565b8281036040840152615569818661534d565b838103606085015261557b818661537e565b98975050505050505050565b60006001600160a01b0385168252606060208301526155a9606083018561537e565b9050826040830152949350505050565b60006001600160a01b0386168252608060208301526155db608083018661537e565b8281036040840152615569818661537e565b6001600160a01b03929092168252602082015260400190565b60006080825261561960808301876152f6565b828103602084015261562b81876152b2565b838103604085015261563d81876152b2565b9150508281036060840152615652818561534d565b979650505050505050565b602080825282518282018190526000918401906040840190835b8181101561569e57835161568a81615db7565b835260209384019390920191600101615677565b509095945050505050565b606080825284519082018190526000906020906080840190828801845b828110156156ec576156d98483516153aa565b60609390930192908401906001016156c6565b50505083810382850152615700818761534d565b84810360408601528551808252908301915082860190845b81811015615736578251151584529284019291840191600101615718565b509198975050505050505050565b600060208252610dc1602083018461534d565b60006040825261576a604083018561534d565b828103602084015261577c81856152f6565b95945050505050565b600060408252615798604083018561534d565b828103602084015261577c818561534d565b60008582526001600160a01b0385166020830152608060408301526157d2608083018561537e565b8281036060840152615652818561537e565b918252602082015260400190565b600083825260406020830152613e84604083018461537e565b600084825260606020830152615824606083018561537e565b82810360408401526154bd818561537e565b8281526040810161584683615dad565b8260208301529392505050565b6001600160e01b031991909116815260200190565b6001600160e01b03199290921682526001600160a01b0316602082015260400190565b60006001600160e01b0319871682526001600160a01b038616602083015260a060408301526158bd60a083018661534d565b82810360608401526158cf818661534d565b83810360808501526158e1818661537e565b9998505050505050505050565b60006001600160e01b0319861682526001600160a01b038516602083015260806040830152615920608083018561537e565b905082606083015295945050505050565b6001600160e01b03199390931683526001600160a01b03919091166020830152604082015260600190565b60006001600160e01b0319851682526060602083015261597f606083018561534d565b82810360408401526154bd81856152f6565b600060208252610dc1602083018461537e565b6000608082526159b7608083018761537e565b6001600160a01b03958616602084015293909416604082015260ff9190911660609091015292915050565b60006159ed85615d96565b8482528360208301526060604083015261577c606083018461537e565b6060810160048510615a1857fe5b938152602081019290925260409091015290565b60608101615a3985615da3565b93815260208101929092526001600160a01b031660409091015290565b6040810160048410615a6457fe5b9281526020015290565b60608101615a1885615da3565b6060810160088510615a1857fe5b60208101615a9683615db7565b91905290565b6000615aa786615dad565b8582528460208301526001600160a01b0384166040830152608060608301526154bd608083018461537e565b60408101615a6484615d96565b600060808252615af3608083018761537e565b602083820381850152818751808452828401915082838202850101838a01865b83811015615b4157601f19878403018552615b2f8383516153c6565b94860194925090850190600101615b13565b50508681036040880152615b55818a61534d565b945050505050828103606084015261565281856152f6565b60208082526013908201527f554e4b4e4f574e5f52455455524e5f4441544100000000000000000000000000604082015260600190565b60208082526019908201527f554e4b4e4f574e5f46554e4354494f4e5f53454c4543544f5200000000000000604082015260600190565b6020808252600d908201527f554e494d504c454d454e54454400000000000000000000000000000000000000604082015260600190565b6020808252600c908201527f4241445f53454c4543544f520000000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f57524f4e475f50524f58595f4944000000000000000000000000000000000000604082015260600190565b60a08101615c8e82866153aa565b8360608301528215156080830152949350505050565b600060208252610dc160208301846153c6565b600060408252615cca60408301856153c6565b828103602084015261577c818561537e565b90815260200190565b9283526020830191909152604082015260600190565b60405181810167ffffffffffffffff81118282101715615d1a57600080fd5b604052919050565b600067ffffffffffffffff821115615d38578081fd5b5060209081020190565b600067ffffffffffffffff821115615d58578081fd5b50601f01601f191660200190565b60005b83811015615d81578181015183820152602001615d69565b83811115615d90576000848401525b50505050565b60028110615da057fe5b50565b60038110615da057fe5b60078110615da057fe5b60058110615da057fe5b6001600160a01b0381168114615da057600080fd5b60ff81168114615da057600080fdfea365627a7a723158209bd08114ba2e3dada6fb089e11dba7dc3bfedf454a0bac82e7a05d67b08360dd6c6578706572696d656e74616cf564736f6c634300050c0040'; - /** - * Decompose an ABI-encoded AssetProxyDispatchError. - */ - public decodeAssetProxyDispatchError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns errorCode The error code.orderHash Hash of the order being dispatched.assetData Asset data of the order being dispatched. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[number, string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeAssetProxyDispatchError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyDispatchError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[number, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded AssetProxyExistsError. - */ - public decodeAssetProxyExistsError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns assetProxyId Id of asset proxy.assetProxyAddress The address of the asset proxy. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeAssetProxyExistsError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyExistsError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decode AssetProxy identifier - */ - public decodeAssetProxyId = { - /** - * 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 AssetProxy-compliant asset data describing an ERC-20, ERC- - * 721, ERC1155, or MultiAsset asset. - * @returns The AssetProxy identifier - */ - async callAsync( - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeAssetProxyId(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyId(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded AssetProxyTransferError. - */ - public decodeAssetProxyTransferError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns orderHash Hash of the order being dispatched.assetData Asset data of the order being dispatched.errorData ABI-encoded revert data from the asset proxy. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeAssetProxyTransferError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyTransferError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded SignatureValidatorError. - */ - public decodeEIP1271SignatureError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns signerAddress The expected signer of the hash.signature The full signature bytes.errorData The revert data thrown by the validator contract. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeEIP1271SignatureError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeEIP1271SignatureError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. - */ - public decodeERC1155AssetData = { - /** - * 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 AssetProxy-compliant asset data describing an ERC-1155 set - * of assets. - * @returns The ERC-1155 AssetProxy identifier, the address of the ERC-1155 contract hosting the assets, an array of the identifiers of the assets to be traded, an array of asset amounts to be traded, and callback data. Each element of the arrays corresponds to the same-indexed element of the other array. Return values specified as `memory` are returned as pointers to locations within the memory of the input parameter `assetData`. - */ - async callAsync( - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, BigNumber[], BigNumber[], string]> { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeERC1155AssetData(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeERC1155AssetData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, BigNumber[], BigNumber[], string]>( - rawCallResult, - ); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decode ERC-20 asset data from the format described in the AssetProxy contract specification. - */ - public decodeERC20AssetData = { - /** - * 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 AssetProxy-compliant asset data describing an ERC-20 asset. - * @returns The AssetProxy identifier, and the address of the ERC-20 contract hosting this asset. - */ - async callAsync( - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string]> { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeERC20AssetData(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeERC20AssetData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decode ERC-721 asset data from the format described in the AssetProxy contract specification. - */ - public decodeERC721AssetData = { - /** - * 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 AssetProxy-compliant asset data describing an ERC-721 - * asset. - * @returns The ERC-721 AssetProxy identifier, the address of the ERC-721 contract hosting this asset, and the identifier of the specific asset to be traded. - */ - async callAsync( - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, BigNumber]> { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeERC721AssetData(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeERC721AssetData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, BigNumber]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded OrderStatusError. - */ - public decodeExchangeInvalidContextError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns errorCode Error code that corresponds to invalid maker, taker, or sender.orderHash The order hash.contextAddress The maker, taker, or sender address - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[number, string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeExchangeInvalidContextError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeExchangeInvalidContextError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[number, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded FillError. - */ - public decodeFillError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns errorCode The error code.orderHash The order hash. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[number, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeFillError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeFillError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[number, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded IncompleteFillError. - */ - public decodeIncompleteFillError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns orderHash Hash of the order being filled. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[number, BigNumber, BigNumber]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeIncompleteFillError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeIncompleteFillError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[number, BigNumber, BigNumber]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decode multi-asset data from the format described in the AssetProxy contract specification. - */ - public decodeMultiAssetData = { - /** - * 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 AssetProxy-compliant data describing a multi-asset basket. - * @returns The Multi-Asset AssetProxy identifier, an array of the amounts of the assets to be traded, and an array of the AssetProxy-compliant data describing each asset to be traded. Each element of the arrays corresponds to the same-indexed element of the other array. - */ - async callAsync( - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, BigNumber[], string[]]> { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeMultiAssetData(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeMultiAssetData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, BigNumber[], string[]]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded NegativeSpreadError. - */ - public decodeNegativeSpreadError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns leftOrderHash Hash of the left order being matched.rightOrderHash Hash of the right order being matched. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeNegativeSpreadError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeNegativeSpreadError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded OrderEpochError. - */ - public decodeOrderEpochError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns makerAddress The order maker.orderSenderAddress The order sender.currentEpoch The current epoch for the maker. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, BigNumber]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeOrderEpochError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeOrderEpochError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, BigNumber]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded OrderStatusError. - */ - public decodeOrderStatusError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns orderHash The order hash.orderStatus The order status. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, number]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeOrderStatusError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeOrderStatusError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, number]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded SignatureError. - */ - public decodeSignatureError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns errorCode The error code.signerAddress The expected signer of the hash.signature The full signature. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[number, string, string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeSignatureError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeSignatureError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[number, string, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded SignatureValidatorNotApprovedError. - */ - public decodeSignatureValidatorNotApprovedError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns signerAddress The expected signer of the hash.validatorAddress The expected validator. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeSignatureValidatorNotApprovedError(bytes)', [ - encoded, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeSignatureValidatorNotApprovedError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded SignatureWalletError. - */ - public decodeSignatureWalletError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns errorCode The error code.signerAddress The expected signer of the hash.signature The full signature bytes.errorData The revert data thrown by the validator contract. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeSignatureWalletError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeSignatureWalletError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decode StaticCall asset data from the format described in the AssetProxy contract specification. - */ - public decodeStaticCallAssetData = { - /** - * 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 AssetProxy-compliant asset data describing a StaticCall - * asset - * @returns The StaticCall AssetProxy identifier, the target address of the StaticCAll, the data to be passed to the target address, and the expected Keccak-256 hash of the static call return data. - */ - async callAsync( - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, string, string]> { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeStaticCallAssetData(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeStaticCallAssetData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded TransactionError. - */ - public decodeTransactionError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns errorCode The error code.transactionHash Hash of the transaction. - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[number, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeTransactionError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeTransactionError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[number, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decompose an ABI-encoded TransactionExecutionError. - */ - public decodeTransactionExecutionError = { - /** - * 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 encoded ABI-encoded revert error. - * @returns transactionHash Hash of the transaction.errorData Error thrown by exeucteTransaction(). - */ - async callAsync( - encoded: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string]> { - assert.isString('encoded', encoded); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeTransactionExecutionError(bytes)', [encoded]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('decodeTransactionExecutionError(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decodes the call data for an Exchange contract method call. - */ - public decodeZeroExTransactionData = { - /** - * 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 transactionData ABI-encoded calldata for an Exchange contract - * method call. - * @returns The name of the function called, and the parameters it was given. For single-order fills and cancels, the arrays will have just one element. - */ - async callAsync( - transactionData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - [ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - BigNumber[], - string[] - ] - > { - assert.isString('transactionData', transactionData); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('decodeZeroExTransactionData(bytes)', [transactionData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; + private readonly _methodABIIndex: { [name: string]: number } = {}; + 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; } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); + } + return DevUtilsContract.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(`DevUtils successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new DevUtilsContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [_exchange]; + return contractInstance; + } - const abiEncoder = self._lookupAbiEncoder('decodeZeroExTransactionData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - [ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - BigNumber[], - string[] - ] - >(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; /** - * Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. - */ - public encodeERC1155AssetData = { - /** - * 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 tokenAddress The address of the ERC-1155 contract hosting the - * asset(s) to be traded. - * @param tokenIds The identifiers of the specific assets to be traded. - * @param tokenValues The amounts of each asset to be traded. - * @param callbackData Data to be passed to receiving contracts when a transfer - * is performed. - * @returns AssetProxy-compliant asset data describing the set of assets. - */ - async callAsync( - tokenAddress: string, - tokenIds: BigNumber[], - tokenValues: BigNumber[], - callbackData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('tokenAddress', tokenAddress); - assert.isArray('tokenIds', tokenIds); - assert.isArray('tokenValues', tokenValues); - assert.isString('callbackData', callbackData); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'encodeERC1155AssetData(address,uint256[],uint256[],bytes)', - [tokenAddress.toLowerCase(), tokenIds, tokenValues, callbackData], - ); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('encodeERC1155AssetData(address,uint256[],uint256[],bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Encode ERC-20 asset data into the format described in the AssetProxy contract specification. - */ - public encodeERC20AssetData = { - /** - * 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 tokenAddress The address of the ERC-20 contract hosting the asset to - * be traded. - * @returns AssetProxy-compliant data describing the asset. - */ - async callAsync( - tokenAddress: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('tokenAddress', tokenAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('encodeERC20AssetData(address)', [ - tokenAddress.toLowerCase(), - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('encodeERC20AssetData(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Encode ERC-721 asset data into the format described in the AssetProxy specification. - */ - public encodeERC721AssetData = { - /** - * 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 tokenAddress The address of the ERC-721 contract hosting the asset to - * be traded. - * @param tokenId The identifier of the specific asset to be traded. - * @returns AssetProxy-compliant asset data describing the asset. - */ - async callAsync( - tokenAddress: string, - tokenId: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('tokenAddress', tokenAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('encodeERC721AssetData(address,uint256)', [ - tokenAddress.toLowerCase(), - tokenId, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('encodeERC721AssetData(address,uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Encode data for multiple assets, per the AssetProxy contract specification. - */ - public encodeMultiAssetData = { - /** - * 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 amounts The amounts of each asset to be traded. - * @param nestedAssetData AssetProxy-compliant data describing each asset to be - * traded. - * @returns AssetProxy-compliant data describing the set of assets. - */ - async callAsync( - amounts: BigNumber[], - nestedAssetData: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isArray('amounts', amounts); - assert.isArray('nestedAssetData', nestedAssetData); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('encodeMultiAssetData(uint256[],bytes[])', [ - amounts, - nestedAssetData, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('encodeMultiAssetData(uint256[],bytes[])'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Encode StaticCall asset data into the format described in the AssetProxy contract specification. - */ - public encodeStaticCallAssetData = { - /** - * 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 staticCallTargetAddress Target address of StaticCall. - * @param staticCallData Data that will be passed to staticCallTargetAddress in - * the StaticCall. - * @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall - * return data. - * @returns AssetProxy-compliant asset data describing the set of assets. - */ - async callAsync( - staticCallTargetAddress: string, - staticCallData: string, - expectedReturnDataHash: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('staticCallTargetAddress', staticCallTargetAddress); - assert.isString('staticCallData', staticCallData); - assert.isString('expectedReturnDataHash', expectedReturnDataHash); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('encodeStaticCallAssetData(address,bytes,bytes32)', [ - staticCallTargetAddress.toLowerCase(), - staticCallData, - expectedReturnDataHash, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('encodeStaticCallAssetData(address,bytes,bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the number of asset(s) (described by assetData) that the corresponding AssetProxy contract is authorized to spend. When the asset data contains multiple assets (eg for Multi-Asset), the return value indicates how many complete "baskets" of those assets may be spent by all of the corresponding AssetProxy contracts. - */ - public getAssetProxyAllowance = { - /** - * 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 ownerAddress Owner of the assets specified by assetData. - * @param assetData Details of asset, encoded per the AssetProxy contract - * specification. - * @returns Number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. - */ - async callAsync( - ownerAddress: string, - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('getAssetProxyAllowance(address,bytes)', [ - ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getAssetProxyAllowance(address,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the owner's balance of the assets(s) specified in assetData. When the asset data contains multiple assets (eg in ERC1155 or Multi-Asset), the return value indicates how many complete "baskets" of those assets are owned by owner. - */ - public getBalance = { - /** - * 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 ownerAddress Owner of the assets specified by assetData. - * @param assetData Details of asset, encoded per the AssetProxy contract - * specification. - * @returns Number of assets (or asset baskets) held by owner. - */ - async callAsync( - ownerAddress: string, - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('getBalance(address,bytes)', [ - ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getBalance(address,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Calls getBalance() and getAllowance() for assetData. - */ - public getBalanceAndAssetProxyAllowance = { - /** - * 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 ownerAddress Owner of the assets specified by assetData. - * @param assetData Details of asset, encoded per the AssetProxy contract - * specification. - * @returns Number of assets (or asset baskets) held by owner, and number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. - */ - async callAsync( - ownerAddress: string, - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber, BigNumber]> { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('getBalanceAndAssetProxyAllowance(address,bytes)', [ - ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getBalanceAndAssetProxyAllowance(address,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Calls getAssetProxyAllowance() for each element of assetData. - */ - public getBatchAssetProxyAllowances = { - /** - * 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 ownerAddress Owner of the assets specified by assetData. - * @param assetData Array of asset details, each encoded per the AssetProxy - * contract specification. - * @returns An array of asset allowances from getAllowance(), with each element corresponding to the same-indexed element in the assetData input. - */ - async callAsync( - ownerAddress: string, - assetData: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('getBatchAssetProxyAllowances(address,bytes[])', [ - ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getBatchAssetProxyAllowances(address,bytes[])'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Calls getBalance() for each element of assetData. - */ - public getBatchBalances = { - /** - * 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 ownerAddress Owner of the assets specified by assetData. - * @param assetData Array of asset details, each encoded per the AssetProxy - * contract specification. - * @returns Array of asset balances from getBalance(), with each element corresponding to the same-indexed element in the assetData input. - */ - async callAsync( - ownerAddress: string, - assetData: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('getBatchBalances(address,bytes[])', [ - ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getBatchBalances(address,bytes[])'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Calls getBatchBalances() and getBatchAllowances() for each element of assetData. - */ - public getBatchBalancesAndAssetProxyAllowances = { - /** - * 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 ownerAddress Owner of the assets specified by assetData. - * @param assetData Array of asset details, each encoded per the AssetProxy - * contract specification. - * @returns An array of asset balances from getBalance(), and an array of asset allowances from getAllowance(), with each element corresponding to the same-indexed element in the assetData input. - */ - async callAsync( - ownerAddress: string, - assetData: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber[], BigNumber[]]> { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getBatchBalancesAndAssetProxyAllowances(address,bytes[])', - [ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getBatchBalancesAndAssetProxyAllowances(address,bytes[])'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber[], BigNumber[]]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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 DevUtilsContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getEthBalances(address[])'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Fetches all order-relevant information needed to validate if the supplied order is fillable. - */ - public getOrderRelevantState = { - /** - * 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 order structure. - * @param signature Signature provided by maker that proves the order's - * authenticity. `0x01` can always be provided if the signature does not - * need to be validated. - * @returns The orderInfo (hash, status, and `takerAssetAmount` already filled for the given order), fillableTakerAssetAmount (amount of the order's `takerAssetAmount` that is fillable given all on-chain state), and isValidSignature (validity of the provided signature). NOTE: If the `takerAssetData` encodes data for multiple assets, `fillableTakerAssetAmount` will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final amount of each asset that can be filled. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - signature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - [{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, BigNumber, boolean] - > { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getOrderRelevantState((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', - [order, signature], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'getOrderRelevantState((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - [{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, BigNumber, boolean] - >(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Fetches all order-relevant information needed to validate if the supplied orders are fillable. - */ - public getOrderRelevantStates = { - /** - * 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 structures. - * @param signatures Array of signatures provided by makers that prove the - * authenticity of the orders. `0x01` can always be provided if a signature - * does not need to be validated. - * @returns The ordersInfo (array of the hash, status, and `takerAssetAmount` already filled for each order), fillableTakerAssetAmounts (array of amounts for each order's `takerAssetAmount` that is fillable given all on-chain state), and isValidSignature (array containing the validity of each provided signature). NOTE: If the `takerAssetData` encodes data for multiple assets, each element of `fillableTakerAssetAmounts` will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final amount of each asset that can be filled. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - [ - Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, - BigNumber[], - boolean[] - ] - > { - assert.isArray('orders', orders); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getOrderRelevantStates((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[])', - [orders, signatures], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'getOrderRelevantStates((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - [ - Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, - BigNumber[], - boolean[] - ] - >(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Simulates all of the transfers within an order and returns the index of the first failed transfer. - */ - public getSimulatedOrderTransferResults = { - /** - * 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 order to simulate transfers for. - * @param takerAddress The address of the taker that will fill the order. - * @param takerAssetFillAmount The amount of takerAsset that the taker wished - * to fill. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAddress: string, - takerAssetFillAmount: BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('takerAddress', takerAddress); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const self = (this as any) as DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', - [order, takerAddress.toLowerCase(), takerAssetFillAmount], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.getSimulatedOrderTransferResults.callAsync( - order, - takerAddress, - takerAssetFillAmount, - txDataWithDefaults, - ); - } - - 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 order to simulate transfers for. - * @param takerAddress The address of the taker that will fill the order. - * @param takerAssetFillAmount The amount of takerAsset that the taker wished - * to fill. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAddress: string, - takerAssetFillAmount: BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('takerAddress', takerAddress); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const self = (this as any) as DevUtilsContract; - const txHashPromise = self.getSimulatedOrderTransferResults.sendTransactionAsync( - order, - takerAddress.toLowerCase(), - takerAssetFillAmount, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param order The order to simulate transfers for. - * @param takerAddress The address of the taker that will fill the order. - * @param takerAssetFillAmount The amount of takerAsset that the taker wished - * to fill. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAddress: string, - takerAssetFillAmount: BigNumber, - txData?: Partial | undefined, - ): Promise { - assert.isString('takerAddress', takerAddress); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const self = (this as any) as DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', - [order, takerAddress.toLowerCase(), takerAssetFillAmount], - ); - 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 order to simulate transfers for. - * @param takerAddress The address of the taker that will fill the order. - * @param takerAssetFillAmount The amount of takerAsset that the taker wished - * to fill. - * @returns The index of the first failed transfer (or 4 if all transfers are successful). - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAddress: string, - takerAssetFillAmount: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('takerAddress', takerAddress); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', - [order, takerAddress.toLowerCase(), takerAssetFillAmount], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),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 order The order to simulate transfers for. - * @param takerAddress The address of the taker that will fill the order. - * @param takerAssetFillAmount The amount of takerAsset that the taker wished - * to fill. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAddress: string, - takerAssetFillAmount: BigNumber, - ): string { - assert.isString('takerAddress', takerAddress); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - const self = (this as any) as DevUtilsContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', - [order, takerAddress.toLowerCase(), takerAssetFillAmount], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DevUtilsContract; - const abiEncoder = self._lookupAbiEncoder( - 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Simulates all of the transfers for each given order and returns the indices of each first failed transfer. - */ - public getSimulatedOrdersTransferResults = { - /** - * 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 orders to individually simulate transfers for. - * @param takerAddresses Array of addresses of takers that will fill each - * order. - * @param takerAssetFillAmounts Array of amounts of takerAsset that will be - * filled for each order. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAddresses: string[], - takerAssetFillAmounts: BigNumber[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('orders', orders); - assert.isArray('takerAddresses', takerAddresses); - assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); - const self = (this as any) as DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', - [orders, takerAddresses, takerAssetFillAmounts], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.getSimulatedOrdersTransferResults.callAsync( - orders, - takerAddresses, - takerAssetFillAmounts, - txDataWithDefaults, - ); - } - - 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 orders to individually simulate transfers for. - * @param takerAddresses Array of addresses of takers that will fill each - * order. - * @param takerAssetFillAmounts Array of amounts of takerAsset that will be - * filled for each 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( - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAddresses: string[], - takerAssetFillAmounts: BigNumber[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('orders', orders); - assert.isArray('takerAddresses', takerAddresses); - assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); - const self = (this as any) as DevUtilsContract; - const txHashPromise = self.getSimulatedOrdersTransferResults.sendTransactionAsync( - orders, - takerAddresses, - takerAssetFillAmounts, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param orders Array of orders to individually simulate transfers for. - * @param takerAddresses Array of addresses of takers that will fill each - * order. - * @param takerAssetFillAmounts Array of amounts of takerAsset that will be - * filled for each order. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAddresses: string[], - takerAssetFillAmounts: BigNumber[], - txData?: Partial | undefined, - ): Promise { - assert.isArray('orders', orders); - assert.isArray('takerAddresses', takerAddresses); - assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); - const self = (this as any) as DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', - [orders, takerAddresses, takerAssetFillAmounts], - ); - 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 orders to individually simulate transfers for. - * @param takerAddresses Array of addresses of takers that will fill each - * order. - * @param takerAssetFillAmounts Array of amounts of takerAsset that will be - * filled for each order. - * @returns The indices of the first failed transfer (or 4 if all transfers are successful) for 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAddresses: string[], - takerAssetFillAmounts: BigNumber[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isArray('orders', orders); - assert.isArray('takerAddresses', takerAddresses); - assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments( - 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', - [orders, takerAddresses, takerAssetFillAmounts], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],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 orders Array of orders to individually simulate transfers for. - * @param takerAddresses Array of addresses of takers that will fill each - * order. - * @param takerAssetFillAmounts Array of amounts of takerAsset that will be - * filled for each order. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAddresses: string[], - takerAssetFillAmounts: BigNumber[], - ): string { - assert.isArray('orders', orders); - assert.isArray('takerAddresses', takerAddresses); - assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); - const self = (this as any) as DevUtilsContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', - [orders, takerAddresses, takerAssetFillAmounts], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DevUtilsContract; - const abiEncoder = self._lookupAbiEncoder( - 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Gets the amount of an asset transferable by the owner. - */ - public getTransferableAssetAmount = { - /** - * 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 ownerAddress Address of the owner of the asset. - * @param assetData Description of tokens, per the AssetProxy contract - * specification. - * @returns The amount of the asset tranferable by the owner. NOTE: If the `assetData` encodes data for multiple assets, the `transferableAssetAmount` will represent the amount of times the entire `assetData` can be transferred. To calculate the total individual transferable amounts, this scaled `transferableAmount` must be multiplied by the individual asset amounts located within the `assetData`. - */ - async callAsync( - ownerAddress: string, - assetData: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('ownerAddress', ownerAddress); - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('getTransferableAssetAmount(address,bytes)', [ - ownerAddress.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getTransferableAssetAmount(address,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public revertIfInvalidAssetData = { - /** - * 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(assetData: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - 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 DevUtilsContract; - const encodedData = self._strictEncodeArguments('revertIfInvalidAssetData(bytes)', [assetData]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('revertIfInvalidAssetData(bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 DevUtilsContract.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(`DevUtils successfully deployed at ${txReceipt.contractAddress}`); - const contractInstance = new DevUtilsContract( - txReceipt.contractAddress as string, - provider, - txDefaults, - logDecodeDependencies, - ); - contractInstance.constructorArgs = [_exchange]; - return contractInstance; - } - - /** - * @returns The contract ABI + * @returns The contract ABI */ public static ABI(): ContractAbi { const abi = [ @@ -3930,150 +1336,2598 @@ export class DevUtilsContract extends BaseContract { ], }, { - name: 'takerAddress', + name: 'takerAddress', + type: 'address', + }, + { + name: 'takerAssetFillAmount', + type: 'uint256', + }, + ], + name: 'getSimulatedOrderTransferResults', + outputs: [ + { + name: 'orderTransferResults', + type: 'uint8', + }, + ], + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'takerAddresses', + type: 'address[]', + }, + { + name: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + ], + name: 'getSimulatedOrdersTransferResults', + outputs: [ + { + name: 'orderTransferResults', + type: 'uint8[]', + }, + ], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'ownerAddress', type: 'address', }, { - name: 'takerAssetFillAmount', - type: 'uint256', + name: 'assetData', + type: 'bytes', }, ], - name: 'getSimulatedOrderTransferResults', + name: 'getTransferableAssetAmount', outputs: [ { - name: 'orderTransferResults', - type: 'uint8', + name: 'transferableAssetAmount', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [ + { + name: 'assetData', + type: 'bytes', + }, + ], + name: 'revertIfInvalidAssetData', + outputs: [], + payable: false, + stateMutability: 'pure', + type: 'function', + }, + ] as ContractAbi; + return abi; + } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = DevUtilsContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DevUtilsContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DevUtilsContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DevUtilsContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Decompose an ABI-encoded AssetProxyDispatchError. + * @param encoded ABI-encoded revert error. + * @returns errorCode The error code.orderHash Hash of the order being dispatched.assetData Asset data of the order being dispatched. + */ + public decodeAssetProxyDispatchError(encoded: string): ContractFunctionObj<[number, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[number, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeAssetProxyDispatchError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyDispatchError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[number, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeAssetProxyDispatchError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded AssetProxyExistsError. + * @param encoded ABI-encoded revert error. + * @returns assetProxyId Id of asset proxy.assetProxyAddress The address of the asset proxy. + */ + public decodeAssetProxyExistsError(encoded: string): ContractFunctionObj<[string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeAssetProxyExistsError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyExistsError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeAssetProxyExistsError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decode AssetProxy identifier + * @param assetData AssetProxy-compliant asset data describing an ERC-20, ERC- + * 721, ERC1155, or MultiAsset asset. + * @returns The AssetProxy identifier + */ + public decodeAssetProxyId(assetData: string): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('decodeAssetProxyId(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyId(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeAssetProxyId(bytes)', [assetData]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded AssetProxyTransferError. + * @param encoded ABI-encoded revert error. + * @returns orderHash Hash of the order being dispatched.assetData Asset data of the order being dispatched.errorData ABI-encoded revert data from the asset proxy. + */ + public decodeAssetProxyTransferError(encoded: string): ContractFunctionObj<[string, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeAssetProxyTransferError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeAssetProxyTransferError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeAssetProxyTransferError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded SignatureValidatorError. + * @param encoded ABI-encoded revert error. + * @returns signerAddress The expected signer of the hash.signature The full signature bytes.errorData The revert data thrown by the validator contract. + */ + public decodeEIP1271SignatureError(encoded: string): ContractFunctionObj<[string, string, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeEIP1271SignatureError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeEIP1271SignatureError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeEIP1271SignatureError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. + * @param assetData AssetProxy-compliant asset data describing an ERC-1155 set + * of assets. + * @returns The ERC-1155 AssetProxy identifier, the address of the ERC-1155 contract hosting the assets, an array of the identifiers of the assets to be traded, an array of asset amounts to be traded, and callback data. Each element of the arrays corresponds to the same-indexed element of the other array. Return values specified as `memory` are returned as pointers to locations within the memory of the input parameter `assetData`. + */ + public decodeERC1155AssetData( + assetData: string, + ): ContractFunctionObj<[string, string, BigNumber[], BigNumber[], string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, BigNumber[], BigNumber[], string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeERC1155AssetData(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeERC1155AssetData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, BigNumber[], BigNumber[], string]>( + rawCallResult, + ); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeERC1155AssetData(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decode ERC-20 asset data from the format described in the AssetProxy contract specification. + * @param assetData AssetProxy-compliant asset data describing an ERC-20 asset. + * @returns The AssetProxy identifier, and the address of the ERC-20 contract hosting this asset. + */ + public decodeERC20AssetData(assetData: string): ContractFunctionObj<[string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeERC20AssetData(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeERC20AssetData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeERC20AssetData(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decode ERC-721 asset data from the format described in the AssetProxy contract specification. + * @param assetData AssetProxy-compliant asset data describing an ERC-721 + * asset. + * @returns The ERC-721 AssetProxy identifier, the address of the ERC-721 contract hosting this asset, and the identifier of the specific asset to be traded. + */ + public decodeERC721AssetData(assetData: string): ContractFunctionObj<[string, string, BigNumber]> { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeERC721AssetData(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeERC721AssetData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeERC721AssetData(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded OrderStatusError. + * @param encoded ABI-encoded revert error. + * @returns errorCode Error code that corresponds to invalid maker, taker, or sender.orderHash The order hash.contextAddress The maker, taker, or sender address + */ + public decodeExchangeInvalidContextError(encoded: string): ContractFunctionObj<[number, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[number, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeExchangeInvalidContextError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeExchangeInvalidContextError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[number, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'decodeExchangeInvalidContextError(bytes)', + [encoded], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded FillError. + * @param encoded ABI-encoded revert error. + * @returns errorCode The error code.orderHash The order hash. + */ + public decodeFillError(encoded: string): ContractFunctionObj<[number, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[number, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeFillError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeFillError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[number, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeFillError(bytes)', [encoded]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded IncompleteFillError. + * @param encoded ABI-encoded revert error. + * @returns orderHash Hash of the order being filled. + */ + public decodeIncompleteFillError(encoded: string): ContractFunctionObj<[number, BigNumber, BigNumber]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[number, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeIncompleteFillError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeIncompleteFillError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[number, BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeIncompleteFillError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decode multi-asset data from the format described in the AssetProxy contract specification. + * @param assetData AssetProxy-compliant data describing a multi-asset basket. + * @returns The Multi-Asset AssetProxy identifier, an array of the amounts of the assets to be traded, and an array of the AssetProxy-compliant data describing each asset to be traded. Each element of the arrays corresponds to the same-indexed element of the other array. + */ + public decodeMultiAssetData(assetData: string): ContractFunctionObj<[string, BigNumber[], string[]]> { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, BigNumber[], string[]]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeMultiAssetData(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeMultiAssetData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, BigNumber[], string[]]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeMultiAssetData(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded NegativeSpreadError. + * @param encoded ABI-encoded revert error. + * @returns leftOrderHash Hash of the left order being matched.rightOrderHash Hash of the right order being matched. + */ + public decodeNegativeSpreadError(encoded: string): ContractFunctionObj<[string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeNegativeSpreadError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeNegativeSpreadError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeNegativeSpreadError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded OrderEpochError. + * @param encoded ABI-encoded revert error. + * @returns makerAddress The order maker.orderSenderAddress The order sender.currentEpoch The current epoch for the maker. + */ + public decodeOrderEpochError(encoded: string): ContractFunctionObj<[string, string, BigNumber]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeOrderEpochError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeOrderEpochError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeOrderEpochError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded OrderStatusError. + * @param encoded ABI-encoded revert error. + * @returns orderHash The order hash.orderStatus The order status. + */ + public decodeOrderStatusError(encoded: string): ContractFunctionObj<[string, number]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[string, number]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeOrderStatusError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeOrderStatusError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, number]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeOrderStatusError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded SignatureError. + * @param encoded ABI-encoded revert error. + * @returns errorCode The error code.signerAddress The expected signer of the hash.signature The full signature. + */ + public decodeSignatureError(encoded: string): ContractFunctionObj<[number, string, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[number, string, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeSignatureError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeSignatureError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[number, string, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeSignatureError(bytes)', [encoded]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded SignatureValidatorNotApprovedError. + * @param encoded ABI-encoded revert error. + * @returns signerAddress The expected signer of the hash.validatorAddress The expected validator. + */ + public decodeSignatureValidatorNotApprovedError(encoded: string): ContractFunctionObj<[string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeSignatureValidatorNotApprovedError(bytes)', [ + encoded, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeSignatureValidatorNotApprovedError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'decodeSignatureValidatorNotApprovedError(bytes)', + [encoded], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded SignatureWalletError. + * @param encoded ABI-encoded revert error. + * @returns errorCode The error code.signerAddress The expected signer of the hash.signature The full signature bytes.errorData The revert data thrown by the validator contract. + */ + public decodeSignatureWalletError(encoded: string): ContractFunctionObj<[string, string, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeSignatureWalletError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeSignatureWalletError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeSignatureWalletError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decode StaticCall asset data from the format described in the AssetProxy contract specification. + * @param assetData AssetProxy-compliant asset data describing a StaticCall + * asset + * @returns The StaticCall AssetProxy identifier, the target address of the StaticCAll, the data to be passed to the target address, and the expected Keccak-256 hash of the static call return data. + */ + public decodeStaticCallAssetData(assetData: string): ContractFunctionObj<[string, string, string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeStaticCallAssetData(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeStaticCallAssetData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeStaticCallAssetData(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded TransactionError. + * @param encoded ABI-encoded revert error. + * @returns errorCode The error code.transactionHash Hash of the transaction. + */ + public decodeTransactionError(encoded: string): ContractFunctionObj<[number, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[number, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeTransactionError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeTransactionError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[number, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeTransactionError(bytes)', [ + encoded, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decompose an ABI-encoded TransactionExecutionError. + * @param encoded ABI-encoded revert error. + * @returns transactionHash Hash of the transaction.errorData Error thrown by exeucteTransaction(). + */ + public decodeTransactionExecutionError(encoded: string): ContractFunctionObj<[string, string]> { + const self = (this as any) as DevUtilsContract; + assert.isString('encoded', encoded); + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeTransactionExecutionError(bytes)', [encoded]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeTransactionExecutionError(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'decodeTransactionExecutionError(bytes)', + [encoded], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decodes the call data for an Exchange contract method call. + * @param transactionData ABI-encoded calldata for an Exchange contract + * method call. + * @returns The name of the function called, and the parameters it was given. For single-order fills and cancels, the arrays will have just one element. + */ + public decodeZeroExTransactionData( + transactionData: string, + ): ContractFunctionObj< + [ + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + BigNumber[], + string[] + ] + > { + const self = (this as any) as DevUtilsContract; + assert.isString('transactionData', transactionData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [ + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + BigNumber[], + string[] + ] + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('decodeZeroExTransactionData(bytes)', [ + transactionData, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decodeZeroExTransactionData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + BigNumber[], + string[] + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decodeZeroExTransactionData(bytes)', [ + transactionData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. + * @param tokenAddress The address of the ERC-1155 contract hosting the + * asset(s) to be traded. + * @param tokenIds The identifiers of the specific assets to be traded. + * @param tokenValues The amounts of each asset to be traded. + * @param callbackData Data to be passed to receiving contracts when a transfer + * is performed. + * @returns AssetProxy-compliant asset data describing the set of assets. + */ + public encodeERC1155AssetData( + tokenAddress: string, + tokenIds: BigNumber[], + tokenValues: BigNumber[], + callbackData: string, + ): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('tokenAddress', tokenAddress); + assert.isArray('tokenIds', tokenIds); + assert.isArray('tokenValues', tokenValues); + assert.isString('callbackData', callbackData); + + return { + 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 encodedData = self._strictEncodeArguments( + 'encodeERC1155AssetData(address,uint256[],uint256[],bytes)', + [tokenAddress.toLowerCase(), tokenIds, tokenValues, callbackData], + ); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('encodeERC1155AssetData(address,uint256[],uint256[],bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'encodeERC1155AssetData(address,uint256[],uint256[],bytes)', + [tokenAddress.toLowerCase(), tokenIds, tokenValues, callbackData], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Encode ERC-20 asset data into the format described in the AssetProxy contract specification. + * @param tokenAddress The address of the ERC-20 contract hosting the asset to + * be traded. + * @returns AssetProxy-compliant data describing the asset. + */ + public encodeERC20AssetData(tokenAddress: string): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('tokenAddress', tokenAddress); + + return { + 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 encodedData = self._strictEncodeArguments('encodeERC20AssetData(address)', [ + tokenAddress.toLowerCase(), + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('encodeERC20AssetData(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('encodeERC20AssetData(address)', [ + tokenAddress.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Encode ERC-721 asset data into the format described in the AssetProxy specification. + * @param tokenAddress The address of the ERC-721 contract hosting the asset to + * be traded. + * @param tokenId The identifier of the specific asset to be traded. + * @returns AssetProxy-compliant asset data describing the asset. + */ + public encodeERC721AssetData(tokenAddress: string, tokenId: BigNumber): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('tokenAddress', tokenAddress); + assert.isBigNumber('tokenId', tokenId); + + return { + 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 encodedData = self._strictEncodeArguments('encodeERC721AssetData(address,uint256)', [ + tokenAddress.toLowerCase(), + tokenId, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('encodeERC721AssetData(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'encodeERC721AssetData(address,uint256)', + [tokenAddress.toLowerCase(), tokenId], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Encode data for multiple assets, per the AssetProxy contract specification. + * @param amounts The amounts of each asset to be traded. + * @param nestedAssetData AssetProxy-compliant data describing each asset to be + * traded. + * @returns AssetProxy-compliant data describing the set of assets. + */ + public encodeMultiAssetData(amounts: BigNumber[], nestedAssetData: string[]): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isArray('amounts', amounts); + assert.isArray('nestedAssetData', nestedAssetData); + + return { + 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 encodedData = self._strictEncodeArguments('encodeMultiAssetData(uint256[],bytes[])', [ + amounts, + nestedAssetData, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('encodeMultiAssetData(uint256[],bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'encodeMultiAssetData(uint256[],bytes[])', + [amounts, nestedAssetData], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Encode StaticCall asset data into the format described in the AssetProxy contract specification. + * @param staticCallTargetAddress Target address of StaticCall. + * @param staticCallData Data that will be passed to staticCallTargetAddress in + * the StaticCall. + * @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall + * return data. + * @returns AssetProxy-compliant asset data describing the set of assets. + */ + public encodeStaticCallAssetData( + staticCallTargetAddress: string, + staticCallData: string, + expectedReturnDataHash: string, + ): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('staticCallTargetAddress', staticCallTargetAddress); + assert.isString('staticCallData', staticCallData); + assert.isString('expectedReturnDataHash', expectedReturnDataHash); + + return { + 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 encodedData = self._strictEncodeArguments('encodeStaticCallAssetData(address,bytes,bytes32)', [ + staticCallTargetAddress.toLowerCase(), + staticCallData, + expectedReturnDataHash, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('encodeStaticCallAssetData(address,bytes,bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'encodeStaticCallAssetData(address,bytes,bytes32)', + [staticCallTargetAddress.toLowerCase(), staticCallData, expectedReturnDataHash], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the number of asset(s) (described by assetData) that the corresponding AssetProxy contract is authorized to spend. When the asset data contains multiple assets (eg for Multi-Asset), the return value indicates how many complete "baskets" of those assets may be spent by all of the corresponding AssetProxy contracts. + * @param ownerAddress Owner of the assets specified by assetData. + * @param assetData Details of asset, encoded per the AssetProxy contract + * specification. + * @returns Number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. + */ + public getAssetProxyAllowance(ownerAddress: string, assetData: string): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isString('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('getAssetProxyAllowance(address,bytes)', [ + ownerAddress.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAssetProxyAllowance(address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getAssetProxyAllowance(address,bytes)', [ + ownerAddress.toLowerCase(), + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the owner's balance of the assets(s) specified in assetData. When the asset data contains multiple assets (eg in ERC1155 or Multi-Asset), the return value indicates how many complete "baskets" of those assets are owned by owner. + * @param ownerAddress Owner of the assets specified by assetData. + * @param assetData Details of asset, encoded per the AssetProxy contract + * specification. + * @returns Number of assets (or asset baskets) held by owner. + */ + public getBalance(ownerAddress: string, assetData: string): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isString('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('getBalance(address,bytes)', [ + ownerAddress.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBalance(address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getBalance(address,bytes)', [ + ownerAddress.toLowerCase(), + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calls getBalance() and getAllowance() for assetData. + * @param ownerAddress Owner of the assets specified by assetData. + * @param assetData Details of asset, encoded per the AssetProxy contract + * specification. + * @returns Number of assets (or asset baskets) held by owner, and number of assets (or asset baskets) that the corresponding AssetProxy is authorized to spend. + */ + public getBalanceAndAssetProxyAllowance( + ownerAddress: string, + assetData: string, + ): ContractFunctionObj<[BigNumber, BigNumber]> { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isString('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getBalanceAndAssetProxyAllowance(address,bytes)', [ + ownerAddress.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBalanceAndAssetProxyAllowance(address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getBalanceAndAssetProxyAllowance(address,bytes)', + [ownerAddress.toLowerCase(), assetData], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calls getAssetProxyAllowance() for each element of assetData. + * @param ownerAddress Owner of the assets specified by assetData. + * @param assetData Array of asset details, each encoded per the AssetProxy + * contract specification. + * @returns An array of asset allowances from getAllowance(), with each element corresponding to the same-indexed element in the assetData input. + */ + public getBatchAssetProxyAllowances(ownerAddress: string, assetData: string[]): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isArray('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('getBatchAssetProxyAllowances(address,bytes[])', [ + ownerAddress.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBatchAssetProxyAllowances(address,bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getBatchAssetProxyAllowances(address,bytes[])', + [ownerAddress.toLowerCase(), assetData], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calls getBalance() for each element of assetData. + * @param ownerAddress Owner of the assets specified by assetData. + * @param assetData Array of asset details, each encoded per the AssetProxy + * contract specification. + * @returns Array of asset balances from getBalance(), with each element corresponding to the same-indexed element in the assetData input. + */ + public getBatchBalances(ownerAddress: string, assetData: string[]): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isArray('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('getBatchBalances(address,bytes[])', [ + ownerAddress.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBatchBalances(address,bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getBatchBalances(address,bytes[])', [ + ownerAddress.toLowerCase(), + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calls getBatchBalances() and getBatchAllowances() for each element of assetData. + * @param ownerAddress Owner of the assets specified by assetData. + * @param assetData Array of asset details, each encoded per the AssetProxy + * contract specification. + * @returns An array of asset balances from getBalance(), and an array of asset allowances from getAllowance(), with each element corresponding to the same-indexed element in the assetData input. + */ + public getBatchBalancesAndAssetProxyAllowances( + ownerAddress: string, + assetData: string[], + ): ContractFunctionObj<[BigNumber[], BigNumber[]]> { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isArray('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber[], BigNumber[]]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getBatchBalancesAndAssetProxyAllowances(address,bytes[])', + [ownerAddress.toLowerCase(), assetData], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getBatchBalancesAndAssetProxyAllowances(address,bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber[], BigNumber[]]>(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getBatchBalancesAndAssetProxyAllowances(address,bytes[])', + [ownerAddress.toLowerCase(), assetData], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Batch fetches ETH balances + * @param addresses Array of addresses. + * @returns Array of ETH balances. + */ + public getEthBalances(addresses: string[]): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isArray('addresses', addresses); + + return { + 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 encodedData = self._strictEncodeArguments('getEthBalances(address[])', [addresses]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getEthBalances(address[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getEthBalances(address[])', [addresses]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Fetches all order-relevant information needed to validate if the supplied order is fillable. + * @param order The order structure. + * @param signature Signature provided by maker that proves the order's + * authenticity. `0x01` can always be provided if the signature does not + * need to be validated. + * @returns The orderInfo (hash, status, and `takerAssetAmount` already filled for the given order), fillableTakerAssetAmount (amount of the order's `takerAssetAmount` that is fillable given all on-chain state), and isValidSignature (validity of the provided signature). NOTE: If the `takerAssetData` encodes data for multiple assets, `fillableTakerAssetAmount` will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final amount of each asset that can be filled. + */ + public getOrderRelevantState( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + signature: string, + ): ContractFunctionObj< + [{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, BigNumber, boolean] + > { + const self = (this as any) as DevUtilsContract; + + assert.isString('signature', signature); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, BigNumber, boolean] + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getOrderRelevantState((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', + [order, signature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrderRelevantState((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + { orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }, + BigNumber, + boolean + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrderRelevantState((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', + [order, signature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Fetches all order-relevant information needed to validate if the supplied orders are fillable. + * @param orders Array of order structures. + * @param signatures Array of signatures provided by makers that prove the + * authenticity of the orders. `0x01` can always be provided if a signature + * does not need to be validated. + * @returns The ordersInfo (array of the hash, status, and `takerAssetAmount` already filled for each order), fillableTakerAssetAmounts (array of amounts for each order's `takerAssetAmount` that is fillable given all on-chain state), and isValidSignature (array containing the validity of each provided signature). NOTE: If the `takerAssetData` encodes data for multiple assets, each element of `fillableTakerAssetAmounts` will represent a "scaled" amount, meaning it must be multiplied by all the individual asset amounts within the `takerAssetData` to get the final amount of each asset that can be filled. + */ + public getOrderRelevantStates( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + signatures: string[], + ): ContractFunctionObj< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + BigNumber[], + boolean[] + ] + > { + const self = (this as any) as DevUtilsContract; + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + BigNumber[], + boolean[] + ] + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getOrderRelevantStates((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[])', + [orders, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'takerAddresses', - type: 'address[]', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrderRelevantStates((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [ + Array<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }>, + BigNumber[], + boolean[] + ] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrderRelevantStates((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[])', + [orders, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Simulates all of the transfers within an order and returns the index of the first failed transfer. + * @param order The order to simulate transfers for. + * @param takerAddress The address of the taker that will fill the order. + * @param takerAssetFillAmount The amount of takerAsset that the taker wished + * to fill. + * @returns The index of the first failed transfer (or 4 if all transfers are successful). + */ + public getSimulatedOrderTransferResults( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + takerAddress: string, + takerAssetFillAmount: BigNumber, + ): ContractTxFunctionObj { + const self = (this as any) as DevUtilsContract; + + assert.isString('takerAddress', takerAddress); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', + [order, takerAddress.toLowerCase(), takerAssetFillAmount], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'takerAssetFillAmounts', - type: 'uint256[]', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'getSimulatedOrdersTransferResults', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', + [order, takerAddress.toLowerCase(), takerAssetFillAmount], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'orderTransferResults', - type: 'uint8[]', + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: true, - inputs: [ + 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 encodedData = self._strictEncodeArguments( + 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', + [order, takerAddress.toLowerCase(), takerAssetFillAmount], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'ownerAddress', - type: 'address', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getSimulatedOrderTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),address,uint256)', + [order, takerAddress.toLowerCase(), takerAssetFillAmount], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Simulates all of the transfers for each given order and returns the indices of each first failed transfer. + * @param orders Array of orders to individually simulate transfers for. + * @param takerAddresses Array of addresses of takers that will fill each + * order. + * @param takerAssetFillAmounts Array of amounts of takerAsset that will be + * filled for each order. + * @returns The indices of the first failed transfer (or 4 if all transfers are successful) for each order. + */ + public getSimulatedOrdersTransferResults( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + takerAddresses: string[], + takerAssetFillAmounts: BigNumber[], + ): ContractTxFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', + [orders, takerAddresses, takerAssetFillAmounts], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'assetData', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'getTransferableAssetAmount', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', + [orders, takerAddresses, takerAssetFillAmounts], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'transferableAssetAmount', - type: 'uint256', + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: true, - inputs: [ + 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 encodedData = self._strictEncodeArguments( + 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', + [orders, takerAddresses, takerAssetFillAmounts], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'assetData', - type: 'bytes', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'revertIfInvalidAssetData', - outputs: [], - payable: false, - stateMutability: 'pure', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - ] as ContractAbi; - return abi; + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getSimulatedOrdersTransferResults((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],address[],uint256[])', + [orders, takerAddresses, takerAssetFillAmounts], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets the amount of an asset transferable by the owner. + * @param ownerAddress Address of the owner of the asset. + * @param assetData Description of tokens, per the AssetProxy contract + * specification. + * @returns The amount of the asset tranferable by the owner. NOTE: If the `assetData` encodes data for multiple assets, the `transferableAssetAmount` will represent the amount of times the entire `assetData` can be transferred. To calculate the total individual transferable amounts, this scaled `transferableAmount` must be multiplied by the individual asset amounts located within the `assetData`. + */ + public getTransferableAssetAmount(ownerAddress: string, assetData: string): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('ownerAddress', ownerAddress); + assert.isString('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('getTransferableAssetAmount(address,bytes)', [ + ownerAddress.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTransferableAssetAmount(address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTransferableAssetAmount(address,bytes)', + [ownerAddress.toLowerCase(), assetData], + ); + return abiEncodedTransactionData; + }, + }; + } + public revertIfInvalidAssetData(assetData: string): ContractFunctionObj { + const self = (this as any) as DevUtilsContract; + assert.isString('assetData', assetData); + + return { + 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 encodedData = self._strictEncodeArguments('revertIfInvalidAssetData(bytes)', [assetData]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('revertIfInvalidAssetData(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('revertIfInvalidAssetData(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; } + constructor( address: string, supportedProvider: SupportedProvider, @@ -4091,6 +3945,12 @@ export class DevUtilsContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + DevUtilsContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 304044c949..54a21f2095 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 @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -58,1453 +61,7 @@ export class DummyERC20TokenContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('MAX_MINT_AMOUNT()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * `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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.approve.callAsync(_spender, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('decimals()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.mint.callAsync(_value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('_value', _value); - const self = (this as any) as DummyERC20TokenContract; - const txHashPromise = self.mint.sendTransactionAsync(_value, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(_value: BigNumber): string { - assert.isBigNumber('_value', _value); - const self = (this as any) as DummyERC20TokenContract; - const abiEncodedTransactionData = self._strictEncodeArguments('mint(uint256)', [_value]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('mint(uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('name()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('owner()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.setBalance.callAsync(_target, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('setBalance(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('symbol()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('totalSupply()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transfer.callAsync(_to, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferFrom.callAsync(_from, _to, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferOwnership.callAsync(newOwner, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('newOwner', newOwner); - const self = (this as any) as DummyERC20TokenContract; - const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -1915,6 +472,1154 @@ export class DummyERC20TokenContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = DummyERC20TokenContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DummyERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + public MAX_MINT_AMOUNT(): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('MAX_MINT_AMOUNT()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('MAX_MINT_AMOUNT()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('MAX_MINT_AMOUNT()', []); + return abiEncodedTransactionData; + }, + }; + } + public allowance(_owner: string, _spender: string): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + + return { + 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 encodedData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * `msg.sender` approves `_spender` to spend `_value` tokens + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @returns Always true if the call has enough gas to complete execution + */ + public approve(_spender: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Query the balance of owner + * @param _owner The address from which the balance will be retrieved + * @returns Balance of owner + */ + public balanceOf(_owner: string): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('_owner', _owner); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [ + _owner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public decimals(): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('decimals()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decimals()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Mints new tokens for sender + * @param _value Amount of tokens to mint + */ + public mint(_value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('mint(uint256)', [_value]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('mint(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('mint(uint256)', [_value]); + return abiEncodedTransactionData; + }, + }; + } + public name(): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('name()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + }; + } + public owner(): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('owner()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Sets the balance of target address + * @param _target Address or which balance will be updated + * @param _value New balance of target address + */ + public setBalance(_target: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('_target', _target); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('setBalance(address,uint256)', [ + _target.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setBalance(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('setBalance(address,uint256)', [ + _target.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + public symbol(): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('symbol()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Query total supply of token + * @returns Total supply of token + */ + public totalSupply(): ContractFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('totalSupply()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * send `value` token to `to` from `msg.sender` + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @returns True if transfer was successful + */ + public transfer(_to: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * ERC20 transferFrom, modified such that an allowance of MAX_UINT represents an unlimited allowance. See https://github.com/ethereum/EIPs/issues/717 + * @param _from Address to transfer from. + * @param _to Address to transfer to. + * @param _value Amount to transfer. + * @returns Success of transfer. + */ + public transferFrom(_from: string, _to: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + public transferOwnership(newOwner: string): ContractTxFunctionObj { + const self = (this as any) as DummyERC20TokenContract; + assert.isString('newOwner', newOwner); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the DummyERC20Token contract. * @param eventName The DummyERC20Token contract event you would like to subscribe to. @@ -2004,6 +1709,12 @@ export class DummyERC20TokenContract extends BaseContract { DummyERC20TokenContract.ABI(), this._web3Wrapper, ); + DummyERC20TokenContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 5fb1cf8f24..6ff77684f4 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 @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -68,1916 +71,7 @@ export class DummyERC721TokenContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.approve.callAsync(_approved, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.burn.callAsync(_owner, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('burn(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.mint.callAsync(_to, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('mint(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('name()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('owner()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.safeTransferFrom1.callAsync(_from, _to, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.safeTransferFrom2.callAsync(_from, _to, _tokenId, _data, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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` - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.setApprovalForAll.callAsync(_operator, _approved, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('symbol()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferFrom.callAsync(_from, _to, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferOwnership.callAsync(newOwner, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('newOwner', newOwner); - const self = (this as any) as DummyERC721TokenContract; - const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as DummyERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -2430,6 +524,1402 @@ export class DummyERC721TokenContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = DummyERC721TokenContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as DummyERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * 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. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + */ + public approve(_approved: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * NFTs assigned to the zero address are considered invalid, and this + * function throws for queries about the zero address. + * @param _owner An address for whom to query the balance + * @returns The number of NFTs owned by `_owner`, possibly zero + */ + public balanceOf(_owner: string): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_owner', _owner); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [ + _owner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Function to burn a token + * Reverts if the given token ID doesn't exist or not called by contract owner + * @param _owner Owner of token with given token ID + * @param _tokenId ID of the token to be burned by the msg.sender + */ + public burn(_owner: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_owner', _owner); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('burn(address,uint256)', [ + _owner.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('burn(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('burn(address,uint256)', [ + _owner.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Throws if `_tokenId` is not a valid NFT. + * @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 + */ + public getApproved(_tokenId: BigNumber): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isBigNumber('_tokenId', _tokenId); + + return { + 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 encodedData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + }; + } + public isApprovedForAll(_owner: string, _operator: string): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_owner', _owner); + assert.isString('_operator', _operator); + + return { + 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 encodedData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Function to mint a new token + * Reverts if the given token ID already exists + * @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 + */ + public mint(_to: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('mint(address,uint256)', [_to.toLowerCase(), _tokenId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('mint(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('mint(address,uint256)', [ + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + public name(): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('name()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + }; + } + public owner(): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('owner()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * NFTs assigned to zero address are considered invalid, and queries + * about them do throw. + * @param _tokenId The identifier for an NFT + * @returns The address of the owner of the NFT + */ + public ownerOf(_tokenId: BigNumber): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isBigNumber('_tokenId', _tokenId); + + return { + 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 encodedData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + }; + } + /** + * This works identically to the other function with an extra data parameter, + * except this function just sets data to "". + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + public safeTransferFrom1(_from: string, _to: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256)', + [_from.toLowerCase(), _to.toLowerCase(), _tokenId], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * 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)"))`. + * @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` + */ + public safeTransferFrom2( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + ): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,bytes)', + [_from.toLowerCase(), _to.toLowerCase(), _tokenId, _data], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Emits the ApprovalForAll event. The contract MUST allow + * multiple operators per owner. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + */ + public setApprovalForAll(_operator: string, _approved: boolean): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + return abiEncodedTransactionData; + }, + }; + } + public symbol(): ContractFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('symbol()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * 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. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + public transferFrom(_from: string, _to: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + public transferOwnership(newOwner: string): ContractTxFunctionObj { + const self = (this as any) as DummyERC721TokenContract; + assert.isString('newOwner', newOwner); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the DummyERC721Token contract. * @param eventName The DummyERC721Token contract event you would like to subscribe to. @@ -2519,6 +2009,12 @@ export class DummyERC721TokenContract extends BaseContract { DummyERC721TokenContract.ABI(), this._web3Wrapper, ); + DummyERC721TokenContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/erc1155_mintable.ts b/packages/abi-gen-wrappers/src/generated-wrappers/erc1155_mintable.ts index 9d8a0f0167..a5e41bca2f 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc1155_mintable.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc1155_mintable.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -80,2063 +83,7 @@ export class ERC1155MintableContract extends BaseContract { */ public static deployedBytecode = '0x608060405234801561001057600080fd5b50600436106101765760003560e01c80639f4b286a116100d8578063e0a5c9491161008c578063f242432a11610066578063f242432a146107bb578063f94190881461085d578063fc67bf1c146108d457610176565b8063e0a5c94914610726578063e44591f014610763578063e985e9c51461078057610176565b8063adebf6f2116100bd578063adebf6f21461067a578063cc10e40114610697578063cd53d08e1461070957610176565b80639f4b286a146105c8578063a22cb4651461063f57610176565b80636352211e1161012f5780637269a327116101145780637269a327146104c557806378b27221146104e25780639cca1c64146105ab57610176565b80636352211e146104625780636f969c2d146104a857610176565b80632eb2c2d6116101605780632eb2c2d6146101e35780634e1273f41461031f5780635e81b9581461043157610176565b8062fdd58e1461017b57806308d7d469146101c6575b600080fd5b6101b46004803603604081101561019157600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001356108dc565b60408051918252519081900360200190f35b6101b4600480360360208110156101dc57600080fd5b5035610966565b61031d600480360360a08110156101f957600080fd5b73ffffffffffffffffffffffffffffffffffffffff823581169260208101359091169181019060608101604082013564010000000081111561023a57600080fd5b82018360208201111561024c57600080fd5b8035906020019184602083028401116401000000008311171561026e57600080fd5b91939092909160208101903564010000000081111561028c57600080fd5b82018360208201111561029e57600080fd5b803590602001918460208302840111640100000000831117156102c057600080fd5b9193909290916020810190356401000000008111156102de57600080fd5b8201836020820111156102f057600080fd5b8035906020019184600183028401116401000000008311171561031257600080fd5b509092509050610978565b005b6103e16004803603604081101561033557600080fd5b81019060208101813564010000000081111561035057600080fd5b82018360208201111561036257600080fd5b8035906020019184602083028401116401000000008311171561038457600080fd5b9193909290916020810190356401000000008111156103a257600080fd5b8201836020820111156103b457600080fd5b803590602001918460208302840111640100000000831117156103d657600080fd5b509092509050611192565b60408051602080825283518183015283519192839290830191858101910280838360005b8381101561041d578181015183820152602001610405565b505050509050019250505060405180910390f35b61044e6004803603602081101561044757600080fd5b5035611357565b604080519115158252519081900360200190f35b61047f6004803603602081101561047857600080fd5b503561139d565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b6101b4600480360360208110156104be57600080fd5b50356113c5565b61044e600480360360208110156104db57600080fd5b50356113ea565b61031d600480360360608110156104f857600080fd5b8135919081019060408101602082013564010000000081111561051a57600080fd5b82018360208201111561052c57600080fd5b8035906020019184602083028401116401000000008311171561054e57600080fd5b91939092909160208101903564010000000081111561056c57600080fd5b82018360208201111561057e57600080fd5b803590602001918460208302840111640100000000831117156105a057600080fd5b50909250905061142f565b6101b4600480360360208110156105c157600080fd5b5035611760565b61031d600480360360408110156105de57600080fd5b8135919081019060408101602082013564010000000081111561060057600080fd5b82018360208201111561061257600080fd5b8035906020019184600183028401116401000000008311171561063457600080fd5b509092509050611775565b61031d6004803603604081101561065557600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81351690602001351515611875565b61044e6004803603602081101561069057600080fd5b503561190e565b6101b4600480360360408110156106ad57600080fd5b8101906020810181356401000000008111156106c857600080fd5b8201836020820111156106da57600080fd5b803590602001918460018302840111640100000000831117156106fc57600080fd5b9193509150351515611934565b61047f6004803603602081101561071f57600080fd5b5035611a6d565b61072e611a95565b604080517fffffffff000000000000000000000000000000000000000000000000000000009092168252519081900360200190f35b61044e6004803603602081101561077957600080fd5b5035611ab9565b61044e6004803603604081101561079657600080fd5b5073ffffffffffffffffffffffffffffffffffffffff81358116916020013516611ae1565b61031d600480360360a08110156107d157600080fd5b73ffffffffffffffffffffffffffffffffffffffff823581169260208101359091169160408201359160608101359181019060a08101608082013564010000000081111561081e57600080fd5b82018360208201111561083057600080fd5b8035906020019184600183028401116401000000008311171561085257600080fd5b509092509050611b1c565b61031d6004803603604081101561087357600080fd5b8135919081019060408101602082013564010000000081111561089557600080fd5b8201836020820111156108a757600080fd5b803590602001918460208302840111640100000000831117156108c957600080fd5b5090925090506120fb565b61072e61242b565b60006108e782611357565b1561092e5760008281526020819052604090205473ffffffffffffffffffffffffffffffffffffffff848116911614610921576000610924565b60015b60ff169050610960565b50600081815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff861684529091529020545b92915050565b60056020526000908152604090205481565b73ffffffffffffffffffffffffffffffffffffffff87166109fa57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f43414e4e4f545f5452414e534645525f544f5f414444524553535f5a45524f00604482015290519081900360640190fd5b848314610a6857604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820181905260248201527f544f4b454e5f414e445f56414c5545535f4c454e4754485f4d49534d41544348604482015290519081900360640190fd5b73ffffffffffffffffffffffffffffffffffffffff8816331480610ac1575073ffffffffffffffffffffffffffffffffffffffff8816600090815260026020908152604080832033845290915290205460ff1615156001145b610b2c57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f494e53554646494349454e545f414c4c4f57414e434500000000000000000000604482015290519081900360640190fd5b60005b85811015610deb576000878783818110610b4557fe5b9050602002013590506000868684818110610b5c57fe5b905060200201359050610b6e82611ab9565b15610cc85780600114610be257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f414d4f554e545f455155414c5f544f5f4f4e455f524551554952454400000000604482015290519081900360640190fd5b60008281526020819052604090205473ffffffffffffffffffffffffffffffffffffffff8c8116911614610c7757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f4e46545f4e4f545f4f574e45445f42595f46524f4d5f41444452455353000000604482015290519081900360640190fd5b600082815260208190526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff8c16179055610de1565b600082815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8f168452909152902054610d02908261244f565b6001600084815260200190815260200160002060008d73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002081905550610db06001600084815260200190815260200160002060008c73ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205482612473565b600083815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8f1684529091529020555b5050600101610b2f565b508673ffffffffffffffffffffffffffffffffffffffff168873ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167f4a39dc06d4c0dbc64b70af90fd698a233a518aa5d07e595d983b8c0526c8f7fb898989896040518080602001806020018381038352878782818152602001925060200280828437600083820152601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169091018481038352858152602090810191508690860280828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169092018290039850909650505050505050a4610f1f8773ffffffffffffffffffffffffffffffffffffffff1661248f565b156111885760008773ffffffffffffffffffffffffffffffffffffffff1663bc197c81338b8a8a8a8a8a8a6040518963ffffffff1660e01b8152600401808973ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018873ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200180602001806020018060200184810384528a8a82818152602001925060200280828437600083820152601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169091018581038452888152602090810191508990890280828437600083820152601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe01690910185810383528681526020019050868680828437600081840152601f19601f8201169050808301925050509b505050505050505050505050602060405180830381600087803b1580156110a857600080fd5b505af11580156110bc573d6000803e3d6000fd5b505050506040513d60208110156110d257600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167fbc197c81000000000000000000000000000000000000000000000000000000001461118657604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f4241445f52454345495645525f52455455524e5f56414c554500000000000000604482015290519081900360640190fd5b505b5050505050505050565b60608382146111ec576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602481526020018061256a6024913960400191505060405180910390fd5b604080518581526020808702820101909152848015611215578160200160208202803883390190505b50905060005b8481101561134e57600084848381811061123157fe5b90506020020135905061124381611357565b156112b95786868381811061125457fe5b600084815260208181526040909120549102929092013573ffffffffffffffffffffffffffffffffffffffff9081169216919091149050611296576000611299565b60015b60ff168383815181106112a857fe5b602002602001018181525050611345565b6000818152600160205260408120908888858181106112d457fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020019081526020016000205483838151811061133857fe5b6020026020010181815250505b5060010161121b565b50949350505050565b60007f80000000000000000000000000000000000000000000000000000000000000008083161480156109605750506fffffffffffffffffffffffffffffffff16151590565b60009081526020819052604090205473ffffffffffffffffffffffffffffffffffffffff1690565b7fffffffffffffffffffffffffffffffff000000000000000000000000000000001690565b60007f80000000000000000000000000000000000000000000000000000000000000008083161480156109605750506fffffffffffffffffffffffffffffffff161590565b600085815260046020526040902054859073ffffffffffffffffffffffffffffffffffffffff16331461146157600080fd5b61146a8661190e565b6114bf576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602d81526020018061258e602d913960400191505060405180910390fd5b60005b848110156117575760008686838181106114d857fe5b9050602002013573ffffffffffffffffffffffffffffffffffffffff169050600085858481811061150557fe5b60008c815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8916845282529091205491029290920135925061154a91839150612473565b60008a815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168085529083528184209490945580518d8152918201859052805133927fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f6292908290030190a46115d68273ffffffffffffffffffffffffffffffffffffffff1661248f565b1561174d57604080517ff23a6e6100000000000000000000000000000000000000000000000000000000815233600482018190526024820152604481018b90526064810183905260a06084820152600060a48201819052915173ffffffffffffffffffffffffffffffffffffffff85169163f23a6e619160e480830192602092919082900301818787803b15801561166d57600080fd5b505af1158015611681573d6000803e3d6000fd5b505050506040513d602081101561169757600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167ff23a6e61000000000000000000000000000000000000000000000000000000001461174b57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f4241445f52454345495645525f52455455524e5f56414c554500000000000000604482015290519081900360640190fd5b505b50506001016114c2565b50505050505050565b6fffffffffffffffffffffffffffffffff1690565b600083815260046020908152604080832080547fffffffffffffffffffffffff0000000000000000000000000000000000000000163390811790915581518781529283018490528151849391927fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62928290030190a4801561187057827f6bb7ff708619ba0610cba295a58592e0451dee2622938c8755667688daf3529b838360405180806020018281038252848482818152602001925080828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169092018290039550909350505050a25b505050565b33600081815260026020908152604080832073ffffffffffffffffffffffffffffffffffffffff87168085529083529281902080547fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0016861515908117909155815190815290519293927f17307eab39ab6107e8899845ad3d59bd9653f200f220920489ca2b5937696c31929181900390910190a35050565b7f8000000000000000000000000000000000000000000000000000000000000000161590565b600380546001019081905560801b811561196b577f8000000000000000000000000000000000000000000000000000000000000000175b600081815260046020908152604080832080547fffffffffffffffffffffffff0000000000000000000000000000000000000000163390811790915581518581529283018490528151849391927fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f62928290030190a48215611a6657807f6bb7ff708619ba0610cba295a58592e0451dee2622938c8755667688daf3529b858560405180806020018281038252848482818152602001925080828437600083820152604051601f9091017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169092018290039550909350505050a25b9392505050565b60046020526000908152604090205473ffffffffffffffffffffffffffffffffffffffff1681565b7ff23a6e610000000000000000000000000000000000000000000000000000000081565b7f80000000000000000000000000000000000000000000000000000000000000009081161490565b73ffffffffffffffffffffffffffffffffffffffff918216600090815260026020908152604080832093909416825291909152205460ff1690565b73ffffffffffffffffffffffffffffffffffffffff8516611b9e57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601f60248201527f43414e4e4f545f5452414e534645525f544f5f414444524553535f5a45524f00604482015290519081900360640190fd5b73ffffffffffffffffffffffffffffffffffffffff8616331480611bf7575073ffffffffffffffffffffffffffffffffffffffff8616600090815260026020908152604080832033845290915290205460ff1615156001145b611c6257604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601660248201527f494e53554646494349454e545f414c4c4f57414e434500000000000000000000604482015290519081900360640190fd5b611c6b84611ab9565b15611dc55782600114611cdf57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601c60248201527f414d4f554e545f455155414c5f544f5f4f4e455f524551554952454400000000604482015290519081900360640190fd5b60008481526020819052604090205473ffffffffffffffffffffffffffffffffffffffff878116911614611d7457604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601d60248201527f4e46545f4e4f545f4f574e45445f42595f46524f4d5f41444452455353000000604482015290519081900360640190fd5b600084815260208190526040902080547fffffffffffffffffffffffff00000000000000000000000000000000000000001673ffffffffffffffffffffffffffffffffffffffff8716179055611e74565b600084815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8a168452909152902054611dff908461244f565b600085815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8b81168552925280832093909355871681522054611e439084612473565b600085815260016020908152604080832073ffffffffffffffffffffffffffffffffffffffff8a1684529091529020555b8473ffffffffffffffffffffffffffffffffffffffff168673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff167fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f628787604051808381526020018281526020019250505060405180910390a4611f178573ffffffffffffffffffffffffffffffffffffffff1661248f565b156120f35760008573ffffffffffffffffffffffffffffffffffffffff1663f23a6e613389888888886040518763ffffffff1660e01b8152600401808773ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1681526020018673ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001858152602001848152602001806020018281038252848482818152602001925080828437600081840152601f19601f820116905080830192505050975050505050505050602060405180830381600087803b15801561201557600080fd5b505af1158015612029573d6000803e3d6000fd5b505050506040513d602081101561203f57600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167ff23a6e61000000000000000000000000000000000000000000000000000000001461175757604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f4241445f52454345495645525f52455455524e5f56414c554500000000000000604482015290519081900360640190fd5b505050505050565b600083815260046020526040902054839073ffffffffffffffffffffffffffffffffffffffff16331461212d57600080fd5b61213684611ab9565b61218b576040517f08c379a000000000000000000000000000000000000000000000000000000000815260040180806020018281038252602d81526020018061253d602d913960400191505060405180910390fd5b600084815260056020526040812054600101905b838110156123f75760008585838181106121b557fe5b8486018a176000818152602081815260408083208054958302979097013573ffffffffffffffffffffffffffffffffffffffff167fffffffffffffffffffffffff00000000000000000000000000000000000000009095168517909655855183815260019181019190915285519396509194869450909233927fc3d58168c5ae7397731d063d5bbf3d657854427343f4c083240f7aacaa2d0f6292908290030190a46122768273ffffffffffffffffffffffffffffffffffffffff1661248f565b156123ed57604080517ff23a6e6100000000000000000000000000000000000000000000000000000000815233600482018190526024820152604481018390526001606482015260a06084820152600060a48201819052915173ffffffffffffffffffffffffffffffffffffffff85169163f23a6e619160e480830192602092919082900301818787803b15801561230d57600080fd5b505af1158015612321573d6000803e3d6000fd5b505050506040513d602081101561233757600080fd5b505190507fffffffff0000000000000000000000000000000000000000000000000000000081167ff23a6e6100000000000000000000000000000000000000000000000000000000146123eb57604080517f08c379a000000000000000000000000000000000000000000000000000000000815260206004820152601960248201527f4241445f52454345495645525f52455455524e5f56414c554500000000000000604482015290519081900360640190fd5b505b505060010161219f565b50600085815260056020526040902054612412908490612473565b6000958652600560205260409095209490945550505050565b7fbc197c810000000000000000000000000000000000000000000000000000000081565b60008282111561246d5761246d61246860028585612495565b612534565b50900390565b600082820183811015611a6657611a6661246860008686612495565b3b151590565b606063e946c1bb60e01b848484604051602401808460038111156124b557fe5b60ff1681526020018381526020018281526020019350505050604051602081830303815290604052907bffffffffffffffffffffffffffffffffffffffffffffffffffffffff19166020820180517bffffffffffffffffffffffffffffffffffffffffffffffffffffffff838183161783525050505090509392505050565b805160208201fdfe54524945445f544f5f4d494e545f4e4f4e5f46554e4749424c455f464f525f46554e4749424c455f544f4b454e4f574e4552535f414e445f4944535f4d5553545f484156455f53414d455f4c454e47544854524945445f544f5f4d494e545f46554e4749424c455f464f525f4e4f4e5f46554e4749424c455f544f4b454ea265627a7a723158205af7d187cbffb255b374d24e5838a04f6b3a3245622025907396b2a61f9d93da64736f6c634300050c0032'; - public ERC1155_BATCH_RECEIVED = { - /** - * 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('ERC1155_BATCH_RECEIVED()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('ERC1155_BATCH_RECEIVED()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public ERC1155_RECEIVED = { - /** - * 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('ERC1155_RECEIVED()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('ERC1155_RECEIVED()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 of the token holder - * @param id ID of the Token - * @returns The _owner's balance of the Token type requested - */ - async callAsync( - owner: string, - id: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('owner', owner); - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('balanceOf(address,uint256)', [owner.toLowerCase(), id]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOf(address,uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public balanceOfBatch = { - /** - * 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 owners The addresses of the token holders - * @param ids ID of the Tokens - * @returns The _owner's balance of the Token types requested - */ - async callAsync( - owners: string[], - ids: BigNumber[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isArray('owners', owners); - assert.isArray('ids', ids); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('balanceOfBatch(address[],uint256[])', [owners, ids]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOfBatch(address[],uint256[])'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * creates a new token - */ - public create = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param uri URI of token - * @param isNF is non-fungible token - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - uri: string, - isNF: boolean, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('uri', uri); - assert.isBoolean('isNF', isNF); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.create.callAsync(uri, isNF, txDataWithDefaults); - } - - 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 uri URI of token - * @param isNF is non-fungible token - * @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( - uri: string, - isNF: boolean, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('uri', uri); - assert.isBoolean('isNF', isNF); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.create.sendTransactionAsync(uri, isNF, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param uri URI of token - * @param isNF is non-fungible token - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(uri: string, isNF: boolean, txData?: Partial | undefined): Promise { - assert.isString('uri', uri); - assert.isBoolean('isNF', isNF); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); - 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 uri URI of token - * @param isNF is non-fungible token - * @returns type_ of token (a unique identifier) - */ - async callAsync( - uri: string, - isNF: boolean, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('uri', uri); - assert.isBoolean('isNF', isNF); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('create(string,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 uri URI of token - * @param isNF is non-fungible token - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(uri: string, isNF: boolean): string { - assert.isString('uri', uri); - assert.isBoolean('isNF', isNF); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder('create(string,bool)'); - return abiEncoder.getSelector(); - }, - }; - /** - * creates a new token - */ - public createWithType = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param type_ of token - * @param uri URI of token - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - type_: BigNumber, - uri: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('type_', type_); - assert.isString('uri', uri); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('createWithType(uint256,string)', [type_, uri]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.createWithType.callAsync(type_, uri, txDataWithDefaults); - } - - 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 type_ of token - * @param uri URI of token - * @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( - type_: BigNumber, - uri: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('type_', type_); - assert.isString('uri', uri); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.createWithType.sendTransactionAsync(type_, uri, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param type_ of token - * @param uri URI of token - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(type_: BigNumber, uri: string, txData?: Partial | undefined): Promise { - assert.isBigNumber('type_', type_); - assert.isString('uri', uri); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('createWithType(uint256,string)', [type_, uri]); - 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 type_ of token - * @param uri URI of token - */ - async callAsync( - type_: BigNumber, - uri: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('type_', type_); - assert.isString('uri', uri); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('createWithType(uint256,string)', [type_, uri]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('createWithType(uint256,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 type_ of token - * @param uri URI of token - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(type_: BigNumber, uri: string): string { - assert.isBigNumber('type_', type_); - assert.isString('uri', uri); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments('createWithType(uint256,string)', [ - type_, - uri, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder('createWithType(uint256,string)'); - return abiEncoder.getSelector(); - }, - }; - public creators = { - /** - * 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('creators(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('creators(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns base type of non-fungible token - */ - public getNonFungibleBaseType = { - /** - * 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( - id: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('getNonFungibleBaseType(uint256)', [id]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('getNonFungibleBaseType(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns index of non-fungible token - */ - public getNonFungibleIndex = { - /** - * 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( - id: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('getNonFungibleIndex(uint256)', [id]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('getNonFungibleIndex(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 owner of the Tokens - * @param operator Address of authorized operator - * @returns True if the operator is approved, false if not - */ - 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 ERC1155MintableContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns true if token is fungible - */ - public isFungible = { - /** - * 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(id: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('isFungible(uint256)', [id]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('isFungible(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns true if token is non-fungible - */ - public isNonFungible = { - /** - * 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(id: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('isNonFungible(uint256)', [id]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('isNonFungible(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns true if input is base-type of a non-fungible token - */ - public isNonFungibleBaseType = { - /** - * 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(id: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('isNonFungibleBaseType(uint256)', [id]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('isNonFungibleBaseType(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns true if input is a non-fungible token - */ - public isNonFungibleItem = { - /** - * 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(id: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('isNonFungibleItem(uint256)', [id]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('isNonFungibleItem(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public maxIndex = { - /** - * 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('maxIndex(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('maxIndex(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * mints fungible tokens - */ - public mintFungible = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param id token type - * @param to beneficiaries of minted tokens - * @param quantities amounts of minted tokens - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - id: BigNumber, - to: string[], - quantities: BigNumber[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('id', id); - assert.isArray('to', to); - assert.isArray('quantities', quantities); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ - id, - to, - quantities, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.mintFungible.callAsync(id, to, quantities, txDataWithDefaults); - } - - 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 id token type - * @param to beneficiaries of minted tokens - * @param quantities amounts of minted tokens - * @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( - id: BigNumber, - to: string[], - quantities: BigNumber[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('id', id); - assert.isArray('to', to); - assert.isArray('quantities', quantities); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.mintFungible.sendTransactionAsync(id, to, quantities, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param id token type - * @param to beneficiaries of minted tokens - * @param quantities amounts of minted tokens - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - id: BigNumber, - to: string[], - quantities: BigNumber[], - txData?: Partial | undefined, - ): Promise { - assert.isBigNumber('id', id); - assert.isArray('to', to); - assert.isArray('quantities', quantities); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ - id, - to, - quantities, - ]); - 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 id token type - * @param to beneficiaries of minted tokens - * @param quantities amounts of minted tokens - */ - async callAsync( - id: BigNumber, - to: string[], - quantities: BigNumber[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('id', id); - assert.isArray('to', to); - assert.isArray('quantities', quantities); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ - id, - to, - quantities, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('mintFungible(uint256,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 id token type - * @param to beneficiaries of minted tokens - * @param quantities amounts of minted tokens - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(id: BigNumber, to: string[], quantities: BigNumber[]): string { - assert.isBigNumber('id', id); - assert.isArray('to', to); - assert.isArray('quantities', quantities); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ - id, - to, - quantities, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder('mintFungible(uint256,address[],uint256[])'); - return abiEncoder.getSelector(); - }, - }; - /** - * mints a non-fungible token - */ - public mintNonFungible = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param type_ token type - * @param to beneficiaries of minted tokens - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - type_: BigNumber, - to: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('type_', type_); - assert.isArray('to', to); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [type_, to]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.mintNonFungible.callAsync(type_, to, txDataWithDefaults); - } - - 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 type_ token type - * @param to beneficiaries of minted tokens - * @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( - type_: BigNumber, - to: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('type_', type_); - assert.isArray('to', to); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.mintNonFungible.sendTransactionAsync(type_, to, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param type_ token type - * @param to beneficiaries of minted tokens - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(type_: BigNumber, to: string[], txData?: Partial | undefined): Promise { - assert.isBigNumber('type_', type_); - assert.isArray('to', to); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [type_, to]); - 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 type_ token type - * @param to beneficiaries of minted tokens - */ - async callAsync( - type_: BigNumber, - to: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('type_', type_); - assert.isArray('to', to); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [type_, to]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('mintNonFungible(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). - * @param type_ token type - * @param to beneficiaries of minted tokens - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(type_: BigNumber, to: string[]): string { - assert.isBigNumber('type_', type_); - assert.isArray('to', to); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [ - type_, - to, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder('mintNonFungible(uint256,address[])'); - return abiEncoder.getSelector(); - }, - }; - /** - * returns owner of a non-fungible token - */ - 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. - */ - async callAsync(id: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('ownerOf(uint256)', [id]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * MUST emit TransferBatch event on success. Caller must be approved to manage the _from account's tokens (see isApprovedForAll). MUST throw if `_to` is the zero address. MUST throw if length of `_ids` is not the same as length of `_values`. MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. MUST throw on any other error. When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. - */ - public safeBatchTransferFrom = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param from Source addresses - * @param to Target addresses - * @param ids IDs of each token type - * @param values Transfer amounts per token type - * @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, - ids: BigNumber[], - values: BigNumber[], - data: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('from', from); - assert.isString('to', to); - assert.isArray('ids', ids); - assert.isArray('values', values); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments( - 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', - [from.toLowerCase(), to.toLowerCase(), ids, values, data], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.safeBatchTransferFrom.callAsync(from, to, ids, values, data, txDataWithDefaults); - } - - 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 Source addresses - * @param to Target addresses - * @param ids IDs of each token type - * @param values Transfer amounts per token type - * @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, - ids: BigNumber[], - values: BigNumber[], - data: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('from', from); - assert.isString('to', to); - assert.isArray('ids', ids); - assert.isArray('values', values); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.safeBatchTransferFrom.sendTransactionAsync( - from.toLowerCase(), - to.toLowerCase(), - ids, - values, - data, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param from Source addresses - * @param to Target addresses - * @param ids IDs of each token type - * @param values Transfer amounts per token type - * @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, - ids: BigNumber[], - values: BigNumber[], - data: string, - txData?: Partial | undefined, - ): Promise { - assert.isString('from', from); - assert.isString('to', to); - assert.isArray('ids', ids); - assert.isArray('values', values); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments( - 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', - [from.toLowerCase(), to.toLowerCase(), ids, values, 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 Source addresses - * @param to Target addresses - * @param ids IDs of each token type - * @param values Transfer amounts per token type - * @param data Additional data with no specified format, sent in call to `_to` - */ - async callAsync( - from: string, - to: string, - ids: BigNumber[], - values: BigNumber[], - data: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('from', from); - assert.isString('to', to); - assert.isArray('ids', ids); - assert.isArray('values', values); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments( - 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', - [from.toLowerCase(), to.toLowerCase(), ids, values, data], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'safeBatchTransferFrom(address,address,uint256[],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 Source addresses - * @param to Target addresses - * @param ids IDs of each token type - * @param values Transfer amounts per token type - * @param data Additional data with no specified format, sent in call to `_to` - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - from: string, - to: string, - ids: BigNumber[], - values: BigNumber[], - data: string, - ): string { - assert.isString('from', from); - assert.isString('to', to); - assert.isArray('ids', ids); - assert.isArray('values', values); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', - [from.toLowerCase(), to.toLowerCase(), ids, values, data], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder( - 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * MUST emit TransferSingle event on success. Caller must be approved to manage the _from account's tokens (see isApprovedForAll). MUST throw if `_to` is the zero address. MUST throw if balance of sender for token `_id` is lower than the `_value` sent. MUST throw on any other error. When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. - */ - public safeTransferFrom = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param from Source address - * @param to Target address - * @param id ID of the token type - * @param value Transfer amount - * @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, - id: BigNumber, - value: BigNumber, - data: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('from', from); - assert.isString('to', to); - assert.isBigNumber('id', id); - assert.isBigNumber('value', value); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,uint256,bytes)', [ - from.toLowerCase(), - to.toLowerCase(), - id, - 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(); - } - - if (opts.shouldValidate !== false) { - await self.safeTransferFrom.callAsync(from, to, id, value, data, txDataWithDefaults); - } - - 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 Source address - * @param to Target address - * @param id ID of the token type - * @param value Transfer amount - * @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, - id: BigNumber, - value: BigNumber, - data: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('from', from); - assert.isString('to', to); - assert.isBigNumber('id', id); - assert.isBigNumber('value', value); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.safeTransferFrom.sendTransactionAsync( - from.toLowerCase(), - to.toLowerCase(), - id, - value, - data, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param from Source address - * @param to Target address - * @param id ID of the token type - * @param value Transfer amount - * @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, - id: BigNumber, - value: BigNumber, - data: string, - txData?: Partial | undefined, - ): Promise { - assert.isString('from', from); - assert.isString('to', to); - assert.isBigNumber('id', id); - assert.isBigNumber('value', value); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,uint256,bytes)', [ - from.toLowerCase(), - to.toLowerCase(), - id, - 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 from Source address - * @param to Target address - * @param id ID of the token type - * @param value Transfer amount - * @param data Additional data with no specified format, sent in call to `_to` - */ - async callAsync( - from: string, - to: string, - id: BigNumber, - value: BigNumber, - data: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('from', from); - assert.isString('to', to); - assert.isBigNumber('id', id); - 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 ERC1155MintableContract; - const encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,uint256,bytes)', [ - from.toLowerCase(), - to.toLowerCase(), - id, - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,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 Source address - * @param to Target address - * @param id ID of the token type - * @param value Transfer amount - * @param data Additional data with no specified format, sent in call to `_to` - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(from: string, to: string, id: BigNumber, value: BigNumber, data: string): string { - assert.isString('from', from); - assert.isString('to', to); - assert.isBigNumber('id', id); - assert.isBigNumber('value', value); - assert.isString('data', data); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'safeTransferFrom(address,address,uint256,uint256,bytes)', - [from.toLowerCase(), to.toLowerCase(), id, value, data], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,uint256,bytes)'); - return abiEncoder.getSelector(); - }, - }; - /** - * MUST emit the ApprovalForAll event on success. - */ - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('operator', operator); - assert.isBoolean('approved', approved); - const self = (this as any) as ERC1155MintableContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.setApprovalForAll.callAsync(operator, approved, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('operator', operator); - assert.isBoolean('approved', approved); - const self = (this as any) as ERC1155MintableContract; - const txHashPromise = self.setApprovalForAll.sendTransactionAsync( - operator.toLowerCase(), - approved, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 ERC1155MintableContract; - 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 ERC1155MintableContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(operator: string, approved: boolean): string { - assert.isString('operator', operator); - assert.isBoolean('approved', approved); - const self = (this as any) as ERC1155MintableContract; - const abiEncodedTransactionData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ - operator.toLowerCase(), - approved, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC1155MintableContract; - const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -2744,6 +691,1554 @@ export class ERC1155MintableContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = ERC1155MintableContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC1155MintableContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC1155MintableContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC1155MintableContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + public ERC1155_BATCH_RECEIVED(): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + + return { + 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 encodedData = self._strictEncodeArguments('ERC1155_BATCH_RECEIVED()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ERC1155_BATCH_RECEIVED()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('ERC1155_BATCH_RECEIVED()', []); + return abiEncodedTransactionData; + }, + }; + } + public ERC1155_RECEIVED(): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + + return { + 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 encodedData = self._strictEncodeArguments('ERC1155_RECEIVED()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ERC1155_RECEIVED()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('ERC1155_RECEIVED()', []); + return abiEncodedTransactionData; + }, + }; + } + public balanceOf(owner: string, id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isString('owner', owner); + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOf(address,uint256)', [ + owner.toLowerCase(), + id, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address,uint256)', [ + owner.toLowerCase(), + id, + ]); + return abiEncodedTransactionData; + }, + }; + } + public balanceOfBatch(owners: string[], ids: BigNumber[]): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isArray('owners', owners); + assert.isArray('ids', ids); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOfBatch(address[],uint256[])', [owners, ids]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOfBatch(address[],uint256[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOfBatch(address[],uint256[])', [ + owners, + ids, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * creates a new token + * @param uri URI of token + * @param isNF is non-fungible token + * @returns type_ of token (a unique identifier) + */ + public create(uri: string, isNF: boolean): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isString('uri', uri); + assert.isBoolean('isNF', isNF); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('create(string,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('create(string,bool)', [uri, isNF]); + return abiEncodedTransactionData; + }, + }; + } + /** + * creates a new token + * @param type_ of token + * @param uri URI of token + */ + public createWithType(type_: BigNumber, uri: string): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('type_', type_); + assert.isString('uri', uri); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('createWithType(uint256,string)', [type_, uri]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('createWithType(uint256,string)', [type_, uri]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('createWithType(uint256,string)', [type_, uri]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('createWithType(uint256,string)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('createWithType(uint256,string)', [ + type_, + uri, + ]); + return abiEncodedTransactionData; + }, + }; + } + public creators(index_0: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('creators(uint256)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('creators(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('creators(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns base type of non-fungible token + */ + public getNonFungibleBaseType(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('getNonFungibleBaseType(uint256)', [id]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getNonFungibleBaseType(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getNonFungibleBaseType(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns index of non-fungible token + */ + public getNonFungibleIndex(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('getNonFungibleIndex(uint256)', [id]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getNonFungibleIndex(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getNonFungibleIndex(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + public isApprovedForAll(owner: string, operator: string): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isString('owner', owner); + assert.isString('operator', operator); + + return { + 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 encodedData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + owner.toLowerCase(), + operator.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + owner.toLowerCase(), + operator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns true if token is fungible + */ + public isFungible(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('isFungible(uint256)', [id]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isFungible(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isFungible(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns true if token is non-fungible + */ + public isNonFungible(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('isNonFungible(uint256)', [id]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isNonFungible(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isNonFungible(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns true if input is base-type of a non-fungible token + */ + public isNonFungibleBaseType(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('isNonFungibleBaseType(uint256)', [id]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isNonFungibleBaseType(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isNonFungibleBaseType(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns true if input is a non-fungible token + */ + public isNonFungibleItem(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('isNonFungibleItem(uint256)', [id]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isNonFungibleItem(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isNonFungibleItem(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + public maxIndex(index_0: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('maxIndex(uint256)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('maxIndex(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('maxIndex(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + /** + * mints fungible tokens + * @param id token type + * @param to beneficiaries of minted tokens + * @param quantities amounts of minted tokens + */ + public mintFungible(id: BigNumber, to: string[], quantities: BigNumber[]): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + assert.isArray('to', to); + assert.isArray('quantities', quantities); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ + id, + to, + quantities, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ + id, + to, + quantities, + ]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('mintFungible(uint256,address[],uint256[])', [ + id, + to, + quantities, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('mintFungible(uint256,address[],uint256[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'mintFungible(uint256,address[],uint256[])', + [id, to, quantities], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * mints a non-fungible token + * @param type_ token type + * @param to beneficiaries of minted tokens + */ + public mintNonFungible(type_: BigNumber, to: string[]): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('type_', type_); + assert.isArray('to', to); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [type_, to]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [type_, to]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [type_, to]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('mintNonFungible(uint256,address[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('mintNonFungible(uint256,address[])', [ + type_, + to, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * returns owner of a non-fungible token + */ + public ownerOf(id: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isBigNumber('id', id); + + return { + 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 encodedData = self._strictEncodeArguments('ownerOf(uint256)', [id]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('ownerOf(uint256)', [id]); + return abiEncodedTransactionData; + }, + }; + } + /** + * MUST emit TransferBatch event on success. Caller must be approved to manage the _from account's tokens (see isApprovedForAll). MUST throw if `_to` is the zero address. MUST throw if length of `_ids` is not the same as length of `_values`. MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_values` sent. MUST throw on any other error. When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`. + * @param from Source addresses + * @param to Target addresses + * @param ids IDs of each token type + * @param values Transfer amounts per token type + * @param data Additional data with no specified format, sent in call to `_to` + */ + public safeBatchTransferFrom( + from: string, + to: string, + ids: BigNumber[], + values: BigNumber[], + data: string, + ): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isString('from', from); + assert.isString('to', to); + assert.isArray('ids', ids); + assert.isArray('values', values); + assert.isString('data', data); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', + [from.toLowerCase(), to.toLowerCase(), ids, values, data], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', + [from.toLowerCase(), to.toLowerCase(), ids, values, 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; + }, + 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 encodedData = self._strictEncodeArguments( + 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', + [from.toLowerCase(), to.toLowerCase(), ids, values, data], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)', + [from.toLowerCase(), to.toLowerCase(), ids, values, data], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * MUST emit TransferSingle event on success. Caller must be approved to manage the _from account's tokens (see isApprovedForAll). MUST throw if `_to` is the zero address. MUST throw if balance of sender for token `_id` is lower than the `_value` sent. MUST throw on any other error. When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return value is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`. + * @param from Source address + * @param to Target address + * @param id ID of the token type + * @param value Transfer amount + * @param data Additional data with no specified format, sent in call to `_to` + */ + public safeTransferFrom( + from: string, + to: string, + id: BigNumber, + value: BigNumber, + data: string, + ): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isString('from', from); + assert.isString('to', to); + assert.isBigNumber('id', id); + assert.isBigNumber('value', value); + assert.isString('data', data); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,uint256,bytes)', + [from.toLowerCase(), to.toLowerCase(), id, 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,uint256,bytes)', + [from.toLowerCase(), to.toLowerCase(), id, 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; + }, + 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 encodedData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,uint256,bytes)', + [from.toLowerCase(), to.toLowerCase(), id, value, data], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,uint256,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,uint256,bytes)', + [from.toLowerCase(), to.toLowerCase(), id, value, data], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * MUST emit the ApprovalForAll event on success. + * @param operator Address to add to the set of authorized operators + * @param approved True if the operator is approved, false to revoke approval + */ + public setApprovalForAll(operator: string, approved: boolean): ContractTxFunctionObj { + const self = (this as any) as ERC1155MintableContract; + assert.isString('operator', operator); + assert.isBoolean('approved', approved); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + operator.toLowerCase(), + approved, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + operator.toLowerCase(), + approved, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the ERC1155Mintable contract. * @param eventName The ERC1155Mintable contract event you would like to subscribe to. @@ -2833,6 +2328,12 @@ export class ERC1155MintableContract extends BaseContract { ERC1155MintableContract.ABI(), this._web3Wrapper, ); + ERC1155MintableContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 df2b061a3a..c1d3579e53 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc20_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc20_token.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -58,743 +61,7 @@ export class ERC20TokenContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * `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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.approve.callAsync(_spender, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('totalSupply()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferFrom.callAsync(_from, _to, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transfer.callAsync(_to, _value, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC20TokenContract; - const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -1043,6 +310,577 @@ export class ERC20TokenContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = ERC20TokenContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC20TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * `msg.sender` approves `_spender` to spend `_value` tokens + * @param _spender The address of the account able to transfer the tokens + * @param _value The amount of wei to be approved for transfer + * @returns Always true if the call has enough gas to complete execution + */ + public approve(_spender: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ERC20TokenContract; + assert.isString('_spender', _spender); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _spender.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Query total supply of token + * @returns Total supply of token + */ + public totalSupply(): ContractFunctionObj { + const self = (this as any) as ERC20TokenContract; + + return { + 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 encodedData = self._strictEncodeArguments('totalSupply()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * send `value` token to `to` from `from` on the condition it is approved by `from` + * @param _from The address of the sender + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @returns True if transfer was successful + */ + public transferFrom(_from: string, _to: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ERC20TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Query the balance of owner + * @param _owner The address from which the balance will be retrieved + * @returns Balance of owner + */ + public balanceOf(_owner: string): ContractFunctionObj { + const self = (this as any) as ERC20TokenContract; + assert.isString('_owner', _owner); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [ + _owner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * send `value` token to `to` from `msg.sender` + * @param _to The address of the recipient + * @param _value The amount of token to be transferred + * @returns True if transfer was successful + */ + public transfer(_to: string, _value: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ERC20TokenContract; + assert.isString('_to', _to); + assert.isBigNumber('_value', _value); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + _to.toLowerCase(), + _value, + ]); + return abiEncodedTransactionData; + }, + }; + } + public allowance(_owner: string, _spender: string): ContractFunctionObj { + const self = (this as any) as ERC20TokenContract; + assert.isString('_owner', _owner); + assert.isString('_spender', _spender); + + return { + 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 encodedData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + _owner.toLowerCase(), + _spender.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the ERC20Token contract. * @param eventName The ERC20Token contract event you would like to subscribe to. @@ -1132,6 +970,12 @@ export class ERC20TokenContract extends BaseContract { ERC20TokenContract.ABI(), this._web3Wrapper, ); + ERC20TokenContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 00ee288b74..7892de27fb 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/erc721_token.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/erc721_token.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -68,1275 +71,7 @@ export class ERC721TokenContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.approve.callAsync(_approved, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.safeTransferFrom1.callAsync(_from, _to, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.safeTransferFrom2.callAsync(_from, _to, _tokenId, _data, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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` - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256,bytes)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.setApprovalForAll.callAsync(_operator, _approved, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferFrom.callAsync(_from, _to, _tokenId, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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 - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ERC721TokenContract; - const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -1665,6 +400,912 @@ export class ERC721TokenContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = ERC721TokenContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ERC721TokenContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * 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. + * @param _approved The new approved NFT controller + * @param _tokenId The NFT to approve + */ + public approve(_approved: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_approved', _approved); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + _approved.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * NFTs assigned to the zero address are considered invalid, and this + * function throws for queries about the zero address. + * @param _owner An address for whom to query the balance + * @returns The number of NFTs owned by `_owner`, possibly zero + */ + public balanceOf(_owner: string): ContractFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_owner', _owner); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOf(address)', [_owner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [ + _owner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Throws if `_tokenId` is not a valid NFT. + * @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 + */ + public getApproved(_tokenId: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isBigNumber('_tokenId', _tokenId); + + return { + 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 encodedData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getApproved(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getApproved(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + }; + } + public isApprovedForAll(_owner: string, _operator: string): ContractFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_owner', _owner); + assert.isString('_operator', _operator); + + return { + 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 encodedData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isApprovedForAll(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isApprovedForAll(address,address)', [ + _owner.toLowerCase(), + _operator.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * NFTs assigned to zero address are considered invalid, and queries + * about them do throw. + * @param _tokenId The identifier for an NFT + * @returns The address of the owner of the NFT + */ + public ownerOf(_tokenId: BigNumber): ContractFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isBigNumber('_tokenId', _tokenId); + + return { + 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 encodedData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ownerOf(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('ownerOf(uint256)', [_tokenId]); + return abiEncodedTransactionData; + }, + }; + } + /** + * This works identically to the other function with an extra data parameter, + * except this function just sets data to "". + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + public safeTransferFrom1(_from: string, _to: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('safeTransferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256)', + [_from.toLowerCase(), _to.toLowerCase(), _tokenId], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * 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)"))`. + * @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` + */ + public safeTransferFrom2( + _from: string, + _to: string, + _tokenId: BigNumber, + _data: string, + ): ContractTxFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + assert.isString('_data', _data); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('safeTransferFrom(address,address,uint256,bytes)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + _data, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'safeTransferFrom(address,address,uint256,bytes)', + [_from.toLowerCase(), _to.toLowerCase(), _tokenId, _data], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Emits the ApprovalForAll event. The contract MUST allow + * multiple operators per owner. + * @param _operator Address to add to the set of authorized operators + * @param _approved True if the operator is approved, false to revoke approval + */ + public setApprovalForAll(_operator: string, _approved: boolean): ContractTxFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_operator', _operator); + assert.isBoolean('_approved', _approved); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setApprovalForAll(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('setApprovalForAll(address,bool)', [ + _operator.toLowerCase(), + _approved, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * 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. + * @param _from The current owner of the NFT + * @param _to The new owner + * @param _tokenId The NFT to transfer + */ + public transferFrom(_from: string, _to: string, _tokenId: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ERC721TokenContract; + assert.isString('_from', _from); + assert.isString('_to', _to); + assert.isBigNumber('_tokenId', _tokenId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + _from.toLowerCase(), + _to.toLowerCase(), + _tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the ERC721Token contract. * @param eventName The ERC721Token contract event you would like to subscribe to. @@ -1754,6 +1395,12 @@ export class ERC721TokenContract extends BaseContract { ERC721TokenContract.ABI(), this._web3Wrapper, ); + ERC721TokenContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts b/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts index bb4329eef8..d56ee22154 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/exchange.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -117,8141 +120,1759 @@ export class ExchangeContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - public EIP1271_MAGIC_VALUE = { - /** - * 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('EIP1271_MAGIC_VALUE()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('EIP1271_MAGIC_VALUE()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 ExchangeContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('allowedValidators(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Executes multiple calls of cancelOrder. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.batchCancelOrders.callAsync(orders, txDataWithDefaults); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('orders', orders); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.batchCancelOrders.sendTransactionAsync(orders, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes)[])', - [orders], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Executes a batch of Exchange method calls in the context of signer(s). - */ - public batchExecuteTransactions = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param transactions Array of 0x transaction structures. - * @param signatures Array of proofs that transactions have been signed by - * signer(s). - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - transactions: Array<{ - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }>, - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('transactions', transactions); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', - [transactions, signatures], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.batchExecuteTransactions.callAsync(transactions, signatures, txDataWithDefaults); - } - - 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 transactions Array of 0x transaction structures. - * @param signatures Array of proofs that transactions have been signed by - * signer(s). - * @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( - transactions: Array<{ - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }>, - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('transactions', transactions); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.batchExecuteTransactions.sendTransactionAsync( - transactions, - signatures, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param transactions Array of 0x transaction structures. - * @param signatures Array of proofs that transactions have been signed by - * signer(s). - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - transactions: Array<{ - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }>, - signatures: string[], - txData?: Partial | undefined, - ): Promise { - assert.isArray('transactions', transactions); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', - [transactions, 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 transactions Array of 0x transaction structures. - * @param signatures Array of proofs that transactions have been signed by - * signer(s). - * @returns Array containing ABI encoded return data for each of the underlying Exchange function calls. - */ - async callAsync( - transactions: Array<{ - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }>, - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isArray('transactions', transactions); - 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( - 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', - [transactions, signatures], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchExecuteTransactions((uint256,uint256,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 transactions Array of 0x transaction structures. - * @param signatures Array of proofs that transactions have been signed by - * signer(s). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - transactions: Array<{ - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }>, - signatures: string[], - ): string { - assert.isArray('transactions', transactions); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', - [transactions, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Executes multiple calls of fillOrKillOrder. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.batchFillOrKillOrders.callAsync( - orders, - takerAssetFillAmounts, - signatures, - txDataWithDefaults, - ); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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 Array of 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes)[],uint256[],bytes[])', - [orders, takerAssetFillAmounts, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.batchFillOrders.callAsync(orders, takerAssetFillAmounts, signatures, txDataWithDefaults); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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 Array of 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes)[],uint256[],bytes[])', - [orders, takerAssetFillAmounts, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.batchFillOrdersNoThrow.callAsync( - orders, - takerAssetFillAmounts, - signatures, - txDataWithDefaults, - ); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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 Array of 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmounts: BigNumber[], - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise< - Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes)[],uint256[],bytes[])', - [orders, takerAssetFillAmounts, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Match complementary orders that have a profitable spread. - * Each order is filled at their respective price point, and - * the matcher receives a profit denominated in the left maker asset. - */ - public batchMatchOrders = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.batchMatchOrders.callAsync( - leftOrders, - rightOrders, - leftSignatures, - rightSignatures, - txDataWithDefaults, - ); - } - - 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 leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * 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( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.batchMatchOrders.sendTransactionAsync( - leftOrders, - rightOrders, - leftSignatures, - rightSignatures, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - txData?: Partial | undefined, - ): Promise { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + private readonly _methodABIIndex: { [name: string]: number } = {}; + private readonly _subscriptionManager: SubscriptionManager; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + chainId: 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 ExchangeContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, chainId); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + chainId: 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); + [chainId] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [chainId], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [chainId]); + 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 = [chainId]; + return contractInstance; + } - 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 leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @returns batchMatchedFillResults Amounts filled and profit generated. - */ - async callAsync( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - left: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - right: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: BigNumber; - }> { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - 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( - 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - left: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - right: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: 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 leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - ): string { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; /** - * Match complementary orders that have a profitable spread. - * Each order is maximally filled at their respective price point, and - * the matcher receives a profit denominated in either the left maker asset, - * right maker asset, or a combination of both. - */ - public batchMatchOrdersWithMaximalFill = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.batchMatchOrdersWithMaximalFill.callAsync( - leftOrders, - rightOrders, - leftSignatures, - rightSignatures, - txDataWithDefaults, - ); - } - - 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 leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * 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( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.batchMatchOrdersWithMaximalFill.sendTransactionAsync( - leftOrders, - rightOrders, - leftSignatures, - rightSignatures, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - txData?: Partial | undefined, - ): Promise { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - 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 leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @returns batchMatchedFillResults Amounts filled and profit generated. - */ - async callAsync( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - left: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - right: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: BigNumber; - }> { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - 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( - 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - left: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - right: Array<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }>; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: 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 leftOrders Set of orders with the same maker / taker asset. - * @param rightOrders Set of orders to match against `leftOrders` - * @param leftSignatures Proof that left orders were created by the left - * makers. - * @param rightSignatures Proof that right orders were created by the right - * makers. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - leftOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - rightOrders: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - leftSignatures: string[], - rightSignatures: string[], - ): string { - assert.isArray('leftOrders', leftOrders); - assert.isArray('rightOrders', rightOrders); - assert.isArray('leftSignatures', leftSignatures); - assert.isArray('rightSignatures', rightSignatures); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - [leftOrders, rightOrders, leftSignatures, rightSignatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * After calling, the order can not be filled anymore. - */ - 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 struct containing order specifications. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.cancelOrder.callAsync(order, txDataWithDefaults); - } - - 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 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as ExchangeContract; - const txHashPromise = self.cancelOrder.sendTransactionAsync(order, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param order Order struct containing order specifications. - * @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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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 struct containing order specifications. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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 struct containing order specifications. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes))', - [order], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.cancelOrdersUpTo.callAsync(targetOrderEpoch, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.cancelOrdersUpTo.sendTransactionAsync(targetOrderEpoch, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(targetOrderEpoch: BigNumber): string { - assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [ - targetOrderEpoch, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('cancelOrdersUpTo(uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('cancelled(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('currentContextAddress()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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 transaction 0x transaction structure. - * @param signature Proof that transaction has been signed by signer. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - transaction: { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }, - signature: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('signature', signature); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', - [transaction, signature], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.executeTransaction.callAsync(transaction, signature, txDataWithDefaults); - } - - 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 structure. - * @param signature Proof that transaction 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( - transaction: { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }, - signature: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('signature', signature); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.executeTransaction.sendTransactionAsync(transaction, signature, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param transaction 0x transaction structure. - * @param signature Proof that transaction has been signed by signer. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - transaction: { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }, - signature: string, - txData?: Partial | undefined, - ): Promise { - assert.isString('signature', signature); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', - [transaction, 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 transaction 0x transaction structure. - * @param signature Proof that transaction has been signed by signer. - * @returns ABI encoded return data of the underlying Exchange function call. - */ - async callAsync( - transaction: { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }, - signature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - 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,uint256,uint256,address,bytes),bytes)', - [transaction, signature], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'executeTransaction((uint256,uint256,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 transaction 0x transaction structure. - * @param signature Proof that transaction has been signed by signer. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - transaction: { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }, - signature: string, - ): string { - assert.isString('signature', signature); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', - [transaction, signature], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAssetFillAmount: BigNumber, - signature: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.fillOrKillOrder.callAsync(order, takerAssetFillAmount, signature, txDataWithDefaults); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAssetFillAmount: BigNumber, - signature: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAssetFillAmount: BigNumber, - signature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes),uint256,bytes)', - [order, takerAssetFillAmount, signature], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAssetFillAmount: BigNumber, - signature: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.fillOrder.callAsync(order, takerAssetFillAmount, signature, txDataWithDefaults); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAssetFillAmount: BigNumber, - signature: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - takerAssetFillAmount: BigNumber, - signature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes),uint256,bytes)', - [order, takerAssetFillAmount, signature], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', - ); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('filled(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - orderStatus: number; - orderHash: string; - orderTakerAssetFilledAmount: BigNumber; - }>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Verifies that a hash has been signed by the given signer. - */ - public isValidHashSignature = { - /** - * 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 isValid `true` if the signature is valid for the given hash and 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('isValidHashSignature(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('isValidHashSignature(bytes32,address,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Verifies that a signature for an order is valid. - */ - public isValidOrderSignature = { - /** - * 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 order. - * @param signature Proof that the order has been signed by signer. - * @returns isValid `true` if the signature is valid for the given order and signer. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - signature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - 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( - 'isValidOrderSignature((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', - [order, signature], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'isValidOrderSignature((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Verifies that a signature for a transaction is valid. - */ - public isValidTransactionSignature = { - /** - * 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 The transaction. - * @param signature Proof that the order has been signed by signer. - * @returns isValid `true` if the signature is valid for the given transaction and signer. - */ - async callAsync( - transaction: { - salt: BigNumber; - expirationTimeSeconds: BigNumber; - gasPrice: BigNumber; - signerAddress: string; - data: string; - }, - signature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - 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( - 'isValidTransactionSignature((uint256,uint256,uint256,address,bytes),bytes)', - [transaction, signature], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'isValidTransactionSignature((uint256,uint256,uint256,address,bytes),bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. - * NOTE: This function does not enforce that the makerAsset is the same for each order. - */ - public marketBuyOrdersFillOrKill = { - /** - * 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 Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); - } - - if (opts.shouldValidate !== false) { - await self.marketBuyOrdersFillOrKill.callAsync( - orders, - makerAssetFillAmount, - signatures, - txDataWithDefaults, - ); - } - - 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 Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.marketBuyOrdersFillOrKill.sendTransactionAsync( - orders, - makerAssetFillAmount, - signatures, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param orders Array of order specifications. - * @param makerAssetFillAmount Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: 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( - 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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 Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetFillAmount: BigNumber, - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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( - 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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 Minimum amount of makerAsset to buy. - * @param signatures Proofs that orders have been signed by makers. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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( - 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - [orders, makerAssetFillAmount, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. - * If any fill reverts, the error is caught and ignored. - * NOTE: This function does not enforce that the makerAsset is the same for each order. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.marketBuyOrdersNoThrow.callAsync( - orders, - makerAssetFillAmount, - signatures, - txDataWithDefaults, - ); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetFillAmount: BigNumber, - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes)[],uint256,bytes[])', - [orders, makerAssetFillAmount, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. - * NOTE: This function does not enforce that the takerAsset is the same for each order. - */ - public marketSellOrdersFillOrKill = { - /** - * 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 Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('orders', orders); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); - } - - if (opts.shouldValidate !== false) { - await self.marketSellOrdersFillOrKill.callAsync( - orders, - takerAssetFillAmount, - signatures, - txDataWithDefaults, - ); - } - - 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 Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('orders', orders); - assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); - assert.isArray('signatures', signatures); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.marketSellOrdersFillOrKill.sendTransactionAsync( - orders, - takerAssetFillAmount, - signatures, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param orders Array of order specifications. - * @param takerAssetFillAmount Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: 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( - 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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 Minimum 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmount: BigNumber, - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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( - 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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 Minimum amount of takerAsset to sell. - * @param signatures Proofs that orders have been signed by makers. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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( - 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - [orders, takerAssetFillAmount, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. - * If any fill reverts, the error is caught and ignored. - * NOTE: This function does not enforce that the takerAsset is the same for each order. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,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(); - } - - if (opts.shouldValidate !== false) { - await self.marketSellOrdersNoThrow.callAsync( - orders, - takerAssetFillAmount, - signatures, - txDataWithDefaults, - ); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmount: BigNumber, - signatures: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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,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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - takerAssetFillAmount: BigNumber, - signatures: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes)[],uint256,bytes[])', - [orders, takerAssetFillAmount, signatures], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - leftSignature: string, - rightSignature: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); - } - - if (opts.shouldValidate !== false) { - await self.matchOrders.callAsync( - leftOrder, - rightOrder, - leftSignature, - rightSignature, - txDataWithDefaults, - ); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - leftSignature: string, - rightSignature: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - leftSignature: string, - rightSignature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - left: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - right: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: 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,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - left: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - right: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: 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,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', - [leftOrder, rightOrder, leftSignature, rightSignature], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Match two complementary orders that have a profitable spread. - * Each order is maximally filled at their respective price point, and - * the matcher receives a profit denominated in either the left maker asset, - * right maker asset, or a combination of both. - */ - public matchOrdersWithMaximalFill = { - /** - * 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - leftSignature: string, - rightSignature: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('leftSignature', leftSignature); - assert.isString('rightSignature', rightSignature); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); - } - - if (opts.shouldValidate !== false) { - await self.matchOrdersWithMaximalFill.callAsync( - leftOrder, - rightOrder, - leftSignature, - rightSignature, - txDataWithDefaults, - ); - } - - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - leftSignature: string, - rightSignature: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('leftSignature', leftSignature); - assert.isString('rightSignature', rightSignature); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.matchOrdersWithMaximalFill.sendTransactionAsync( - leftOrder, - rightOrder, - leftSignature, - rightSignature, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: 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( - 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }, - leftSignature: string, - rightSignature: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - left: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - right: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: 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( - 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - left: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - right: { - makerAssetFilledAmount: BigNumber; - takerAssetFilledAmount: BigNumber; - makerFeePaid: BigNumber; - takerFeePaid: BigNumber; - protocolFeePaid: BigNumber; - }; - profitInLeftMakerAsset: BigNumber; - profitInRightMakerAsset: 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. - * @returns The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: 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; - makerFeeAssetData: string; - takerFeeAssetData: 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( - 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', - [leftOrder, rightOrder, leftSignature, rightSignature], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', - ); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('orderEpoch(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('owner()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Approves a hash on-chain. - * 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 hash Any 32-byte hash. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - hash: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('hash', hash); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments('preSign(bytes32)', [hash]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.preSign.callAsync(hash, txDataWithDefaults); - } - - 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 hash Any 32-byte hash. - * @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, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('hash', hash); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.preSign.sendTransactionAsync(hash, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param hash Any 32-byte hash. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(hash: string, txData?: Partial | undefined): Promise { - assert.isString('hash', hash); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments('preSign(bytes32)', [hash]); - 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 hash Any 32-byte hash. - */ - async callAsync(hash: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('hash', hash); - 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)', [hash]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('preSign(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). - * @param hash Any 32-byte hash. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(hash: string): string { - assert.isString('hash', hash); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments('preSign(bytes32)', [hash]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('preSign(bytes32)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('preSigned(bytes32,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public protocolFeeCollector = { - /** - * 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('protocolFeeCollector()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('protocolFeeCollector()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public protocolFeeMultiplier = { - /** - * 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('protocolFeeMultiplier()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('protocolFeeMultiplier()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.registerAssetProxy.callAsync(assetProxy, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('assetProxy', assetProxy); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.registerAssetProxy.sendTransactionAsync(assetProxy.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Allows the owner to update the protocolFeeCollector address. - */ - public setProtocolFeeCollectorAddress = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param updatedProtocolFeeCollector The updated protocolFeeCollector contract - * address. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - updatedProtocolFeeCollector: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('updatedProtocolFeeCollector', updatedProtocolFeeCollector); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments('setProtocolFeeCollectorAddress(address)', [ - updatedProtocolFeeCollector.toLowerCase(), - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.setProtocolFeeCollectorAddress.callAsync(updatedProtocolFeeCollector, txDataWithDefaults); - } - - 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 updatedProtocolFeeCollector The updated protocolFeeCollector contract - * 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( - updatedProtocolFeeCollector: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('updatedProtocolFeeCollector', updatedProtocolFeeCollector); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.setProtocolFeeCollectorAddress.sendTransactionAsync( - updatedProtocolFeeCollector.toLowerCase(), - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param updatedProtocolFeeCollector The updated protocolFeeCollector contract - * address. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - updatedProtocolFeeCollector: string, - txData?: Partial | undefined, - ): Promise { - assert.isString('updatedProtocolFeeCollector', updatedProtocolFeeCollector); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments('setProtocolFeeCollectorAddress(address)', [ - updatedProtocolFeeCollector.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 updatedProtocolFeeCollector The updated protocolFeeCollector contract - * address. - */ - async callAsync( - updatedProtocolFeeCollector: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('updatedProtocolFeeCollector', updatedProtocolFeeCollector); - 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('setProtocolFeeCollectorAddress(address)', [ - updatedProtocolFeeCollector.toLowerCase(), - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('setProtocolFeeCollectorAddress(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 updatedProtocolFeeCollector The updated protocolFeeCollector contract - * address. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(updatedProtocolFeeCollector: string): string { - assert.isString('updatedProtocolFeeCollector', updatedProtocolFeeCollector); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments('setProtocolFeeCollectorAddress(address)', [ - updatedProtocolFeeCollector.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('setProtocolFeeCollectorAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Allows the owner to update the protocol fee multiplier. - */ - public setProtocolFeeMultiplier = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - updatedProtocolFeeMultiplier: BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('updatedProtocolFeeMultiplier', updatedProtocolFeeMultiplier); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ - updatedProtocolFeeMultiplier, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.setProtocolFeeMultiplier.callAsync(updatedProtocolFeeMultiplier, txDataWithDefaults); - } - - 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 updatedProtocolFeeMultiplier The updated protocol fee multiplier. - * @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( - updatedProtocolFeeMultiplier: BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('updatedProtocolFeeMultiplier', updatedProtocolFeeMultiplier); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.setProtocolFeeMultiplier.sendTransactionAsync( - updatedProtocolFeeMultiplier, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - updatedProtocolFeeMultiplier: BigNumber, - txData?: Partial | undefined, - ): Promise { - assert.isBigNumber('updatedProtocolFeeMultiplier', updatedProtocolFeeMultiplier); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ - updatedProtocolFeeMultiplier, - ]); - 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 updatedProtocolFeeMultiplier The updated protocol fee multiplier. - */ - async callAsync( - updatedProtocolFeeMultiplier: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('updatedProtocolFeeMultiplier', updatedProtocolFeeMultiplier); - 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('setProtocolFeeMultiplier(uint256)', [ - updatedProtocolFeeMultiplier, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('setProtocolFeeMultiplier(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 updatedProtocolFeeMultiplier The updated protocol fee multiplier. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(updatedProtocolFeeMultiplier: BigNumber): string { - assert.isBigNumber('updatedProtocolFeeMultiplier', updatedProtocolFeeMultiplier); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ - updatedProtocolFeeMultiplier, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('setProtocolFeeMultiplier(uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Approves/unnapproves a Validator contract to verify signatures on signer's behalf - * using the `Validator` signature type. - */ - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.setSignatureValidatorApproval.callAsync(validatorAddress, approval, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('setSignatureValidatorApproval(address,bool)'); - return abiEncoder.getSelector(); - }, - }; - /** - * This function may be used to simulate any amount of transfers As they would occur through the Exchange contract. Note that this function will always revert, even if all transfers are successful. However, it may be used with eth_call or with a try/catch pattern in order to simulate the results of the transfers. - */ - public simulateDispatchTransferFromCalls = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param assetData Array of asset details, each encoded per the AssetProxy - * contract specification. - * @param fromAddresses Array containing the `from` addresses that correspond - * with each transfer. - * @param toAddresses Array containing the `to` addresses that correspond with - * each transfer. - * @param amounts Array containing the amounts that correspond to each - * transfer. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - assetData: string[], - fromAddresses: string[], - toAddresses: string[], - amounts: BigNumber[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('assetData', assetData); - assert.isArray('fromAddresses', fromAddresses); - assert.isArray('toAddresses', toAddresses); - assert.isArray('amounts', amounts); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', - [assetData, fromAddresses, toAddresses, amounts], - ); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.simulateDispatchTransferFromCalls.callAsync( - assetData, - fromAddresses, - toAddresses, - amounts, - txDataWithDefaults, - ); - } - - 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 Array of asset details, each encoded per the AssetProxy - * contract specification. - * @param fromAddresses Array containing the `from` addresses that correspond - * with each transfer. - * @param toAddresses Array containing the `to` addresses that correspond with - * each transfer. - * @param amounts Array containing the amounts that correspond to each - * 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[], - fromAddresses: string[], - toAddresses: string[], - amounts: BigNumber[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('assetData', assetData); - assert.isArray('fromAddresses', fromAddresses); - assert.isArray('toAddresses', toAddresses); - assert.isArray('amounts', amounts); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.simulateDispatchTransferFromCalls.sendTransactionAsync( - assetData, - fromAddresses, - toAddresses, - amounts, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param assetData Array of asset details, each encoded per the AssetProxy - * contract specification. - * @param fromAddresses Array containing the `from` addresses that correspond - * with each transfer. - * @param toAddresses Array containing the `to` addresses that correspond with - * each transfer. - * @param amounts Array containing the amounts that correspond to each - * transfer. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - assetData: string[], - fromAddresses: string[], - toAddresses: string[], - amounts: BigNumber[], - txData?: Partial | undefined, - ): Promise { - assert.isArray('assetData', assetData); - assert.isArray('fromAddresses', fromAddresses); - assert.isArray('toAddresses', toAddresses); - assert.isArray('amounts', amounts); - const self = (this as any) as ExchangeContract; - const encodedData = self._strictEncodeArguments( - 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', - [assetData, fromAddresses, toAddresses, amounts], - ); - 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 Array of asset details, each encoded per the AssetProxy - * contract specification. - * @param fromAddresses Array containing the `from` addresses that correspond - * with each transfer. - * @param toAddresses Array containing the `to` addresses that correspond with - * each transfer. - * @param amounts Array containing the amounts that correspond to each - * transfer. - * @returns This function does not return a value. However, it will always revert with `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. - */ - async callAsync( - assetData: string[], - fromAddresses: string[], - toAddresses: string[], - amounts: BigNumber[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isArray('assetData', assetData); - assert.isArray('fromAddresses', fromAddresses); - assert.isArray('toAddresses', toAddresses); - assert.isArray('amounts', amounts); - 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( - 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', - [assetData, fromAddresses, toAddresses, amounts], - ); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'simulateDispatchTransferFromCalls(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 Array of asset details, each encoded per the AssetProxy - * contract specification. - * @param fromAddresses Array containing the `from` addresses that correspond - * with each transfer. - * @param toAddresses Array containing the `to` addresses that correspond with - * each transfer. - * @param amounts Array containing the amounts that correspond to each - * transfer. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - assetData: string[], - fromAddresses: string[], - toAddresses: string[], - amounts: BigNumber[], - ): string { - assert.isArray('assetData', assetData); - assert.isArray('fromAddresses', fromAddresses); - assert.isArray('toAddresses', toAddresses); - assert.isArray('amounts', amounts); - const self = (this as any) as ExchangeContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', - [assetData, fromAddresses, toAddresses, amounts], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder( - 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', - ); - return abiEncoder.getSelector(); - }, - }; - public transactionsExecuted = { - /** - * 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('transactionsExecuted(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('transactionsExecuted(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferOwnership.callAsync(newOwner, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('newOwner', newOwner); - const self = (this as any) as ExchangeContract; - const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ExchangeContract; - const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); - return abiEncoder.getSelector(); - }, - }; - private readonly _subscriptionManager: SubscriptionManager; - public static async deployFrom0xArtifactAsync( - artifact: ContractArtifact | SimpleContractArtifact, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - chainId: 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 ExchangeContract.deployAsync(bytecode, abi, provider, txDefaults, logDecodeDependenciesAbiOnly, chainId); - } - public static async deployAsync( - bytecode: string, - abi: ContractAbi, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractAbi }, - chainId: 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); - [chainId] = BaseContract._formatABIDataItemList( - constructorAbi.inputs, - [chainId], - BaseContract._bigNumberToString, - ); - const iface = new ethers.utils.Interface(abi); - const deployInfo = iface.deployFunction; - const txData = deployInfo.encode(bytecode, [chainId]); - 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 = [chainId]; - return contractInstance; - } - - /** - * @returns The contract ABI + * @returns The contract ABI */ public static ABI(): ContractAbi { const abi = [ { inputs: [ { - name: 'chainId', + name: 'chainId', + type: 'uint256', + }, + ], + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'constructor', + }, + { + anonymous: false, + inputs: [ + { + name: 'id', + type: 'bytes4', + indexed: false, + }, + { + name: 'assetProxy', + type: 'address', + indexed: false, + }, + ], + name: 'AssetProxyRegistered', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'makerAddress', + type: 'address', + indexed: true, + }, + { + name: 'feeRecipientAddress', + type: 'address', + indexed: true, + }, + { + name: 'makerAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'takerAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'senderAddress', + type: 'address', + indexed: false, + }, + { + name: 'orderHash', + type: 'bytes32', + indexed: true, + }, + ], + name: 'Cancel', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'makerAddress', + type: 'address', + indexed: true, + }, + { + name: 'orderSenderAddress', + type: 'address', + indexed: true, + }, + { + name: 'orderEpoch', + type: 'uint256', + indexed: false, + }, + ], + name: 'CancelUpTo', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'makerAddress', + type: 'address', + indexed: true, + }, + { + name: 'feeRecipientAddress', + type: 'address', + indexed: true, + }, + { + name: 'makerAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'takerAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'makerFeeAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + indexed: false, + }, + { + name: 'orderHash', + type: 'bytes32', + 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: 'protocolFeePaid', + type: 'uint256', + indexed: false, + }, + ], + name: 'Fill', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'oldProtocolFeeCollector', + type: 'address', + indexed: false, + }, + { + name: 'updatedProtocolFeeCollector', + type: 'address', + indexed: false, + }, + ], + name: 'ProtocolFeeCollectorAddress', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'oldProtocolFeeMultiplier', + type: 'uint256', + indexed: false, + }, + { + name: 'updatedProtocolFeeMultiplier', + type: 'uint256', + indexed: false, + }, + ], + name: 'ProtocolFeeMultiplier', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'signerAddress', + type: 'address', + indexed: true, + }, + { + name: 'validatorAddress', + type: 'address', + indexed: true, + }, + { + name: 'isApproved', + type: 'bool', + indexed: false, + }, + ], + name: 'SignatureValidatorApproval', + outputs: [], + type: 'event', + }, + { + anonymous: false, + inputs: [ + { + name: 'transactionHash', + type: 'bytes32', + indexed: true, + }, + ], + name: 'TransactionExecution', + outputs: [], + type: 'event', + }, + { + constant: true, + inputs: [], + name: 'EIP1271_MAGIC_VALUE', + outputs: [ + { + name: '', + type: 'bytes4', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'EIP712_EXCHANGE_DOMAIN_HASH', + outputs: [ + { + name: '', + type: 'bytes32', + }, + ], + payable: false, + stateMutability: 'view', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + ], + name: 'batchCancelOrders', + outputs: [], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'transactions', + type: 'tuple[]', + components: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'expirationTimeSeconds', + type: 'uint256', + }, + { + name: 'gasPrice', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + ], + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchExecuteTransactions', + outputs: [ + { + name: '', + type: 'bytes[]', + }, + ], + payable: true, + stateMutability: 'payable', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchFillOrKillOrders', + outputs: [ + { + name: 'fillResults', + type: 'tuple[]', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchFillOrders', + outputs: [ + { + name: 'fillResults', + type: 'tuple[]', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'takerAssetFillAmounts', + type: 'uint256[]', + }, + { + name: 'signatures', + type: 'bytes[]', + }, + ], + name: 'batchFillOrdersNoThrow', + outputs: [ + { + name: 'fillResults', + type: 'tuple[]', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'leftOrders', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'rightOrders', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'leftSignatures', + type: 'bytes[]', + }, + { + name: 'rightSignatures', + type: 'bytes[]', + }, + ], + name: 'batchMatchOrders', + outputs: [ + { + name: 'batchMatchedFillResults', + 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: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'right', + type: 'tuple[]', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'profitInLeftMakerAsset', + type: 'uint256', + }, + { + name: 'profitInRightMakerAsset', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'leftOrders', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'rightOrders', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'leftSignatures', + type: 'bytes[]', + }, + { + name: 'rightSignatures', + type: 'bytes[]', + }, + ], + name: 'batchMatchOrdersWithMaximalFill', + outputs: [ + { + name: 'batchMatchedFillResults', + 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: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'right', + type: 'tuple[]', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], + }, + { + name: 'profitInLeftMakerAsset', + type: 'uint256', + }, + { + name: 'profitInRightMakerAsset', + type: 'uint256', + }, + ], + }, + ], + payable: true, + stateMutability: 'payable', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + ], + name: 'cancelOrder', + outputs: [], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'targetOrderEpoch', type: 'uint256', }, ], + name: 'cancelOrdersUpTo', outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'constructor', + payable: true, + stateMutability: 'payable', + type: 'function', }, { - anonymous: false, + constant: true, inputs: [ { - name: 'id', - type: 'bytes4', - indexed: false, + name: 'index_0', + type: 'bytes32', }, + ], + name: 'cancelled', + outputs: [ { - name: 'assetProxy', + name: '', + type: 'bool', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'currentContextAddress', + outputs: [ + { + name: '', type: 'address', - indexed: false, }, ], - name: 'AssetProxyRegistered', - outputs: [], - type: 'event', + payable: false, + stateMutability: 'view', + type: 'function', }, { - anonymous: false, + constant: false, inputs: [ { - name: 'makerAddress', - type: 'address', - indexed: true, + name: 'transaction', + type: 'tuple', + components: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'expirationTimeSeconds', + type: 'uint256', + }, + { + name: 'gasPrice', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + ], }, { - name: 'feeRecipientAddress', - type: 'address', - indexed: true, + name: 'signature', + type: 'bytes', + }, + ], + name: 'executeTransaction', + outputs: [ + { + name: '', + type: 'bytes', + }, + ], + payable: true, + stateMutability: 'payable', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], }, { - name: 'makerAssetData', - type: 'bytes', - indexed: false, + name: 'takerAssetFillAmount', + type: 'uint256', }, { - name: 'takerAssetData', + name: 'signature', type: 'bytes', - indexed: false, - }, - { - name: 'senderAddress', - type: 'address', - indexed: false, - }, - { - name: 'orderHash', - type: 'bytes32', - indexed: true, }, ], - name: 'Cancel', - outputs: [], - type: 'event', - }, - { - anonymous: false, - inputs: [ - { - name: 'makerAddress', - type: 'address', - indexed: true, - }, - { - name: 'orderSenderAddress', - type: 'address', - indexed: true, - }, + name: 'fillOrKillOrder', + outputs: [ { - name: 'orderEpoch', - type: 'uint256', - indexed: false, + name: 'fillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], }, ], - name: 'CancelUpTo', - outputs: [], - type: 'event', + payable: true, + stateMutability: 'payable', + type: 'function', }, { - anonymous: false, + constant: false, inputs: [ { - name: 'makerAddress', - type: 'address', - indexed: true, - }, - { - name: 'feeRecipientAddress', - type: 'address', - indexed: true, - }, - { - name: 'makerAssetData', - type: 'bytes', - indexed: false, + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], }, { - name: 'takerAssetData', - type: 'bytes', - indexed: false, + name: 'takerAssetFillAmount', + type: 'uint256', }, { - name: 'makerFeeAssetData', + name: 'signature', type: 'bytes', - indexed: false, }, + ], + name: 'fillOrder', + outputs: [ { - name: 'takerFeeAssetData', - type: 'bytes', - indexed: false, + name: 'fillResults', + type: 'tuple', + components: [ + { + name: 'makerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'takerAssetFilledAmount', + type: 'uint256', + }, + { + name: 'makerFeePaid', + type: 'uint256', + }, + { + name: 'takerFeePaid', + type: 'uint256', + }, + { + name: 'protocolFeePaid', + type: 'uint256', + }, + ], }, + ], + payable: true, + stateMutability: 'payable', + type: 'function', + }, + { + constant: true, + inputs: [ { - name: 'orderHash', + name: 'index_0', type: 'bytes32', - 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: 'filled', + outputs: [ { - name: 'protocolFeePaid', + name: '', type: 'uint256', - indexed: false, }, ], - name: 'Fill', - outputs: [], - type: 'event', + payable: false, + stateMutability: 'view', + type: 'function', }, { - anonymous: false, - inputs: [ - { - name: 'oldProtocolFeeCollector', - type: 'address', - indexed: false, + constant: true, + inputs: [ + { + name: 'assetProxyId', + type: 'bytes4', }, + ], + name: 'getAssetProxy', + outputs: [ { - name: 'updatedProtocolFeeCollector', + name: '', type: 'address', - indexed: false, }, ], - name: 'ProtocolFeeCollectorAddress', - outputs: [], - type: 'event', + payable: false, + stateMutability: 'view', + type: 'function', }, { - anonymous: false, + constant: true, inputs: [ { - name: 'oldProtocolFeeMultiplier', - type: 'uint256', - indexed: false, + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], }, + ], + name: 'getOrderInfo', + outputs: [ { - name: 'updatedProtocolFeeMultiplier', - type: 'uint256', - indexed: false, + name: 'orderInfo', + type: 'tuple', + components: [ + { + name: 'orderStatus', + type: 'uint8', + }, + { + name: 'orderHash', + type: 'bytes32', + }, + { + name: 'orderTakerAssetFilledAmount', + type: 'uint256', + }, + ], }, ], - name: 'ProtocolFeeMultiplier', - outputs: [], - type: 'event', + payable: false, + stateMutability: 'view', + type: 'function', }, { - anonymous: false, + constant: true, inputs: [ { - name: 'signerAddress', - type: 'address', - indexed: true, + name: 'hash', + type: 'bytes32', }, { - name: 'validatorAddress', + name: 'signerAddress', type: 'address', - indexed: true, - }, - { - name: 'isApproved', - type: 'bool', - indexed: false, }, - ], - name: 'SignatureValidatorApproval', - outputs: [], - type: 'event', - }, - { - anonymous: false, - inputs: [ { - name: 'transactionHash', - type: 'bytes32', - indexed: true, + name: 'signature', + type: 'bytes', }, ], - name: 'TransactionExecution', - outputs: [], - type: 'event', - }, - { - constant: true, - inputs: [], - name: 'EIP1271_MAGIC_VALUE', + name: 'isValidHashSignature', outputs: [ { - name: '', - type: 'bytes4', + name: 'isValid', + type: 'bool', }, ], payable: false, @@ -8260,12 +1881,79 @@ export class ExchangeContract extends BaseContract { }, { constant: true, - inputs: [], - name: 'EIP712_EXCHANGE_DOMAIN_HASH', + 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: 'makerFeeAssetData', + type: 'bytes', + }, + { + name: 'takerFeeAssetData', + type: 'bytes', + }, + ], + }, + { + name: 'signature', + type: 'bytes', + }, + ], + name: 'isValidOrderSignature', outputs: [ { - name: '', - type: 'bytes32', + name: 'isValid', + type: 'bool', }, ], payable: false, @@ -8276,18 +1964,40 @@ export class ExchangeContract extends BaseContract { constant: true, inputs: [ { - name: 'index_0', - type: 'address', + name: 'transaction', + type: 'tuple', + components: [ + { + name: 'salt', + type: 'uint256', + }, + { + name: 'expirationTimeSeconds', + type: 'uint256', + }, + { + name: 'gasPrice', + type: 'uint256', + }, + { + name: 'signerAddress', + type: 'address', + }, + { + name: 'data', + type: 'bytes', + }, + ], }, { - name: 'index_1', - type: 'address', + name: 'signature', + type: 'bytes', }, ], - name: 'allowedValidators', + name: 'isValidTransactionSignature', outputs: [ { - name: '', + name: 'isValid', type: 'bool', }, ], @@ -8360,53 +2070,43 @@ export class ExchangeContract extends BaseContract { }, ], }, + { + name: 'makerAssetFillAmount', + type: 'uint256', + }, + { + name: 'signatures', + type: 'bytes[]', + }, ], - name: 'batchCancelOrders', - outputs: [], - payable: true, - stateMutability: 'payable', - type: 'function', - }, - { - constant: false, - inputs: [ + name: 'marketBuyOrdersFillOrKill', + outputs: [ { - name: 'transactions', - type: 'tuple[]', + name: 'fillResults', + type: 'tuple', components: [ { - name: 'salt', + name: 'makerAssetFilledAmount', type: 'uint256', }, { - name: 'expirationTimeSeconds', + name: 'takerAssetFilledAmount', type: 'uint256', }, { - name: 'gasPrice', + name: 'makerFeePaid', type: 'uint256', }, { - name: 'signerAddress', - type: 'address', + name: 'takerFeePaid', + type: 'uint256', }, { - name: 'data', - type: 'bytes', + name: 'protocolFeePaid', + type: 'uint256', }, ], }, - { - name: 'signatures', - type: 'bytes[]', - }, - ], - name: 'batchExecuteTransactions', - outputs: [ - { - name: '', - type: 'bytes[]', - }, ], payable: true, stateMutability: 'payable', @@ -8478,19 +2178,19 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'takerAssetFillAmounts', - type: 'uint256[]', + name: 'makerAssetFillAmount', + type: 'uint256', }, { name: 'signatures', type: 'bytes[]', }, ], - name: 'batchFillOrKillOrders', + name: 'marketBuyOrdersNoThrow', outputs: [ { name: 'fillResults', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -8585,19 +2285,19 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'takerAssetFillAmounts', - type: 'uint256[]', + name: 'takerAssetFillAmount', + type: 'uint256', }, { name: 'signatures', type: 'bytes[]', }, ], - name: 'batchFillOrders', + name: 'marketSellOrdersFillOrKill', outputs: [ { name: 'fillResults', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -8692,19 +2392,19 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'takerAssetFillAmounts', - type: 'uint256[]', + name: 'takerAssetFillAmount', + type: 'uint256', }, { name: 'signatures', type: 'bytes[]', }, ], - name: 'batchFillOrdersNoThrow', + name: 'marketSellOrdersNoThrow', outputs: [ { name: 'fillResults', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -8737,8 +2437,8 @@ export class ExchangeContract extends BaseContract { constant: false, inputs: [ { - name: 'leftOrders', - type: 'tuple[]', + name: 'leftOrder', + type: 'tuple', components: [ { name: 'makerAddress', @@ -8799,8 +2499,8 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'rightOrders', - type: 'tuple[]', + name: 'rightOrder', + type: 'tuple', components: [ { name: 'makerAddress', @@ -8861,23 +2561,23 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'leftSignatures', - type: 'bytes[]', + name: 'leftSignature', + type: 'bytes', }, { - name: 'rightSignatures', - type: 'bytes[]', + name: 'rightSignature', + type: 'bytes', }, ], - name: 'batchMatchOrders', + name: 'matchOrders', outputs: [ { - name: 'batchMatchedFillResults', + name: 'matchedFillResults', type: 'tuple', components: [ { name: 'left', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -8903,7 +2603,7 @@ export class ExchangeContract extends BaseContract { }, { name: 'right', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -8946,8 +2646,8 @@ export class ExchangeContract extends BaseContract { constant: false, inputs: [ { - name: 'leftOrders', - type: 'tuple[]', + name: 'leftOrder', + type: 'tuple', components: [ { name: 'makerAddress', @@ -9008,8 +2708,8 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'rightOrders', - type: 'tuple[]', + name: 'rightOrder', + type: 'tuple', components: [ { name: 'makerAddress', @@ -9070,23 +2770,23 @@ export class ExchangeContract extends BaseContract { ], }, { - name: 'leftSignatures', - type: 'bytes[]', + name: 'leftSignature', + type: 'bytes', }, { - name: 'rightSignatures', - type: 'bytes[]', + name: 'rightSignature', + type: 'bytes', }, ], - name: 'batchMatchOrdersWithMaximalFill', + name: 'matchOrdersWithMaximalFill', outputs: [ { - name: 'batchMatchedFillResults', + name: 'matchedFillResults', type: 'tuple', components: [ { name: 'left', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -9112,7 +2812,7 @@ export class ExchangeContract extends BaseContract { }, { name: 'right', - type: 'tuple[]', + type: 'tuple', components: [ { name: 'makerAssetFilledAmount', @@ -9147,77 +2847,167 @@ export class ExchangeContract extends BaseContract { ], }, ], - payable: true, - stateMutability: 'payable', + payable: true, + stateMutability: 'payable', + 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: 'owner', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'hash', + type: 'bytes32', + }, + ], + name: 'preSign', + outputs: [], + payable: true, + stateMutability: 'payable', + 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: 'protocolFeeCollector', + outputs: [ + { + name: '', + type: 'address', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: true, + inputs: [], + name: 'protocolFeeMultiplier', + outputs: [ + { + name: '', + type: 'uint256', + }, + ], + payable: false, + stateMutability: 'view', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'assetProxy', + type: 'address', + }, + ], + name: 'registerAssetProxy', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'updatedProtocolFeeCollector', + type: 'address', + }, + ], + name: 'setProtocolFeeCollectorAddress', + outputs: [], + payable: false, + stateMutability: 'nonpayable', + type: 'function', + }, + { + constant: false, + inputs: [ + { + name: 'updatedProtocolFeeMultiplier', + type: 'uint256', + }, + ], + name: 'setProtocolFeeMultiplier', + outputs: [], + 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + name: 'validatorAddress', + type: 'address', + }, + { + name: 'approval', + type: 'bool', }, ], - name: 'cancelOrder', + name: 'setSignatureValidatorApproval', outputs: [], payable: true, stateMutability: 'payable', @@ -9227,14 +3017,26 @@ export class ExchangeContract extends BaseContract { constant: false, inputs: [ { - name: 'targetOrderEpoch', - type: 'uint256', + name: 'assetData', + type: 'bytes[]', + }, + { + name: 'fromAddresses', + type: 'address[]', + }, + { + name: 'toAddresses', + type: 'address[]', + }, + { + name: 'amounts', + type: 'uint256[]', }, ], - name: 'cancelOrdersUpTo', + name: 'simulateDispatchTransferFromCalls', outputs: [], - payable: true, - stateMutability: 'payable', + payable: false, + stateMutability: 'nonpayable', type: 'function', }, { @@ -9245,1642 +3047,4955 @@ export class ExchangeContract extends BaseContract { type: 'bytes32', }, ], - name: 'cancelled', + name: 'transactionsExecuted', outputs: [ { - name: '', - type: 'bool', + 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', + }, + ] as ContractAbi; + return abi; + } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = ExchangeContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ExchangeContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + public EIP1271_MAGIC_VALUE(): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + 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 encodedData = self._strictEncodeArguments('EIP1271_MAGIC_VALUE()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP1271_MAGIC_VALUE()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('EIP1271_MAGIC_VALUE()', []); + return abiEncodedTransactionData; + }, + }; + } + public EIP712_EXCHANGE_DOMAIN_HASH(): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + 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 encodedData = self._strictEncodeArguments('EIP712_EXCHANGE_DOMAIN_HASH()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('EIP712_EXCHANGE_DOMAIN_HASH()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('EIP712_EXCHANGE_DOMAIN_HASH()', []); + return abiEncodedTransactionData; + }, + }; + } + public allowedValidators(index_0: string, index_1: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + + return { + 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 encodedData = self._strictEncodeArguments('allowedValidators(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowedValidators(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('allowedValidators(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes multiple calls of cancelOrder. + * @param orders Array of order specifications. + */ + public batchCancelOrders( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + ): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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; + }, + 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 encodedData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[])', + [orders], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchCancelOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[])', + [orders], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes a batch of Exchange method calls in the context of signer(s). + * @param transactions Array of 0x transaction structures. + * @param signatures Array of proofs that transactions have been signed by + * signer(s). + * @returns Array containing ABI encoded return data for each of the underlying Exchange function calls. + */ + public batchExecuteTransactions( + transactions: Array<{ + salt: BigNumber; + expirationTimeSeconds: BigNumber; + gasPrice: BigNumber; + signerAddress: string; + data: string; + }>, + signatures: string[], + ): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isArray('transactions', transactions); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', + [transactions, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', + [transactions, 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; + }, + 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 encodedData = self._strictEncodeArguments( + 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', + [transactions, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchExecuteTransactions((uint256,uint256,uint256,address,bytes)[],bytes[])', + [transactions, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes multiple calls of fillOrKillOrder. + * @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 Array of amounts filled and fees paid by makers and taker. + */ + public batchFillOrKillOrders( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + ): ContractTxFunctionObj< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + > { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: true, - inputs: [], - name: 'currentContextAddress', - outputs: [ - { - name: '', - type: 'address', - }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); }, - { - constant: false, - inputs: [ - { - name: 'transaction', - type: 'tuple', - components: [ - { - name: 'salt', - type: 'uint256', - }, - { - name: 'expirationTimeSeconds', - type: 'uint256', - }, - { - name: 'gasPrice', - type: 'uint256', - }, - { - name: 'signerAddress', - type: 'address', - }, - { - name: 'data', - type: 'bytes', - }, - ], - }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signature', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'executeTransaction', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'bytes', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchFillOrKillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes multiple calls of fillOrder. + * @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 Array of amounts filled and fees paid by makers and taker. + */ + public batchFillOrders( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + ): ContractTxFunctionObj< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + > { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'takerAssetFillAmount', - type: 'uint256', + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signature', - type: 'bytes', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'fillOrKillOrder', - outputs: [ - { - name: 'fillResults', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchFillOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored. + * @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 Array of amounts filled and fees paid by makers and taker. + */ + public batchFillOrdersNoThrow( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + takerAssetFillAmounts: BigNumber[], + signatures: string[], + ): ContractTxFunctionObj< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + > { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isArray('takerAssetFillAmounts', takerAssetFillAmounts); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: false, - inputs: [ + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'takerAssetFillAmount', - type: 'uint256', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchFillOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256[],bytes[])', + [orders, takerAssetFillAmounts, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Match complementary orders that have a profitable spread. + * Each order is filled at their respective price point, and + * the matcher receives a profit denominated in the left maker asset. + * @param leftOrders Set of orders with the same maker / taker asset. + * @param rightOrders Set of orders to match against `leftOrders` + * @param leftSignatures Proof that left orders were created by the left + * makers. + * @param rightSignatures Proof that right orders were created by the right + * makers. + * @returns batchMatchedFillResults Amounts filled and profit generated. + */ + public batchMatchOrders( + leftOrders: 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + rightOrders: 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + leftSignatures: string[], + rightSignatures: string[], + ): ContractTxFunctionObj<{ + left: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + right: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + assert.isArray('leftOrders', leftOrders); + assert.isArray('rightOrders', rightOrders); + assert.isArray('leftSignatures', leftSignatures); + assert.isArray('rightSignatures', rightSignatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signature', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'fillOrder', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'fillResults', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: true, - inputs: [ + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + left: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + right: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'index_0', - type: 'bytes32', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'filled', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + left: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + right: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchMatchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Match complementary orders that have a profitable spread. + * Each order is maximally filled at their respective price point, and + * the matcher receives a profit denominated in either the left maker asset, + * right maker asset, or a combination of both. + * @param leftOrders Set of orders with the same maker / taker asset. + * @param rightOrders Set of orders to match against `leftOrders` + * @param leftSignatures Proof that left orders were created by the left + * makers. + * @param rightSignatures Proof that right orders were created by the right + * makers. + * @returns batchMatchedFillResults Amounts filled and profit generated. + */ + public batchMatchOrdersWithMaximalFill( + leftOrders: 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + rightOrders: 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + leftSignatures: string[], + rightSignatures: string[], + ): ContractTxFunctionObj<{ + left: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + right: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + assert.isArray('leftOrders', leftOrders); + assert.isArray('rightOrders', rightOrders); + assert.isArray('leftSignatures', leftSignatures); + assert.isArray('rightSignatures', rightSignatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'uint256', + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: true, - inputs: [ - { - name: 'assetProxyId', - type: 'bytes4', - }, - ], - name: 'getAssetProxy', - outputs: [ - { - name: '', - type: 'address', - }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); }, - { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], - }, - ], - name: 'getOrderInfo', - outputs: [ + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'orderInfo', - type: 'tuple', - components: [ - { - name: 'orderStatus', - type: 'uint8', - }, - { - name: 'orderHash', - type: 'bytes32', - }, - { - name: 'orderTakerAssetFilledAmount', - type: 'uint256', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: true, - inputs: [ + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + left: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + right: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'hash', - type: 'bytes32', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + left: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + right: Array<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'batchMatchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],bytes[])', + [leftOrders, rightOrders, leftSignatures, rightSignatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * After calling, the order can not be filled anymore. + * @param order Order struct containing order specifications. + */ + public cancelOrder(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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + [order], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signerAddress', - type: 'address', + to: self.address, + ...txData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + [order], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signature', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'isValidHashSignature', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + 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 encodedData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + [order], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'isValid', - type: 'bool', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'cancelOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + [order], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * 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 Orders created with a salt less or equal to this + * value will be cancelled. + */ + public cancelOrdersUpTo(targetOrderEpoch: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isBigNumber('targetOrderEpoch', targetOrderEpoch); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [targetOrderEpoch]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signature', - type: 'bytes', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'isValidOrderSignature', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cancelOrdersUpTo(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('cancelOrdersUpTo(uint256)', [ + targetOrderEpoch, + ]); + return abiEncodedTransactionData; + }, + }; + } + public cancelled(index_0: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('cancelled(bytes32)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'isValid', - type: 'bool', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cancelled(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: true, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('cancelled(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + public currentContextAddress(): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + 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 encodedData = self._strictEncodeArguments('currentContextAddress()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'transaction', - type: 'tuple', - components: [ - { - name: 'salt', - type: 'uint256', - }, - { - name: 'expirationTimeSeconds', - type: 'uint256', - }, - { - name: 'gasPrice', - type: 'uint256', - }, - { - name: 'signerAddress', - type: 'address', - }, - { - name: 'data', - type: 'bytes', - }, - ], + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('currentContextAddress()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('currentContextAddress()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes an Exchange method call in the context of signer. + * @param transaction 0x transaction structure. + * @param signature Proof that transaction has been signed by signer. + * @returns ABI encoded return data of the underlying Exchange function call. + */ + public executeTransaction( + transaction: { + salt: BigNumber; + expirationTimeSeconds: BigNumber; + gasPrice: BigNumber; + signerAddress: string; + data: string; + }, + signature: string, + ): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + + assert.isString('signature', signature); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', + [transaction, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signature', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'isValidTransactionSignature', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', + [transaction, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'isValid', - type: 'bool', + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: false, - inputs: [ + 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 encodedData = self._strictEncodeArguments( + 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', + [transaction, signature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'executeTransaction((uint256,uint256,uint256,address,bytes),bytes)', + [transaction, signature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Fills the input order. Reverts if exact takerAssetFillAmount not filled. + * @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. + */ + public fillOrKillOrder( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + ): ContractTxFunctionObj<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'makerAssetFillAmount', - type: 'uint256', + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signatures', - type: 'bytes[]', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'marketBuyOrdersFillOrKill', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'fillOrKillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Fills the input order. + * @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. + */ + public fillOrder( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + takerAssetFillAmount: BigNumber, + signature: string, + ): ContractTxFunctionObj<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isString('signature', signature); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'fillResults', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: false, - inputs: [ + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'makerAssetFillAmount', - type: 'uint256', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'fillOrder((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),uint256,bytes)', + [order, takerAssetFillAmount, signature], + ); + return abiEncodedTransactionData; + }, + }; + } + public filled(index_0: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('filled(bytes32)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signatures', - type: 'bytes[]', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'marketBuyOrdersNoThrow', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('filled(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('filled(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets an asset proxy. + * @param assetProxyId Id of the asset proxy. + * @returns The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered. + */ + public getAssetProxy(assetProxyId: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('assetProxyId', assetProxyId); + + return { + 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 encodedData = self._strictEncodeArguments('getAssetProxy(bytes4)', [assetProxyId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'fillResults', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAssetProxy(bytes4)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getAssetProxy(bytes4)', [assetProxyId]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets information about an order: status, hash, and amount filled. + * @param order Order to gather information on. + * @returns OrderInfo Information about the order and its state. See LibOrder.OrderInfo for a complete description. + */ + public getOrderInfo(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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }): ContractFunctionObj<{ orderStatus: number; orderHash: string; orderTakerAssetFilledAmount: BigNumber }> { + const self = (this as any) as ExchangeContract; + + return { + async callAsync( + 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 encodedData = self._strictEncodeArguments( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + [order], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + orderStatus: number; + orderHash: string; + orderTakerAssetFilledAmount: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes))', + [order], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Verifies that a hash has been signed by the given signer. + * @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 isValid `true` if the signature is valid for the given hash and signer. + */ + public isValidHashSignature(hash: string, signerAddress: string, signature: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + + return { + 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 encodedData = self._strictEncodeArguments('isValidHashSignature(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'takerAssetFillAmount', - type: 'uint256', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isValidHashSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'isValidHashSignature(bytes32,address,bytes)', + [hash, signerAddress.toLowerCase(), signature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Verifies that a signature for an order is valid. + * @param order The order. + * @param signature Proof that the order has been signed by signer. + * @returns isValid `true` if the signature is valid for the given order and signer. + */ + public isValidOrderSignature( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + signature: string, + ): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + assert.isString('signature', signature); + + return { + 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 encodedData = self._strictEncodeArguments( + 'isValidOrderSignature((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', + [order, signature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signatures', - type: 'bytes[]', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'marketSellOrdersFillOrKill', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'isValidOrderSignature((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'isValidOrderSignature((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes)', + [order, signature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Verifies that a signature for a transaction is valid. + * @param transaction The transaction. + * @param signature Proof that the order has been signed by signer. + * @returns isValid `true` if the signature is valid for the given transaction and signer. + */ + public isValidTransactionSignature( + transaction: { + salt: BigNumber; + expirationTimeSeconds: BigNumber; + gasPrice: BigNumber; + signerAddress: string; + data: string; + }, + signature: string, + ): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + assert.isString('signature', signature); + + return { + 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 encodedData = self._strictEncodeArguments( + 'isValidTransactionSignature((uint256,uint256,uint256,address,bytes),bytes)', + [transaction, signature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'fillResults', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'isValidTransactionSignature((uint256,uint256,uint256,address,bytes),bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'isValidTransactionSignature((uint256,uint256,uint256,address,bytes),bytes)', + [transaction, signature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought. + * NOTE: This function does not enforce that the makerAsset is the same for each order. + * @param orders Array of order specifications. + * @param makerAssetFillAmount Minimum 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. + */ + public marketBuyOrdersFillOrKill( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + ): ContractTxFunctionObj<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'takerAssetFillAmount', - type: 'uint256', + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'signatures', - type: 'bytes[]', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'marketSellOrdersNoThrow', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketBuyOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker. + * If any fill reverts, the error is caught and ignored. + * NOTE: This function does not enforce that the makerAsset is the same for each order. + * @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. + */ + public marketBuyOrdersNoThrow( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + makerAssetFillAmount: BigNumber, + signatures: string[], + ): ContractTxFunctionObj<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetFillAmount', makerAssetFillAmount); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'fillResults', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: false, - inputs: [ + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketBuyOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, makerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold. + * NOTE: This function does not enforce that the takerAsset is the same for each order. + * @param orders Array of order specifications. + * @param takerAssetFillAmount Minimum 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. + */ + public marketSellOrdersFillOrKill( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + ): ContractTxFunctionObj<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'leftSignature', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'rightSignature', - type: 'bytes', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'matchOrders', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'protocolFeePaid', - type: 'uint256', - }, - ], - }, - { - name: 'right', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], - }, - { - name: 'profitInLeftMakerAsset', - type: 'uint256', - }, - { - name: 'profitInRightMakerAsset', - type: 'uint256', - }, - ], + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketSellOrdersFillOrKill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker. + * If any fill reverts, the error is caught and ignored. + * NOTE: This function does not enforce that the takerAsset is the same for each order. + * @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. + */ + public marketSellOrdersNoThrow( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + takerAssetFillAmount: BigNumber, + signatures: string[], + ): ContractTxFunctionObj<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + assert.isArray('orders', orders); + assert.isBigNumber('takerAssetFillAmount', takerAssetFillAmount); + assert.isArray('signatures', signatures); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: false, - inputs: [ + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'makerFeeAssetData', - type: 'bytes', - }, - { - name: 'takerFeeAssetData', - type: 'bytes', - }, - ], + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketSellOrdersNoThrow((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[])', + [orders, takerAssetFillAmount, signatures], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * 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). + * @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. + */ + public matchOrders( + 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; + makerFeeAssetData: string; + takerFeeAssetData: 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + leftSignature: string, + rightSignature: string, + ): ContractTxFunctionObj<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'leftSignature', - type: 'bytes', + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'rightSignature', - type: 'bytes', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'matchOrdersWithMaximalFill', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'matchOrders((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Match two complementary orders that have a profitable spread. + * Each order is maximally filled at their respective price point, and + * the matcher receives a profit denominated in either the left maker asset, + * right maker asset, or a combination of both. + * @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 by maker and taker of matched orders. + */ + public matchOrdersWithMaximalFill( + 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; + makerFeeAssetData: string; + takerFeeAssetData: 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }, + leftSignature: string, + rightSignature: string, + ): ContractTxFunctionObj<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + const self = (this as any) as ExchangeContract; + + assert.isString('leftSignature', leftSignature); + assert.isString('rightSignature', rightSignature); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - 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: 'protocolFeePaid', - type: 'uint256', - }, - ], - }, - { - name: 'right', - type: 'tuple', - components: [ - { - name: 'makerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'takerAssetFilledAmount', - type: 'uint256', - }, - { - name: 'makerFeePaid', - type: 'uint256', - }, - { - name: 'takerFeePaid', - type: 'uint256', - }, - { - name: 'protocolFeePaid', - type: 'uint256', - }, - ], - }, - { - name: 'profitInLeftMakerAsset', - type: 'uint256', - }, - { - name: 'profitInRightMakerAsset', - type: 'uint256', - }, - ], + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; }, - { - constant: true, - inputs: [ + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'index_0', - type: 'address', + 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'index_1', - type: 'address', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'orderEpoch', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + left: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + right: { + makerAssetFilledAmount: BigNumber; + takerAssetFilledAmount: BigNumber; + makerFeePaid: BigNumber; + takerFeePaid: BigNumber; + protocolFeePaid: BigNumber; + }; + profitInLeftMakerAsset: BigNumber; + profitInRightMakerAsset: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'matchOrdersWithMaximalFill((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),(address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes),bytes,bytes)', + [leftOrder, rightOrder, leftSignature, rightSignature], + ); + return abiEncodedTransactionData; + }, + }; + } + public orderEpoch(index_0: string, index_1: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + + return { + 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 encodedData = self._strictEncodeArguments('orderEpoch(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'uint256', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('orderEpoch(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: true, - inputs: [], - name: 'owner', - outputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('orderEpoch(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public owner(): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + 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 encodedData = self._strictEncodeArguments('owner()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'address', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Approves a hash on-chain. + * After presigning a hash, the preSign signature type will become valid for that hash and signer. + * @param hash Any 32-byte hash. + */ + public preSign(hash: string): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('hash', hash); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('preSign(bytes32)', [hash]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('preSign(bytes32)', [hash]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'hash', - type: 'bytes32', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'preSign', - outputs: [], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: true, - inputs: [ + 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 encodedData = self._strictEncodeArguments('preSign(bytes32)', [hash]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'index_0', - type: 'bytes32', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('preSign(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('preSign(bytes32)', [hash]); + return abiEncodedTransactionData; + }, + }; + } + public preSigned(index_0: string, index_1: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + + return { + 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 encodedData = self._strictEncodeArguments('preSigned(bytes32,address)', [ + index_0, + index_1.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'index_1', - type: 'address', - }, - ], - name: 'preSigned', - outputs: [ + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('preSigned(bytes32,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('preSigned(bytes32,address)', [ + index_0, + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public protocolFeeCollector(): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + 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 encodedData = self._strictEncodeArguments('protocolFeeCollector()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'bool', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('protocolFeeCollector()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: true, - inputs: [], - name: 'protocolFeeCollector', - outputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('protocolFeeCollector()', []); + return abiEncodedTransactionData; + }, + }; + } + public protocolFeeMultiplier(): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + + return { + 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 encodedData = self._strictEncodeArguments('protocolFeeMultiplier()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'address', + to: self.address, + ...callData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('protocolFeeMultiplier()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: true, - inputs: [], - name: 'protocolFeeMultiplier', - outputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('protocolFeeMultiplier()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Registers an asset proxy to its asset proxy id. + * Once an asset proxy is registered, it cannot be unregistered. + * @param assetProxy Address of new asset proxy to register. + */ + public registerAssetProxy(assetProxy: string): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('assetProxy', assetProxy); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [ + assetProxy.toLowerCase(), + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'uint256', + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: false, - inputs: [ + 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 encodedData = self._strictEncodeArguments('registerAssetProxy(address)', [ + assetProxy.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'assetProxy', - type: 'address', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'registerAssetProxy', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('registerAssetProxy(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('registerAssetProxy(address)', [ + assetProxy.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Allows the owner to update the protocolFeeCollector address. + * @param updatedProtocolFeeCollector The updated protocolFeeCollector contract + * address. + */ + public setProtocolFeeCollectorAddress(updatedProtocolFeeCollector: string): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('updatedProtocolFeeCollector', updatedProtocolFeeCollector); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('setProtocolFeeCollectorAddress(address)', [ + updatedProtocolFeeCollector.toLowerCase(), + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('setProtocolFeeCollectorAddress(address)', [ + updatedProtocolFeeCollector.toLowerCase(), + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'updatedProtocolFeeCollector', - type: 'address', + to: self.address, + ...txData, + data: encodedData, }, - ], - name: 'setProtocolFeeCollectorAddress', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: false, - inputs: [ + 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 encodedData = self._strictEncodeArguments('setProtocolFeeCollectorAddress(address)', [ + updatedProtocolFeeCollector.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'updatedProtocolFeeMultiplier', - type: 'uint256', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'setProtocolFeeMultiplier', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setProtocolFeeCollectorAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'setProtocolFeeCollectorAddress(address)', + [updatedProtocolFeeCollector.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Allows the owner to update the protocol fee multiplier. + * @param updatedProtocolFeeMultiplier The updated protocol fee multiplier. + */ + public setProtocolFeeMultiplier(updatedProtocolFeeMultiplier: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isBigNumber('updatedProtocolFeeMultiplier', updatedProtocolFeeMultiplier); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ + updatedProtocolFeeMultiplier, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ + updatedProtocolFeeMultiplier, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'validatorAddress', - type: 'address', + 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; + }, + 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 encodedData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ + updatedProtocolFeeMultiplier, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'approval', - type: 'bool', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'setSignatureValidatorApproval', - outputs: [], - payable: true, - stateMutability: 'payable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setProtocolFeeMultiplier(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: false, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('setProtocolFeeMultiplier(uint256)', [ + updatedProtocolFeeMultiplier, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Approves/unnapproves a Validator contract to verify signatures on signer's behalf + * using the `Validator` signature type. + * @param validatorAddress Address of Validator contract. + * @param approval Approval or disapproval of Validator contract. + */ + public setSignatureValidatorApproval(validatorAddress: string, approval: boolean): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('validatorAddress', validatorAddress); + assert.isBoolean('approval', approval); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('setSignatureValidatorApproval(address,bool)', [ + validatorAddress.toLowerCase(), + approval, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'assetData', - type: 'bytes[]', + to: self.address, + ...callData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setSignatureValidatorApproval(address,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'setSignatureValidatorApproval(address,bool)', + [validatorAddress.toLowerCase(), approval], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * This function may be used to simulate any amount of transfers As they would occur through the Exchange contract. Note that this function will always revert, even if all transfers are successful. However, it may be used with eth_call or with a try/catch pattern in order to simulate the results of the transfers. + * @param assetData Array of asset details, each encoded per the AssetProxy + * contract specification. + * @param fromAddresses Array containing the `from` addresses that correspond + * with each transfer. + * @param toAddresses Array containing the `to` addresses that correspond with + * each transfer. + * @param amounts Array containing the amounts that correspond to each + * transfer. + * @returns This function does not return a value. However, it will always revert with `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful. + */ + public simulateDispatchTransferFromCalls( + assetData: string[], + fromAddresses: string[], + toAddresses: string[], + amounts: BigNumber[], + ): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isArray('assetData', assetData); + assert.isArray('fromAddresses', fromAddresses); + assert.isArray('toAddresses', toAddresses); + assert.isArray('amounts', amounts); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', + [assetData, fromAddresses, toAddresses, amounts], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'fromAddresses', - type: 'address[]', + to: self.address, + ...txData, + data: encodedData, }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', + [assetData, fromAddresses, toAddresses, amounts], + ); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'toAddresses', - type: 'address[]', + 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; + }, + 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 encodedData = self._strictEncodeArguments( + 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', + [assetData, fromAddresses, toAddresses, amounts], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'amounts', - type: 'uint256[]', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'simulateDispatchTransferFromCalls', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - { - constant: true, - inputs: [ + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'simulateDispatchTransferFromCalls(bytes[],address[],address[],uint256[])', + [assetData, fromAddresses, toAddresses, amounts], + ); + return abiEncodedTransactionData; + }, + }; + } + public transactionsExecuted(index_0: string): ContractFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('transactionsExecuted(bytes32)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'index_0', - type: 'bytes32', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'transactionsExecuted', - outputs: [ + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transactionsExecuted(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transactionsExecuted(bytes32)', [ + index_0, + ]); + return abiEncodedTransactionData; + }, + }; + } + public transferOwnership(newOwner: string): ContractTxFunctionObj { + const self = (this as any) as ExchangeContract; + assert.isString('newOwner', newOwner); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: '', - type: 'bool', + to: self.address, + ...txData, + data: encodedData, }, - ], - payable: false, - stateMutability: 'view', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + const gas = await self._web3Wrapper.estimateGasAsync(txDataWithDefaults); + return gas; }, - { - constant: false, - inputs: [ + 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 encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { - name: 'newOwner', - type: 'address', + to: self.address, + ...callData, + data: encodedData, }, - ], - name: 'transferOwnership', - outputs: [], - payable: false, - stateMutability: 'nonpayable', - type: 'function', + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; }, - ] as ContractAbi; - return abi; + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; } + /** * Subscribe to an event type emitted by the Exchange contract. * @param eventName The Exchange contract event you would like to subscribe to. @@ -10970,6 +8085,12 @@ export class ExchangeContract extends BaseContract { ExchangeContract.ABI(), this._web3Wrapper, ); + ExchangeContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts b/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts index fd921962fc..9de6c3f8f2 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/forwarder.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -38,1212 +40,7 @@ export class ForwarderContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * Approves the respective proxy for a given asset to transfer tokens on the Forwarder contract's behalf. - * This is necessary because an order fee denominated in the maker asset (i.e. a percentage fee) is sent by the - * Forwarder contract to the fee recipient. - * This method needs to be called before forwarding orders of a maker asset that hasn't - * previously been approved. - */ - public approveMakerAssetProxy = { - /** - * 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 txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - assetData: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('assetData', assetData); - const self = (this as any) as ForwarderContract; - const encodedData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.approveMakerAssetProxy.callAsync(assetData, txDataWithDefaults); - } - - 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 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, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('assetData', assetData); - const self = (this as any) as ForwarderContract; - const txHashPromise = self.approveMakerAssetProxy.sendTransactionAsync(assetData, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(assetData: string, txData?: Partial | undefined): Promise { - assert.isString('assetData', assetData); - const self = (this as any) as ForwarderContract; - const encodedData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); - 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. - */ - async callAsync(assetData: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - 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 ForwarderContract; - const encodedData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('approveMakerAssetProxy(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 assetData Byte array encoded for the respective asset proxy. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(assetData: string): string { - assert.isString('assetData', assetData); - const self = (this as any) as ForwarderContract; - const abiEncodedTransactionData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ForwarderContract; - const abiEncoder = self._lookupAbiEncoder('approveMakerAssetProxy(bytes)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Attempt to buy makerAssetBuyAmount of makerAsset by selling ETH provided with transaction. - * The Forwarder may *fill* more than makerAssetBuyAmount of the makerAsset so that it can - * pay takerFees where takerFeeAssetData == makerAssetData (i.e. percentage fees). - * 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 makerAssetBuyAmount Desired amount of makerAsset to purchase. - * @param signatures Proofs that orders 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetBuyAmount: BigNumber, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); - assert.isArray('signatures', signatures); - 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,bytes,bytes)[],uint256,bytes[],uint256,address)', - [orders, makerAssetBuyAmount, signatures, 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(); - } - - if (opts.shouldValidate !== false) { - await self.marketBuyOrdersWithEth.callAsync( - orders, - makerAssetBuyAmount, - signatures, - feePercentage, - feeRecipient, - txDataWithDefaults, - ); - } - - 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 makerAssetBuyAmount Desired amount of makerAsset to purchase. - * @param signatures Proofs that orders 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetBuyAmount: BigNumber, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); - assert.isArray('signatures', signatures); - assert.isBigNumber('feePercentage', feePercentage); - assert.isString('feeRecipient', feeRecipient); - const self = (this as any) as ForwarderContract; - const txHashPromise = self.marketBuyOrdersWithEth.sendTransactionAsync( - orders, - makerAssetBuyAmount, - signatures, - feePercentage, - feeRecipient.toLowerCase(), - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 makerAssetBuyAmount Desired amount of makerAsset to purchase. - * @param signatures Proofs that orders 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetBuyAmount: BigNumber, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - txData?: Partial | undefined, - ): Promise { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); - assert.isArray('signatures', signatures); - 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,bytes,bytes)[],uint256,bytes[],uint256,address)', - [orders, makerAssetBuyAmount, signatures, 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 makerAssetBuyAmount Desired amount of makerAsset to purchase. - * @param signatures Proofs that orders 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 wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders.ethFeePaid Amount of ETH spent on the given forwarder fee. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetBuyAmount: BigNumber, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber, BigNumber, BigNumber]> { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); - assert.isArray('signatures', signatures); - 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,bytes,bytes)[],uint256,bytes[],uint256,address)', - [orders, makerAssetBuyAmount, signatures, 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, 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). - * @param orders Array of order specifications used containing desired - * makerAsset and WETH as takerAsset. - * @param makerAssetBuyAmount Desired amount of makerAsset to purchase. - * @param signatures Proofs that orders 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 The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - makerAssetBuyAmount: BigNumber, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - ): string { - assert.isArray('orders', orders); - assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); - assert.isArray('signatures', signatures); - 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,bytes,bytes)[],uint256,bytes[],uint256,address)', - [orders, makerAssetBuyAmount, signatures, feePercentage, feeRecipient.toLowerCase()], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ForwarderContract; - const abiEncoder = self._lookupAbiEncoder( - 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', - ); - return abiEncoder.getSelector(); - }, - }; - /** - * Purchases as much of orders' makerAssets as possible by selling as much of the ETH value sent - * as possible, accounting for order and forwarder fees. - */ - 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 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('orders', orders); - assert.isArray('signatures', signatures); - 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,bytes)[],bytes[],uint256,address)', - [orders, signatures, 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(); - } - - if (opts.shouldValidate !== false) { - await self.marketSellOrdersWithEth.callAsync( - orders, - signatures, - feePercentage, - feeRecipient, - txDataWithDefaults, - ); - } - - 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 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('orders', orders); - assert.isArray('signatures', signatures); - assert.isBigNumber('feePercentage', feePercentage); - assert.isString('feeRecipient', feeRecipient); - const self = (this as any) as ForwarderContract; - const txHashPromise = self.marketSellOrdersWithEth.sendTransactionAsync( - orders, - signatures, - feePercentage, - feeRecipient.toLowerCase(), - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - txData?: Partial | undefined, - ): Promise { - assert.isArray('orders', orders); - assert.isArray('signatures', signatures); - 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,bytes)[],bytes[],uint256,address)', - [orders, signatures, 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 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 wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders.ethFeePaid Amount of ETH spent on the given forwarder fee. - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber, BigNumber, BigNumber]> { - assert.isArray('orders', orders); - assert.isArray('signatures', signatures); - 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,bytes)[],bytes[],uint256,address)', - [orders, signatures, 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder( - 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256,address)', - ); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, 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). - * @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 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 The ABI encoded transaction data as a string - */ - 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; - makerFeeAssetData: string; - takerFeeAssetData: string; - }>, - signatures: string[], - feePercentage: BigNumber, - feeRecipient: string, - ): string { - assert.isArray('orders', orders); - assert.isArray('signatures', signatures); - 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,bytes)[],bytes[],uint256,address)', - [orders, signatures, feePercentage, feeRecipient.toLowerCase()], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - 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,bytes)[],bytes[],uint256,address)', - ); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('owner()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferOwnership.callAsync(newOwner, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('newOwner', newOwner); - const self = (this as any) as ForwarderContract; - const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ForwarderContract; - const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Withdraws assets from this contract. The contract formerly required 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.withdrawAsset.callAsync(assetData, amount, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('assetData', assetData); - assert.isBigNumber('amount', amount); - const self = (this as any) as ForwarderContract; - const txHashPromise = self.withdrawAsset.sendTransactionAsync(assetData, amount, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as ForwarderContract; - const abiEncoder = self._lookupAbiEncoder('withdrawAsset(bytes,uint256)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -1613,6 +410,742 @@ export class ForwarderContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = ForwarderContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as ForwarderContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Approves the respective proxy for a given asset to transfer tokens on the Forwarder contract's behalf. + * This is necessary because an order fee denominated in the maker asset (i.e. a percentage fee) is sent by the + * Forwarder contract to the fee recipient. + * This method needs to be called before forwarding orders of a maker asset that hasn't + * previously been approved. + * @param assetData Byte array encoded for the respective asset proxy. + */ + public approveMakerAssetProxy(assetData: string): ContractTxFunctionObj { + const self = (this as any) as ForwarderContract; + assert.isString('assetData', assetData); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [assetData]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approveMakerAssetProxy(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('approveMakerAssetProxy(bytes)', [ + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Attempt to buy makerAssetBuyAmount of makerAsset by selling ETH provided with transaction. + * The Forwarder may *fill* more than makerAssetBuyAmount of the makerAsset so that it can + * pay takerFees where takerFeeAssetData == makerAssetData (i.e. percentage fees). + * Any ETH not spent will be refunded to sender. + * @param orders Array of order specifications used containing desired + * makerAsset and WETH as takerAsset. + * @param makerAssetBuyAmount Desired amount of makerAsset to purchase. + * @param signatures Proofs that orders 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 wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders.ethFeePaid Amount of ETH spent on the given forwarder fee. + */ + public marketBuyOrdersWithEth( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + makerAssetBuyAmount: BigNumber, + signatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + ): ContractTxFunctionObj<[BigNumber, BigNumber, BigNumber]> { + const self = (this as any) as ForwarderContract; + assert.isArray('orders', orders); + assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); + assert.isArray('signatures', signatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', + [orders, makerAssetBuyAmount, signatures, 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', + [orders, makerAssetBuyAmount, signatures, 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', + [orders, makerAssetBuyAmount, signatures, feePercentage, feeRecipient.toLowerCase()], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketBuyOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],uint256,bytes[],uint256,address)', + [orders, makerAssetBuyAmount, signatures, feePercentage, feeRecipient.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Purchases as much of orders' makerAssets as possible by selling as much of the ETH value sent + * as possible, accounting for order and forwarder fees. + * @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 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 wethSpentAmount Amount of WETH spent on the given set of orders.makerAssetAcquiredAmount Amount of maker asset acquired from the given set of orders.ethFeePaid Amount of ETH spent on the given forwarder fee. + */ + public marketSellOrdersWithEth( + 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; + makerFeeAssetData: string; + takerFeeAssetData: string; + }>, + signatures: string[], + feePercentage: BigNumber, + feeRecipient: string, + ): ContractTxFunctionObj<[BigNumber, BigNumber, BigNumber]> { + const self = (this as any) as ForwarderContract; + assert.isArray('orders', orders); + assert.isArray('signatures', signatures); + assert.isBigNumber('feePercentage', feePercentage); + assert.isString('feeRecipient', feeRecipient); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, 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; + }, + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, feePercentage, feeRecipient.toLowerCase()], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256,address)', + ); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'marketSellOrdersWithEth((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes,bytes,bytes)[],bytes[],uint256,address)', + [orders, signatures, feePercentage, feeRecipient.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + }; + } + public owner(): ContractFunctionObj { + const self = (this as any) as ForwarderContract; + + return { + 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 encodedData = self._strictEncodeArguments('owner()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + }; + } + public transferOwnership(newOwner: string): ContractTxFunctionObj { + const self = (this as any) as ForwarderContract; + assert.isString('newOwner', newOwner); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Withdraws assets from this contract. The contract formerly required 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. + * @param assetData Byte array encoded for the respective asset proxy. + * @param amount Amount of ERC20 token to withdraw. + */ + public withdrawAsset(assetData: string, amount: BigNumber): ContractTxFunctionObj { + const self = (this as any) as ForwarderContract; + assert.isString('assetData', assetData); + assert.isBigNumber('amount', amount); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('withdrawAsset(bytes,uint256)', [assetData, amount]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withdrawAsset(bytes,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('withdrawAsset(bytes,uint256)', [ + assetData, + amount, + ]); + return abiEncodedTransactionData; + }, + }; + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -1630,6 +1163,12 @@ export class ForwarderContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + ForwarderContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 1f97f3f316..b629383e3b 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/i_validator.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/i_validator.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -38,69 +40,7 @@ export class IValidatorContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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 Magic bytes4 value if the signature is valid. Magic value is bytes4(keccak256("isValidValidatorSignature(address,bytes32,address,bytes)")) - */ - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -200,6 +140,99 @@ export class IValidatorContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = IValidatorContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as IValidatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as IValidatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as IValidatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Verifies that a signature is valid. + * @param hash Message hash that is signed. + * @param signerAddress Address that should have signed the given hash. + * @param signature Proof of signing. + * @returns Magic bytes4 value if the signature is valid. Magic value is bytes4(keccak256("isValidValidatorSignature(address,bytes32,address,bytes)")) + */ + public isValidSignature(hash: string, signerAddress: string, signature: string): ContractFunctionObj { + const self = (this as any) as IValidatorContract; + assert.isString('hash', hash); + assert.isString('signerAddress', signerAddress); + assert.isString('signature', signature); + + return { + 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 encodedData = self._strictEncodeArguments('isValidSignature(bytes32,address,bytes)', [ + hash, + signerAddress.toLowerCase(), + signature, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,address,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'isValidSignature(bytes32,address,bytes)', + [hash, signerAddress.toLowerCase(), signature], + ); + return abiEncodedTransactionData; + }, + }; + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -217,6 +250,12 @@ export class IValidatorContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + IValidatorContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 000d0798b6..c2515d963c 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/i_wallet.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/i_wallet.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -38,62 +40,7 @@ export class IWalletContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * Validates a hash with the `Wallet` signature type. - */ - 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 magicValue `bytes4(0xb0671381)` if the signature check succeeds. - */ - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,bytes)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -189,6 +136,93 @@ export class IWalletContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = IWalletContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as IWalletContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as IWalletContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as IWalletContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Validates a hash with the `Wallet` signature type. + * @param hash Message hash that is signed. + * @param signature Proof of signing. + * @returns magicValue `bytes4(0xb0671381)` if the signature check succeeds. + */ + public isValidSignature(hash: string, signature: string): ContractFunctionObj { + const self = (this as any) as IWalletContract; + assert.isString('hash', hash); + assert.isString('signature', signature); + + return { + 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 encodedData = self._strictEncodeArguments('isValidSignature(bytes32,bytes)', [hash, signature]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('isValidSignature(bytes32,bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('isValidSignature(bytes32,bytes)', [ + hash, + signature, + ]); + return abiEncodedTransactionData; + }, + }; + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -206,6 +240,12 @@ export class IWalletContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + IWalletContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } 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 aadf482932..0629a8c2e6 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/order_validator.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/order_validator.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -38,531 +40,7 @@ export class OrderValidatorContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getERC721TokenOwner(address,uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -1208,6 +686,657 @@ export class OrderValidatorContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = OrderValidatorContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as OrderValidatorContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + public getOrderAndTraderInfo( + 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, + ): ContractFunctionObj< + [ + { 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; + + assert.isString('takerAddress', takerAddress); + + return { + async callAsync( + 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.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrderAndTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + }; + } + public getBalanceAndAllowance(target: string, assetData: string): ContractFunctionObj<[BigNumber, BigNumber]> { + const self = (this as any) as OrderValidatorContract; + assert.isString('target', target); + assert.isString('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getBalanceAndAllowance(address,bytes)', [ + target.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getBalanceAndAllowance(address,bytes)', [ + target.toLowerCase(), + assetData, + ]); + return abiEncodedTransactionData; + }, + }; + } + public getOrdersAndTradersInfo( + 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[], + ): ContractFunctionObj< + [ + 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; + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + + return { + async callAsync( + 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.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getOrdersAndTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + return abiEncodedTransactionData; + }, + }; + } + public getTradersInfo( + 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[], + ): ContractFunctionObj< + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + > { + const self = (this as any) as OrderValidatorContract; + assert.isArray('orders', orders); + assert.isArray('takerAddresses', takerAddresses); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTradersInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes)[],address[])', + [orders, takerAddresses], + ); + return abiEncodedTransactionData; + }, + }; + } + public getERC721TokenOwner(token: string, tokenId: BigNumber): ContractFunctionObj { + const self = (this as any) as OrderValidatorContract; + assert.isString('token', token); + assert.isBigNumber('tokenId', tokenId); + + return { + 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 encodedData = self._strictEncodeArguments('getERC721TokenOwner(address,uint256)', [ + token.toLowerCase(), + tokenId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getERC721TokenOwner(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getERC721TokenOwner(address,uint256)', [ + token.toLowerCase(), + tokenId, + ]); + return abiEncodedTransactionData; + }, + }; + } + public getBalancesAndAllowances( + target: string, + assetData: string[], + ): ContractFunctionObj<[BigNumber[], BigNumber[]]> { + const self = (this as any) as OrderValidatorContract; + assert.isString('target', target); + assert.isArray('assetData', assetData); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber[], BigNumber[]]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getBalancesAndAllowances(address,bytes[])', [ + target.toLowerCase(), + assetData, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getBalancesAndAllowances(address,bytes[])', + [target.toLowerCase(), assetData], + ); + return abiEncodedTransactionData; + }, + }; + } + public getTraderInfo( + 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, + ): ContractFunctionObj<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> { + const self = (this as any) as OrderValidatorContract; + + assert.isString('takerAddress', takerAddress); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + makerBalance: BigNumber; + makerAllowance: BigNumber; + takerBalance: BigNumber; + takerAllowance: BigNumber; + makerZrxBalance: BigNumber; + makerZrxAllowance: BigNumber; + takerZrxBalance: BigNumber; + takerZrxAllowance: BigNumber; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(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; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getTraderInfo((address,address,address,address,uint256,uint256,uint256,uint256,uint256,uint256,bytes,bytes),address)', + [order, takerAddress.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + }; + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -1225,6 +1354,12 @@ export class OrderValidatorContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + OrderValidatorContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/staking.ts b/packages/abi-gen-wrappers/src/generated-wrappers/staking.ts index ae9708edef..8f844b9780 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/staking.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/staking.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -169,4830 +172,101 @@ export class StakingContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('target', target); - const self = (this as any) as StakingContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.addAuthorizedAddress.callAsync(target, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('target', target); - const self = (this as any) as StakingContract; - const txHashPromise = self.addAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingContract; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(target: string): string { - assert.isString('target', target); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ - target.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Adds a new exchange address - */ - public addExchangeAddress = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param addr Address of exchange contract to add - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - addr: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('addExchangeAddress(address)', [addr.toLowerCase()]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.addExchangeAddress.callAsync(addr, txDataWithDefaults); - } - - 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 addr Address of exchange contract to add - * @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( - addr: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const txHashPromise = self.addExchangeAddress.sendTransactionAsync(addr.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param addr Address of exchange contract to add - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(addr: string, txData?: Partial | undefined): Promise { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('addExchangeAddress(address)', [addr.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 addr Address of exchange contract to add - */ - async callAsync(addr: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('addr', addr); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('addExchangeAddress(address)', [addr.toLowerCase()]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('addExchangeAddress(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 addr Address of exchange contract to add - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(addr: string): string { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('addExchangeAddress(address)', [ - addr.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('addExchangeAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - public aggregatedStatsByEpoch = { - /** - * 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<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { - 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 StakingContract; - const encodedData = self._strictEncodeArguments('aggregatedStatsByEpoch(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('aggregatedStatsByEpoch(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]>( - rawCallResult, - ); - // tslint:enable boolean-naming - return result; - }, - }; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('authorized(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public cobbDouglasAlphaDenominator = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('cobbDouglasAlphaDenominator()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaDenominator()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public cobbDouglasAlphaNumerator = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('cobbDouglasAlphaNumerator()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaNumerator()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Computes the reward balance in ETH of a specific member of a pool. - */ - public computeRewardBalanceOfDelegator = { - /** - * 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 poolId Unique id of pool. - * @param member The member of the pool. - * @returns totalReward Balance in ETH. - */ - async callAsync( - poolId: string, - member: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('poolId', poolId); - assert.isString('member', member); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('computeRewardBalanceOfDelegator(bytes32,address)', [ - poolId, - member.toLowerCase(), - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('computeRewardBalanceOfDelegator(bytes32,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Computes the reward balance in ETH of the operator of a pool. - */ - public computeRewardBalanceOfOperator = { - /** - * 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 poolId Unique id of pool. - * @returns totalReward Balance in ETH. - */ - async callAsync( - poolId: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('computeRewardBalanceOfOperator(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('computeRewardBalanceOfOperator(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Create a new staking pool. The sender will be the operator of this pool. Note that an operator must be payable. - */ - public createStakingPool = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param operatorShare Portion of rewards owned by the operator, in ppm. - * @param addOperatorAsMaker Adds operator to the created pool as a maker for - * convenience iff true. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - operatorShare: number | BigNumber, - addOperatorAsMaker: boolean, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isNumberOrBigNumber('operatorShare', operatorShare); - assert.isBoolean('addOperatorAsMaker', addOperatorAsMaker); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ - operatorShare, - addOperatorAsMaker, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.createStakingPool.callAsync(operatorShare, addOperatorAsMaker, txDataWithDefaults); - } - - 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 operatorShare Portion of rewards owned by the operator, in ppm. - * @param addOperatorAsMaker Adds operator to the created pool as a maker for - * convenience iff true. - * @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( - operatorShare: number | BigNumber, - addOperatorAsMaker: boolean, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isNumberOrBigNumber('operatorShare', operatorShare); - assert.isBoolean('addOperatorAsMaker', addOperatorAsMaker); - const self = (this as any) as StakingContract; - const txHashPromise = self.createStakingPool.sendTransactionAsync( - operatorShare, - addOperatorAsMaker, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param operatorShare Portion of rewards owned by the operator, in ppm. - * @param addOperatorAsMaker Adds operator to the created pool as a maker for - * convenience iff true. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - operatorShare: number | BigNumber, - addOperatorAsMaker: boolean, - txData?: Partial | undefined, - ): Promise { - assert.isNumberOrBigNumber('operatorShare', operatorShare); - assert.isBoolean('addOperatorAsMaker', addOperatorAsMaker); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ - operatorShare, - addOperatorAsMaker, - ]); - 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 operatorShare Portion of rewards owned by the operator, in ppm. - * @param addOperatorAsMaker Adds operator to the created pool as a maker for - * convenience iff true. - * @returns poolId The unique pool id generated for this pool. - */ - async callAsync( - operatorShare: number | BigNumber, - addOperatorAsMaker: boolean, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isNumberOrBigNumber('operatorShare', operatorShare); - assert.isBoolean('addOperatorAsMaker', addOperatorAsMaker); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ - operatorShare, - addOperatorAsMaker, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('createStakingPool(uint32,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 operatorShare Portion of rewards owned by the operator, in ppm. - * @param addOperatorAsMaker Adds operator to the created pool as a maker for - * convenience iff true. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(operatorShare: number | BigNumber, addOperatorAsMaker: boolean): string { - assert.isNumberOrBigNumber('operatorShare', operatorShare); - assert.isBoolean('addOperatorAsMaker', addOperatorAsMaker); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ - operatorShare, - addOperatorAsMaker, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('createStakingPool(uint32,bool)'); - return abiEncoder.getSelector(); - }, - }; - public currentEpoch = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('currentEpoch()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('currentEpoch()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public currentEpochStartTimeInSeconds = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('currentEpochStartTimeInSeconds()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('currentEpochStartTimeInSeconds()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Decreases the operator share for the given pool (i.e. increases pool rewards for members). - */ - public decreaseStakingPoolOperatorShare = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param poolId Unique Id of pool. - * @param newOperatorShare The newly decreased percentage of any rewards owned - * by the operator. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - poolId: string, - newOperatorShare: number | BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('poolId', poolId); - assert.isNumberOrBigNumber('newOperatorShare', newOperatorShare); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('decreaseStakingPoolOperatorShare(bytes32,uint32)', [ - poolId, - newOperatorShare, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.decreaseStakingPoolOperatorShare.callAsync(poolId, newOperatorShare, txDataWithDefaults); - } - - 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 poolId Unique Id of pool. - * @param newOperatorShare The newly decreased percentage of any rewards owned - * by the operator. - * @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( - poolId: string, - newOperatorShare: number | BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('poolId', poolId); - assert.isNumberOrBigNumber('newOperatorShare', newOperatorShare); - const self = (this as any) as StakingContract; - const txHashPromise = self.decreaseStakingPoolOperatorShare.sendTransactionAsync( - poolId, - newOperatorShare, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param poolId Unique Id of pool. - * @param newOperatorShare The newly decreased percentage of any rewards owned - * by the operator. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - poolId: string, - newOperatorShare: number | BigNumber, - txData?: Partial | undefined, - ): Promise { - assert.isString('poolId', poolId); - assert.isNumberOrBigNumber('newOperatorShare', newOperatorShare); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('decreaseStakingPoolOperatorShare(bytes32,uint32)', [ - poolId, - newOperatorShare, - ]); - 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 poolId Unique Id of pool. - * @param newOperatorShare The newly decreased percentage of any rewards owned - * by the operator. - */ - async callAsync( - poolId: string, - newOperatorShare: number | BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('poolId', poolId); - assert.isNumberOrBigNumber('newOperatorShare', newOperatorShare); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('decreaseStakingPoolOperatorShare(bytes32,uint32)', [ - poolId, - newOperatorShare, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('decreaseStakingPoolOperatorShare(bytes32,uint32)'); - // 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 poolId Unique Id of pool. - * @param newOperatorShare The newly decreased percentage of any rewards owned - * by the operator. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(poolId: string, newOperatorShare: number | BigNumber): string { - assert.isString('poolId', poolId); - assert.isNumberOrBigNumber('newOperatorShare', newOperatorShare); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'decreaseStakingPoolOperatorShare(bytes32,uint32)', - [poolId, newOperatorShare], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('decreaseStakingPoolOperatorShare(bytes32,uint32)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Begins a new epoch, preparing the prior one for finalization. - * Throws if not enough time has passed between epochs or if the - * previous epoch was not fully finalized. - */ - public endEpoch = { - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('endEpoch()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.endEpoch.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as StakingContract; - const txHashPromise = self.endEpoch.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingContract; - const encodedData = self._strictEncodeArguments('endEpoch()', []); - 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. - * @returns numPoolsToFinalize The number of unfinalized pools. - */ - 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 StakingContract; - const encodedData = self._strictEncodeArguments('endEpoch()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('endEpoch()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('endEpoch()', []); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('endEpoch()'); - return abiEncoder.getSelector(); - }, - }; - public epochDurationInSeconds = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('epochDurationInSeconds()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('epochDurationInSeconds()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Instantly finalizes a single pool that earned rewards in the previous - * epoch, crediting it rewards for members and withdrawing operator's - * rewards as WETH. This can be called by internal functions that need - * to finalize a pool immediately. Does nothing if the pool is already - * finalized or did not earn rewards in the previous epoch. - */ - public finalizePool = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param poolId The pool ID to finalize. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - poolId: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.finalizePool.callAsync(poolId, txDataWithDefaults); - } - - 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 poolId The pool ID to finalize. - * @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( - poolId: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const txHashPromise = self.finalizePool.sendTransactionAsync(poolId, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param poolId The pool ID to finalize. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(poolId: string, txData?: Partial | undefined): Promise { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); - 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 poolId The pool ID to finalize. - */ - async callAsync(poolId: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('finalizePool(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). - * @param poolId The pool ID to finalize. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(poolId: string): string { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('finalizePool(bytes32)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the earliest end time in seconds of this epoch. - * The next epoch can begin once this time is reached. - * Epoch period = [startTimeInSeconds..endTimeInSeconds) - */ - public getCurrentEpochEarliestEndTimeInSeconds = { - /** - * 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 Time in seconds. - */ - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getCurrentEpochEarliestEndTimeInSeconds()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getCurrentEpochEarliestEndTimeInSeconds()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Gets global stake for a given status. - */ - public getGlobalStakeByStatus = { - /** - * 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 stakeStatus UNDELEGATED or DELEGATED - * @returns Global stake for given status. - */ - async callAsync( - stakeStatus: number | BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { - assert.isNumberOrBigNumber('stakeStatus', stakeStatus); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getGlobalStakeByStatus(uint8)', [stakeStatus]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getGlobalStakeByStatus(uint8)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - currentEpoch: BigNumber; - currentEpochBalance: BigNumber; - nextEpochBalance: BigNumber; - }>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Gets an owner's stake balances by status. - */ - public getOwnerStakeByStatus = { - /** - * 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 staker Owner of stake. - * @param stakeStatus UNDELEGATED or DELEGATED - * @returns Owner's stake balances for given status. - */ - async callAsync( - staker: string, - stakeStatus: number | BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { - assert.isString('staker', staker); - assert.isNumberOrBigNumber('stakeStatus', stakeStatus); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getOwnerStakeByStatus(address,uint8)', [ - staker.toLowerCase(), - stakeStatus, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getOwnerStakeByStatus(address,uint8)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - currentEpoch: BigNumber; - currentEpochBalance: BigNumber; - nextEpochBalance: BigNumber; - }>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Retrieves all configurable parameter values. - */ - public getParams = { - /** - * 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 _epochDurationInSeconds Minimum seconds between epochs._rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm._minimumPoolStake Minimum amount of stake required in a pool to collect rewards._cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor._cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor. - */ - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber, number, BigNumber, number, number]> { - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getParams()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getParams()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, number, BigNumber, number, number]>( - rawCallResult, - ); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the stake delegated to a specific staking pool, by a given staker. - */ - public getStakeDelegatedToPoolByOwner = { - /** - * 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 staker of stake. - * @param poolId Unique Id of pool. - * @returns Stake delegated to pool by staker. - */ - async callAsync( - staker: string, - poolId: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { - assert.isString('staker', staker); - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getStakeDelegatedToPoolByOwner(address,bytes32)', [ - staker.toLowerCase(), - poolId, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getStakeDelegatedToPoolByOwner(address,bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - currentEpoch: BigNumber; - currentEpochBalance: BigNumber; - nextEpochBalance: BigNumber; - }>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns a staking pool - */ - public getStakingPool = { - /** - * 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 poolId Unique id of pool. - */ - async callAsync( - poolId: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ operator: string; operatorShare: number }> { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getStakingPool(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getStakingPool(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ operator: string; operatorShare: number }>( - rawCallResult, - ); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Get stats on a staking pool in this epoch. - */ - public getStakingPoolStatsThisEpoch = { - /** - * 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 poolId Pool Id to query. - * @returns PoolStats struct for pool id. - */ - async callAsync( - poolId: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ feesCollected: BigNumber; weightedStake: BigNumber; membersStake: BigNumber }> { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getStakingPoolStatsThisEpoch(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getStakingPoolStatsThisEpoch(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - feesCollected: BigNumber; - weightedStake: BigNumber; - membersStake: BigNumber; - }>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the total stake for a given staker. - */ - public getTotalStake = { - /** - * 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 staker of stake. - * @returns Total ZRX staked by `staker`. - */ - async callAsync( - staker: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('staker', staker); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getTotalStake(address)', [staker.toLowerCase()]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getTotalStake(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the total stake delegated to a specific staking pool, - * across all members. - */ - public getTotalStakeDelegatedToPool = { - /** - * 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 poolId Unique Id of pool. - * @returns Total stake delegated to pool. - */ - async callAsync( - poolId: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getTotalStakeDelegatedToPool(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getTotalStakeDelegatedToPool(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - currentEpoch: BigNumber; - currentEpochBalance: BigNumber; - nextEpochBalance: BigNumber; - }>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the current weth contract address - */ - public getWethContract = { - /** - * 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 wethContract The WETH contract instance. - */ - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getWethContract()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getWethContract()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Returns the current zrxVault address. - */ - public getZrxVault = { - /** - * 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 zrxVault The zrxVault contract. - */ - 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 StakingContract; - const encodedData = self._strictEncodeArguments('getZrxVault()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getZrxVault()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Initialize storage owned by this contract. - * This function should not be called directly. - * The StakingProxy contract will call it in `attachStakingContract()`. - */ - public init = { - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('init()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.init.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as StakingContract; - const txHashPromise = self.init.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingContract; - const encodedData = self._strictEncodeArguments('init()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + private readonly _methodABIIndex: { [name: string]: number } = {}; + private readonly _subscriptionManager: SubscriptionManager; + public static async deployFrom0xArtifactAsync( + artifact: ContractArtifact | SimpleContractArtifact, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, + wethAddress: string, + zrxVaultAddress: 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 StakingContract.deployAsync( + bytecode, + abi, + provider, + txDefaults, + logDecodeDependenciesAbiOnly, + wethAddress, + zrxVaultAddress, + ); + } + public static async deployAsync( + bytecode: string, + abi: ContractAbi, + supportedProvider: SupportedProvider, + txDefaults: Partial, + logDecodeDependencies: { [contractName: string]: ContractAbi }, + wethAddress: string, + zrxVaultAddress: 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); + [wethAddress, zrxVaultAddress] = BaseContract._formatABIDataItemList( + constructorAbi.inputs, + [wethAddress, zrxVaultAddress], + BaseContract._bigNumberToString, + ); + const iface = new ethers.utils.Interface(abi); + const deployInfo = iface.deployFunction; + const txData = deployInfo.encode(bytecode, [wethAddress, zrxVaultAddress]); + 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(`Staking successfully deployed at ${txReceipt.contractAddress}`); + const contractInstance = new StakingContract( + txReceipt.contractAddress as string, + provider, + txDefaults, + logDecodeDependencies, + ); + contractInstance.constructorArgs = [wethAddress, zrxVaultAddress]; + return contractInstance; + } - 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 StakingContract; - const encodedData = self._strictEncodeArguments('init()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('init()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('init()', []); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('init()'); - return abiEncoder.getSelector(); - }, - }; /** - * Allows caller to join a staking pool as a maker. - */ - public joinStakingPoolAsMaker = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param poolId Unique id of pool. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - poolId: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.joinStakingPoolAsMaker.callAsync(poolId, txDataWithDefaults); - } - - 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 poolId Unique id of pool. - * @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( - poolId: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const txHashPromise = self.joinStakingPoolAsMaker.sendTransactionAsync(poolId, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param poolId Unique id of pool. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(poolId: string, txData?: Partial | undefined): Promise { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); - 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 poolId Unique id of pool. - */ - async callAsync(poolId: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('joinStakingPoolAsMaker(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). - * @param poolId Unique id of pool. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(poolId: string): string { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('joinStakingPoolAsMaker(bytes32)'); - return abiEncoder.getSelector(); - }, - }; - public lastPoolId = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('lastPoolId()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('lastPoolId()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public minimumPoolStake = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('minimumPoolStake()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('minimumPoolStake()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Moves stake between statuses: 'undelegated' or 'delegated'. - * Delegated stake can also be moved between pools. - * This change comes into effect next epoch. - */ - public moveStake = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param from status to move stake out of. - * @param to status to move stake into. - * @param amount of stake to move. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - from: { status: number | BigNumber; poolId: string }, - to: { status: number | BigNumber; poolId: string }, - amount: BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('moveStake((uint8,bytes32),(uint8,bytes32),uint256)', [ - from, - to, - amount, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.moveStake.callAsync(from, to, amount, txDataWithDefaults); - } - - 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 status to move stake out of. - * @param to status to move stake into. - * @param amount of stake to move. - * @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: { status: number | BigNumber; poolId: string }, - to: { status: number | BigNumber; poolId: string }, - amount: BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const txHashPromise = self.moveStake.sendTransactionAsync(from, to, amount, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param from status to move stake out of. - * @param to status to move stake into. - * @param amount of stake to move. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - from: { status: number | BigNumber; poolId: string }, - to: { status: number | BigNumber; poolId: string }, - amount: BigNumber, - txData?: Partial | undefined, - ): Promise { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('moveStake((uint8,bytes32),(uint8,bytes32),uint256)', [ - from, - to, - 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 from status to move stake out of. - * @param to status to move stake into. - * @param amount of stake to move. - */ - async callAsync( - from: { status: number | BigNumber; poolId: string }, - to: { status: number | BigNumber; poolId: string }, - amount: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - 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 StakingContract; - const encodedData = self._strictEncodeArguments('moveStake((uint8,bytes32),(uint8,bytes32),uint256)', [ - from, - to, - amount, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('moveStake((uint8,bytes32),(uint8,bytes32),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 status to move stake out of. - * @param to status to move stake into. - * @param amount of stake to move. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - from: { status: number | BigNumber; poolId: string }, - to: { status: number | BigNumber; poolId: string }, - amount: BigNumber, - ): string { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'moveStake((uint8,bytes32),(uint8,bytes32),uint256)', - [from, to, amount], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('moveStake((uint8,bytes32),(uint8,bytes32),uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('owner()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Pays a protocol fee in ETH or WETH. - * Only a known 0x exchange can call this method. See - * (MixinExchangeManager). - */ - public payProtocolFee = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param makerAddress The address of the order's maker. - * @param payerAddress The address of the protocol fee payer. - * @param protocolFee The protocol fee amount. This is either passed as ETH or - * transferred as WETH. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - makerAddress: string, - payerAddress: string, - protocolFee: BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('makerAddress', makerAddress); - assert.isString('payerAddress', payerAddress); - assert.isBigNumber('protocolFee', protocolFee); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ - makerAddress.toLowerCase(), - payerAddress.toLowerCase(), - protocolFee, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.payProtocolFee.callAsync(makerAddress, payerAddress, protocolFee, txDataWithDefaults); - } - - 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 makerAddress The address of the order's maker. - * @param payerAddress The address of the protocol fee payer. - * @param protocolFee The protocol fee amount. This is either passed as ETH or - * transferred as WETH. - * @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( - makerAddress: string, - payerAddress: string, - protocolFee: BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('makerAddress', makerAddress); - assert.isString('payerAddress', payerAddress); - assert.isBigNumber('protocolFee', protocolFee); - const self = (this as any) as StakingContract; - const txHashPromise = self.payProtocolFee.sendTransactionAsync( - makerAddress.toLowerCase(), - payerAddress.toLowerCase(), - protocolFee, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param makerAddress The address of the order's maker. - * @param payerAddress The address of the protocol fee payer. - * @param protocolFee The protocol fee amount. This is either passed as ETH or - * transferred as WETH. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - makerAddress: string, - payerAddress: string, - protocolFee: BigNumber, - txData?: Partial | undefined, - ): Promise { - assert.isString('makerAddress', makerAddress); - assert.isString('payerAddress', payerAddress); - assert.isBigNumber('protocolFee', protocolFee); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ - makerAddress.toLowerCase(), - payerAddress.toLowerCase(), - protocolFee, - ]); - 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 makerAddress The address of the order's maker. - * @param payerAddress The address of the protocol fee payer. - * @param protocolFee The protocol fee amount. This is either passed as ETH or - * transferred as WETH. - */ - async callAsync( - makerAddress: string, - payerAddress: string, - protocolFee: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('makerAddress', makerAddress); - assert.isString('payerAddress', payerAddress); - assert.isBigNumber('protocolFee', protocolFee); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ - makerAddress.toLowerCase(), - payerAddress.toLowerCase(), - protocolFee, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('payProtocolFee(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 makerAddress The address of the order's maker. - * @param payerAddress The address of the protocol fee payer. - * @param protocolFee The protocol fee amount. This is either passed as ETH or - * transferred as WETH. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(makerAddress: string, payerAddress: string, protocolFee: BigNumber): string { - assert.isString('makerAddress', makerAddress); - assert.isString('payerAddress', payerAddress); - assert.isBigNumber('protocolFee', protocolFee); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ - makerAddress.toLowerCase(), - payerAddress.toLowerCase(), - protocolFee, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('payProtocolFee(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - public poolIdByMaker = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('poolIdByMaker(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('poolIdByMaker(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public poolStatsByEpoch = { - /** - * 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: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber, BigNumber, BigNumber]> { - assert.isString('index_0', index_0); - assert.isBigNumber('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 StakingContract; - const encodedData = self._strictEncodeArguments('poolStatsByEpoch(bytes32,uint256)', [index_0, index_1]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('poolStatsByEpoch(bytes32,uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('target', target); - const self = (this as any) as StakingContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.removeAuthorizedAddress.callAsync(target, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('target', target); - const self = (this as any) as StakingContract; - const txHashPromise = self.removeAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingContract; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(target: string): string { - assert.isString('target', target); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ - target.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('target', target); - assert.isBigNumber('index', index); - const self = (this as any) as StakingContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.removeAuthorizedAddressAtIndex.callAsync(target, index, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('target', target); - assert.isBigNumber('index', index); - const self = (this as any) as StakingContract; - const txHashPromise = self.removeAuthorizedAddressAtIndex.sendTransactionAsync( - target.toLowerCase(), - index, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingContract; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(target: string, index: BigNumber): string { - assert.isString('target', target); - assert.isBigNumber('index', index); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'removeAuthorizedAddressAtIndex(address,uint256)', - [target.toLowerCase(), index], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Removes an existing exchange address - */ - public removeExchangeAddress = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param addr Address of exchange contract to remove - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - addr: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('removeExchangeAddress(address)', [addr.toLowerCase()]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.removeExchangeAddress.callAsync(addr, txDataWithDefaults); - } - - 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 addr Address of exchange contract to remove - * @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( - addr: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const txHashPromise = self.removeExchangeAddress.sendTransactionAsync(addr.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param addr Address of exchange contract to remove - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(addr: string, txData?: Partial | undefined): Promise { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('removeExchangeAddress(address)', [addr.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 addr Address of exchange contract to remove - */ - async callAsync(addr: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('addr', addr); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('removeExchangeAddress(address)', [addr.toLowerCase()]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('removeExchangeAddress(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 addr Address of exchange contract to remove - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(addr: string): string { - assert.isString('addr', addr); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('removeExchangeAddress(address)', [ - addr.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('removeExchangeAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - public rewardDelegatedStakeWeight = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('rewardDelegatedStakeWeight()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('rewardDelegatedStakeWeight()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public rewardsByPoolId = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('rewardsByPoolId(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('rewardsByPoolId(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Set all configurable parameters at once. - */ - public setParams = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param _epochDurationInSeconds Minimum seconds between epochs. - * @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs - * operator stake, in ppm. - * @param _minimumPoolStake Minimum amount of stake required in a pool to - * collect rewards. - * @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor. - * @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha - * factor. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - _epochDurationInSeconds: BigNumber, - _rewardDelegatedStakeWeight: number | BigNumber, - _minimumPoolStake: BigNumber, - _cobbDouglasAlphaNumerator: number | BigNumber, - _cobbDouglasAlphaDenominator: number | BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('_epochDurationInSeconds', _epochDurationInSeconds); - assert.isNumberOrBigNumber('_rewardDelegatedStakeWeight', _rewardDelegatedStakeWeight); - assert.isBigNumber('_minimumPoolStake', _minimumPoolStake); - assert.isNumberOrBigNumber('_cobbDouglasAlphaNumerator', _cobbDouglasAlphaNumerator); - assert.isNumberOrBigNumber('_cobbDouglasAlphaDenominator', _cobbDouglasAlphaDenominator); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('setParams(uint256,uint32,uint256,uint32,uint32)', [ - _epochDurationInSeconds, - _rewardDelegatedStakeWeight, - _minimumPoolStake, - _cobbDouglasAlphaNumerator, - _cobbDouglasAlphaDenominator, - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.setParams.callAsync( - _epochDurationInSeconds, - _rewardDelegatedStakeWeight, - _minimumPoolStake, - _cobbDouglasAlphaNumerator, - _cobbDouglasAlphaDenominator, - txDataWithDefaults, - ); - } - - 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 _epochDurationInSeconds Minimum seconds between epochs. - * @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs - * operator stake, in ppm. - * @param _minimumPoolStake Minimum amount of stake required in a pool to - * collect rewards. - * @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor. - * @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha - * factor. - * @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( - _epochDurationInSeconds: BigNumber, - _rewardDelegatedStakeWeight: number | BigNumber, - _minimumPoolStake: BigNumber, - _cobbDouglasAlphaNumerator: number | BigNumber, - _cobbDouglasAlphaDenominator: number | BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('_epochDurationInSeconds', _epochDurationInSeconds); - assert.isNumberOrBigNumber('_rewardDelegatedStakeWeight', _rewardDelegatedStakeWeight); - assert.isBigNumber('_minimumPoolStake', _minimumPoolStake); - assert.isNumberOrBigNumber('_cobbDouglasAlphaNumerator', _cobbDouglasAlphaNumerator); - assert.isNumberOrBigNumber('_cobbDouglasAlphaDenominator', _cobbDouglasAlphaDenominator); - const self = (this as any) as StakingContract; - const txHashPromise = self.setParams.sendTransactionAsync( - _epochDurationInSeconds, - _rewardDelegatedStakeWeight, - _minimumPoolStake, - _cobbDouglasAlphaNumerator, - _cobbDouglasAlphaDenominator, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param _epochDurationInSeconds Minimum seconds between epochs. - * @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs - * operator stake, in ppm. - * @param _minimumPoolStake Minimum amount of stake required in a pool to - * collect rewards. - * @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor. - * @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha - * factor. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync( - _epochDurationInSeconds: BigNumber, - _rewardDelegatedStakeWeight: number | BigNumber, - _minimumPoolStake: BigNumber, - _cobbDouglasAlphaNumerator: number | BigNumber, - _cobbDouglasAlphaDenominator: number | BigNumber, - txData?: Partial | undefined, - ): Promise { - assert.isBigNumber('_epochDurationInSeconds', _epochDurationInSeconds); - assert.isNumberOrBigNumber('_rewardDelegatedStakeWeight', _rewardDelegatedStakeWeight); - assert.isBigNumber('_minimumPoolStake', _minimumPoolStake); - assert.isNumberOrBigNumber('_cobbDouglasAlphaNumerator', _cobbDouglasAlphaNumerator); - assert.isNumberOrBigNumber('_cobbDouglasAlphaDenominator', _cobbDouglasAlphaDenominator); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('setParams(uint256,uint32,uint256,uint32,uint32)', [ - _epochDurationInSeconds, - _rewardDelegatedStakeWeight, - _minimumPoolStake, - _cobbDouglasAlphaNumerator, - _cobbDouglasAlphaDenominator, - ]); - 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 _epochDurationInSeconds Minimum seconds between epochs. - * @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs - * operator stake, in ppm. - * @param _minimumPoolStake Minimum amount of stake required in a pool to - * collect rewards. - * @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor. - * @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha - * factor. - */ - async callAsync( - _epochDurationInSeconds: BigNumber, - _rewardDelegatedStakeWeight: number | BigNumber, - _minimumPoolStake: BigNumber, - _cobbDouglasAlphaNumerator: number | BigNumber, - _cobbDouglasAlphaDenominator: number | BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isBigNumber('_epochDurationInSeconds', _epochDurationInSeconds); - assert.isNumberOrBigNumber('_rewardDelegatedStakeWeight', _rewardDelegatedStakeWeight); - assert.isBigNumber('_minimumPoolStake', _minimumPoolStake); - assert.isNumberOrBigNumber('_cobbDouglasAlphaNumerator', _cobbDouglasAlphaNumerator); - assert.isNumberOrBigNumber('_cobbDouglasAlphaDenominator', _cobbDouglasAlphaDenominator); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('setParams(uint256,uint32,uint256,uint32,uint32)', [ - _epochDurationInSeconds, - _rewardDelegatedStakeWeight, - _minimumPoolStake, - _cobbDouglasAlphaNumerator, - _cobbDouglasAlphaDenominator, - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('setParams(uint256,uint32,uint256,uint32,uint32)'); - // 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 _epochDurationInSeconds Minimum seconds between epochs. - * @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs - * operator stake, in ppm. - * @param _minimumPoolStake Minimum amount of stake required in a pool to - * collect rewards. - * @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor. - * @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha - * factor. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData( - _epochDurationInSeconds: BigNumber, - _rewardDelegatedStakeWeight: number | BigNumber, - _minimumPoolStake: BigNumber, - _cobbDouglasAlphaNumerator: number | BigNumber, - _cobbDouglasAlphaDenominator: number | BigNumber, - ): string { - assert.isBigNumber('_epochDurationInSeconds', _epochDurationInSeconds); - assert.isNumberOrBigNumber('_rewardDelegatedStakeWeight', _rewardDelegatedStakeWeight); - assert.isBigNumber('_minimumPoolStake', _minimumPoolStake); - assert.isNumberOrBigNumber('_cobbDouglasAlphaNumerator', _cobbDouglasAlphaNumerator); - assert.isNumberOrBigNumber('_cobbDouglasAlphaDenominator', _cobbDouglasAlphaDenominator); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'setParams(uint256,uint32,uint256,uint32,uint32)', - [ - _epochDurationInSeconds, - _rewardDelegatedStakeWeight, - _minimumPoolStake, - _cobbDouglasAlphaNumerator, - _cobbDouglasAlphaDenominator, - ], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('setParams(uint256,uint32,uint256,uint32,uint32)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Stake ZRX tokens. Tokens are deposited into the ZRX Vault. - * Unstake to retrieve the ZRX. Stake is in the 'Active' status. - */ - public stake = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param amount of ZRX to stake. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - amount: BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('stake(uint256)', [amount]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.stake.callAsync(amount, txDataWithDefaults); - } - - 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 amount of ZRX to stake. - * @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( - amount: BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const txHashPromise = self.stake.sendTransactionAsync(amount, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param amount of ZRX to stake. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(amount: BigNumber, txData?: Partial | undefined): Promise { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('stake(uint256)', [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 amount of ZRX to stake. - */ - async callAsync(amount: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - 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 StakingContract; - const encodedData = self._strictEncodeArguments('stake(uint256)', [amount]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('stake(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 amount of ZRX to stake. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(amount: BigNumber): string { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('stake(uint256)', [amount]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('stake(uint256)'); - return abiEncoder.getSelector(); - }, - }; - public stakingContract = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('stakingContract()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('stakingContract()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('newOwner', newOwner); - const self = (this as any) as StakingContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferOwnership.callAsync(newOwner, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('newOwner', newOwner); - const self = (this as any) as StakingContract; - const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingContract; - 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 StakingContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(newOwner: string): string { - assert.isString('newOwner', newOwner); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ - newOwner.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Unstake. Tokens are withdrawn from the ZRX Vault and returned to - * the staker. Stake must be in the 'undelegated' status in both the - * current and next epoch in order to be unstaked. - */ - public unstake = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param amount of ZRX to unstake. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - amount: BigNumber, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('unstake(uint256)', [amount]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.unstake.callAsync(amount, txDataWithDefaults); - } - - 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 amount of ZRX to unstake. - * @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( - amount: BigNumber, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const txHashPromise = self.unstake.sendTransactionAsync(amount, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param amount of ZRX to unstake. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(amount: BigNumber, txData?: Partial | undefined): Promise { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('unstake(uint256)', [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 amount of ZRX to unstake. - */ - async callAsync(amount: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - 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 StakingContract; - const encodedData = self._strictEncodeArguments('unstake(uint256)', [amount]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('unstake(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 amount of ZRX to unstake. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(amount: BigNumber): string { - assert.isBigNumber('amount', amount); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('unstake(uint256)', [amount]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('unstake(uint256)'); - return abiEncoder.getSelector(); - }, - }; - public validExchanges = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('validExchanges(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('validExchanges(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public wethReservedForPoolRewards = { - /** - * 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 StakingContract; - const encodedData = self._strictEncodeArguments('wethReservedForPoolRewards()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('wethReservedForPoolRewards()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Withdraws the caller's WETH rewards that have accumulated - * until the last epoch. - */ - public withdrawDelegatorRewards = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param poolId Unique id of pool. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - poolId: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [poolId]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.withdrawDelegatorRewards.callAsync(poolId, txDataWithDefaults); - } - - 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 poolId Unique id of pool. - * @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( - poolId: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const txHashPromise = self.withdrawDelegatorRewards.sendTransactionAsync(poolId, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param poolId Unique id of pool. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(poolId: string, txData?: Partial | undefined): Promise { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const encodedData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [poolId]); - 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 poolId Unique id of pool. - */ - async callAsync(poolId: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('poolId', poolId); - 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 StakingContract; - const encodedData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [poolId]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('withdrawDelegatorRewards(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). - * @param poolId Unique id of pool. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(poolId: string): string { - assert.isString('poolId', poolId); - const self = (this as any) as StakingContract; - const abiEncodedTransactionData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [ - poolId, - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingContract; - const abiEncoder = self._lookupAbiEncoder('withdrawDelegatorRewards(bytes32)'); - return abiEncoder.getSelector(); - }, - }; - private readonly _subscriptionManager: SubscriptionManager; - public static async deployFrom0xArtifactAsync( - artifact: ContractArtifact | SimpleContractArtifact, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractArtifact | SimpleContractArtifact }, - wethAddress_: string, - zrxVaultAddress_: 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 StakingContract.deployAsync( - bytecode, - abi, - provider, - txDefaults, - logDecodeDependenciesAbiOnly, - wethAddress_, - zrxVaultAddress_, - ); - } - public static async deployAsync( - bytecode: string, - abi: ContractAbi, - supportedProvider: SupportedProvider, - txDefaults: Partial, - logDecodeDependencies: { [contractName: string]: ContractAbi }, - wethAddress_: string, - zrxVaultAddress_: 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); - [wethAddress_, zrxVaultAddress_] = BaseContract._formatABIDataItemList( - constructorAbi.inputs, - [wethAddress_, zrxVaultAddress_], - BaseContract._bigNumberToString, - ); - const iface = new ethers.utils.Interface(abi); - const deployInfo = iface.deployFunction; - const txData = deployInfo.encode(bytecode, [wethAddress_, zrxVaultAddress_]); - 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(`Staking successfully deployed at ${txReceipt.contractAddress}`); - const contractInstance = new StakingContract( - txReceipt.contractAddress as string, - provider, - txDefaults, - logDecodeDependencies, - ); - contractInstance.constructorArgs = [wethAddress_, zrxVaultAddress_]; - return contractInstance; - } - - /** - * @returns The contract ABI + * @returns The contract ABI */ public static ABI(): ContractAbi { const abi = [ { inputs: [ { - name: 'wethAddress_', + name: 'wethAddress', type: 'address', }, { - name: 'zrxVaultAddress_', + name: 'zrxVaultAddress', type: 'address', }, ], @@ -6337,35 +1611,3930 @@ export class StakingContract extends BaseContract { ] as ContractAbi; return abi; } - /** - * Subscribe to an event type emitted by the Staking contract. - * @param eventName The Staking 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: StakingEvents, - indexFilterValues: IndexedFilterValues, - callback: EventCallback, - isVerbose: boolean = false, - blockPollingIntervalMs?: number, - ): string { - assert.doesBelongToStringEnum('eventName', eventName, StakingEvents); - assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); - assert.isFunction('callback', callback); - const subscriptionToken = this._subscriptionManager.subscribe( - this.address, - eventName, - indexFilterValues, - StakingContract.ABI(), - callback, - isVerbose, - blockPollingIntervalMs, - ); - return subscriptionToken; + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = StakingContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as StakingContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as StakingContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as StakingContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Authorizes an address. + * @param target Address to authorize. + */ + public addAuthorizedAddress(target: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('target', target); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Adds a new exchange address + * @param addr Address of exchange contract to add + */ + public addExchangeAddress(addr: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('addr', addr); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('addExchangeAddress(address)', [addr.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('addExchangeAddress(address)', [addr.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; + }, + 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 encodedData = self._strictEncodeArguments('addExchangeAddress(address)', [addr.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addExchangeAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('addExchangeAddress(address)', [ + addr.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public aggregatedStatsByEpoch( + index_0: BigNumber, + ): ContractFunctionObj<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { + const self = (this as any) as StakingContract; + assert.isBigNumber('index_0', index_0); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('aggregatedStatsByEpoch(uint256)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('aggregatedStatsByEpoch(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [BigNumber, BigNumber, BigNumber, BigNumber, BigNumber] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('aggregatedStatsByEpoch(uint256)', [ + index_0, + ]); + return abiEncodedTransactionData; + }, + }; + } + public authorities(index_0: BigNumber): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isBigNumber('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + public authorized(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('authorized(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('authorized(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public cobbDouglasAlphaDenominator(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('cobbDouglasAlphaDenominator()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaDenominator()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('cobbDouglasAlphaDenominator()', []); + return abiEncodedTransactionData; + }, + }; + } + public cobbDouglasAlphaNumerator(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('cobbDouglasAlphaNumerator()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaNumerator()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('cobbDouglasAlphaNumerator()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Computes the reward balance in ETH of a specific member of a pool. + * @param poolId Unique id of pool. + * @param member The member of the pool. + * @returns totalReward Balance in ETH. + */ + public computeRewardBalanceOfDelegator(poolId: string, member: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + assert.isString('member', member); + + return { + 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 encodedData = self._strictEncodeArguments('computeRewardBalanceOfDelegator(bytes32,address)', [ + poolId, + member.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('computeRewardBalanceOfDelegator(bytes32,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'computeRewardBalanceOfDelegator(bytes32,address)', + [poolId, member.toLowerCase()], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Computes the reward balance in ETH of the operator of a pool. + * @param poolId Unique id of pool. + * @returns totalReward Balance in ETH. + */ + public computeRewardBalanceOfOperator(poolId: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + 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 encodedData = self._strictEncodeArguments('computeRewardBalanceOfOperator(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('computeRewardBalanceOfOperator(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'computeRewardBalanceOfOperator(bytes32)', + [poolId], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Create a new staking pool. The sender will be the operator of this pool. Note that an operator must be payable. + * @param operatorShare Portion of rewards owned by the operator, in ppm. + * @param addOperatorAsMaker Adds operator to the created pool as a maker for + * convenience iff true. + * @returns poolId The unique pool id generated for this pool. + */ + public createStakingPool( + operatorShare: number | BigNumber, + addOperatorAsMaker: boolean, + ): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isNumberOrBigNumber('operatorShare', operatorShare); + assert.isBoolean('addOperatorAsMaker', addOperatorAsMaker); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ + operatorShare, + addOperatorAsMaker, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ + operatorShare, + addOperatorAsMaker, + ]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ + operatorShare, + addOperatorAsMaker, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('createStakingPool(uint32,bool)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('createStakingPool(uint32,bool)', [ + operatorShare, + addOperatorAsMaker, + ]); + return abiEncodedTransactionData; + }, + }; + } + public currentEpoch(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('currentEpoch()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('currentEpoch()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('currentEpoch()', []); + return abiEncodedTransactionData; + }, + }; + } + public currentEpochStartTimeInSeconds(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('currentEpochStartTimeInSeconds()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('currentEpochStartTimeInSeconds()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('currentEpochStartTimeInSeconds()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Decreases the operator share for the given pool (i.e. increases pool rewards for members). + * @param poolId Unique Id of pool. + * @param newOperatorShare The newly decreased percentage of any rewards owned + * by the operator. + */ + public decreaseStakingPoolOperatorShare( + poolId: string, + newOperatorShare: number | BigNumber, + ): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + assert.isNumberOrBigNumber('newOperatorShare', newOperatorShare); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('decreaseStakingPoolOperatorShare(bytes32,uint32)', [ + poolId, + newOperatorShare, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('decreaseStakingPoolOperatorShare(bytes32,uint32)', [ + poolId, + newOperatorShare, + ]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('decreaseStakingPoolOperatorShare(bytes32,uint32)', [ + poolId, + newOperatorShare, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decreaseStakingPoolOperatorShare(bytes32,uint32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'decreaseStakingPoolOperatorShare(bytes32,uint32)', + [poolId, newOperatorShare], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Begins a new epoch, preparing the prior one for finalization. + * Throws if not enough time has passed between epochs or if the + * previous epoch was not fully finalized. + * @returns numPoolsToFinalize The number of unfinalized pools. + */ + public endEpoch(): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('endEpoch()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('endEpoch()', []); + 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; + }, + 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 encodedData = self._strictEncodeArguments('endEpoch()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('endEpoch()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('endEpoch()', []); + return abiEncodedTransactionData; + }, + }; + } + public epochDurationInSeconds(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('epochDurationInSeconds()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('epochDurationInSeconds()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('epochDurationInSeconds()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Instantly finalizes a single pool that earned rewards in the previous + * epoch, crediting it rewards for members and withdrawing operator's + * rewards as WETH. This can be called by internal functions that need + * to finalize a pool immediately. Does nothing if the pool is already + * finalized or did not earn rewards in the previous epoch. + * @param poolId The pool ID to finalize. + */ + public finalizePool(poolId: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('finalizePool(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('finalizePool(bytes32)', [poolId]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets all authorized addresses. + * @returns Array of authorized addresses. + */ + public getAuthorizedAddresses(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the earliest end time in seconds of this epoch. + * The next epoch can begin once this time is reached. + * Epoch period = [startTimeInSeconds..endTimeInSeconds) + * @returns Time in seconds. + */ + public getCurrentEpochEarliestEndTimeInSeconds(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('getCurrentEpochEarliestEndTimeInSeconds()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getCurrentEpochEarliestEndTimeInSeconds()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getCurrentEpochEarliestEndTimeInSeconds()', + [], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets global stake for a given status. + * @param stakeStatus UNDELEGATED or DELEGATED + * @returns Global stake for given status. + */ + public getGlobalStakeByStatus( + stakeStatus: number | BigNumber, + ): ContractFunctionObj<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + const self = (this as any) as StakingContract; + assert.isNumberOrBigNumber('stakeStatus', stakeStatus); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getGlobalStakeByStatus(uint8)', [stakeStatus]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getGlobalStakeByStatus(uint8)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + currentEpoch: BigNumber; + currentEpochBalance: BigNumber; + nextEpochBalance: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getGlobalStakeByStatus(uint8)', [ + stakeStatus, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets an owner's stake balances by status. + * @param staker Owner of stake. + * @param stakeStatus UNDELEGATED or DELEGATED + * @returns Owner's stake balances for given status. + */ + public getOwnerStakeByStatus( + staker: string, + stakeStatus: number | BigNumber, + ): ContractFunctionObj<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + const self = (this as any) as StakingContract; + assert.isString('staker', staker); + assert.isNumberOrBigNumber('stakeStatus', stakeStatus); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getOwnerStakeByStatus(address,uint8)', [ + staker.toLowerCase(), + stakeStatus, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getOwnerStakeByStatus(address,uint8)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + currentEpoch: BigNumber; + currentEpochBalance: BigNumber; + nextEpochBalance: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getOwnerStakeByStatus(address,uint8)', [ + staker.toLowerCase(), + stakeStatus, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Retrieves all configurable parameter values. + * @returns _epochDurationInSeconds Minimum seconds between epochs._rewardDelegatedStakeWeight How much delegated stake is weighted vs operator stake, in ppm._minimumPoolStake Minimum amount of stake required in a pool to collect rewards._cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor._cobbDouglasAlphaDenominator Denominator for cobb douglas alpha factor. + */ + public getParams(): ContractFunctionObj<[BigNumber, number, BigNumber, number, number]> { + const self = (this as any) as StakingContract; + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, number, BigNumber, number, number]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getParams()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getParams()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, number, BigNumber, number, number]>( + rawCallResult, + ); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getParams()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the stake delegated to a specific staking pool, by a given staker. + * @param staker of stake. + * @param poolId Unique Id of pool. + * @returns Stake delegated to pool by staker. + */ + public getStakeDelegatedToPoolByOwner( + staker: string, + poolId: string, + ): ContractFunctionObj<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + const self = (this as any) as StakingContract; + assert.isString('staker', staker); + assert.isString('poolId', poolId); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getStakeDelegatedToPoolByOwner(address,bytes32)', [ + staker.toLowerCase(), + poolId, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getStakeDelegatedToPoolByOwner(address,bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + currentEpoch: BigNumber; + currentEpochBalance: BigNumber; + nextEpochBalance: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'getStakeDelegatedToPoolByOwner(address,bytes32)', + [staker.toLowerCase(), poolId], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns a staking pool + * @param poolId Unique id of pool. + */ + public getStakingPool(poolId: string): ContractFunctionObj<{ operator: string; operatorShare: number }> { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ operator: string; operatorShare: number }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getStakingPool(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getStakingPool(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ operator: string; operatorShare: number }>( + rawCallResult, + ); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getStakingPool(bytes32)', [poolId]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Get stats on a staking pool in this epoch. + * @param poolId Pool Id to query. + * @returns PoolStats struct for pool id. + */ + public getStakingPoolStatsThisEpoch( + poolId: string, + ): ContractFunctionObj<{ feesCollected: BigNumber; weightedStake: BigNumber; membersStake: BigNumber }> { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ feesCollected: BigNumber; weightedStake: BigNumber; membersStake: BigNumber }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getStakingPoolStatsThisEpoch(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getStakingPoolStatsThisEpoch(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + feesCollected: BigNumber; + weightedStake: BigNumber; + membersStake: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getStakingPoolStatsThisEpoch(bytes32)', [ + poolId, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the total stake for a given staker. + * @param staker of stake. + * @returns Total ZRX staked by `staker`. + */ + public getTotalStake(staker: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('staker', staker); + + return { + 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 encodedData = self._strictEncodeArguments('getTotalStake(address)', [staker.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTotalStake(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getTotalStake(address)', [ + staker.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the total stake delegated to a specific staking pool, + * across all members. + * @param poolId Unique Id of pool. + * @returns Total stake delegated to pool. + */ + public getTotalStakeDelegatedToPool( + poolId: string, + ): ContractFunctionObj<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ currentEpoch: BigNumber; currentEpochBalance: BigNumber; nextEpochBalance: BigNumber }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('getTotalStakeDelegatedToPool(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getTotalStakeDelegatedToPool(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + currentEpoch: BigNumber; + currentEpochBalance: BigNumber; + nextEpochBalance: BigNumber; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getTotalStakeDelegatedToPool(bytes32)', [ + poolId, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the current weth contract address + * @returns wethContract The WETH contract instance. + */ + public getWethContract(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('getWethContract()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getWethContract()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getWethContract()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Returns the current zrxVault address. + * @returns zrxVault The zrxVault contract. + */ + public getZrxVault(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('getZrxVault()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getZrxVault()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getZrxVault()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Initialize storage owned by this contract. + * This function should not be called directly. + * The StakingProxy contract will call it in `attachStakingContract()`. + */ + public init(): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('init()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('init()', []); + 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; + }, + 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 encodedData = self._strictEncodeArguments('init()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('init()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('init()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Allows caller to join a staking pool as a maker. + * @param poolId Unique id of pool. + */ + public joinStakingPoolAsMaker(poolId: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('joinStakingPoolAsMaker(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('joinStakingPoolAsMaker(bytes32)', [ + poolId, + ]); + return abiEncodedTransactionData; + }, + }; + } + public lastPoolId(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('lastPoolId()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('lastPoolId()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('lastPoolId()', []); + return abiEncodedTransactionData; + }, + }; + } + public minimumPoolStake(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('minimumPoolStake()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('minimumPoolStake()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('minimumPoolStake()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Moves stake between statuses: 'undelegated' or 'delegated'. + * Delegated stake can also be moved between pools. + * This change comes into effect next epoch. + * @param from status to move stake out of. + * @param to status to move stake into. + * @param amount of stake to move. + */ + public moveStake( + from: { status: number | BigNumber; poolId: string }, + to: { status: number | BigNumber; poolId: string }, + amount: BigNumber, + ): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + + assert.isBigNumber('amount', amount); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('moveStake((uint8,bytes32),(uint8,bytes32),uint256)', [ + from, + to, + amount, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('moveStake((uint8,bytes32),(uint8,bytes32),uint256)', [ + from, + to, + 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; + }, + 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 encodedData = self._strictEncodeArguments('moveStake((uint8,bytes32),(uint8,bytes32),uint256)', [ + from, + to, + amount, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('moveStake((uint8,bytes32),(uint8,bytes32),uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'moveStake((uint8,bytes32),(uint8,bytes32),uint256)', + [from, to, amount], + ); + return abiEncodedTransactionData; + }, + }; + } + public owner(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('owner()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Pays a protocol fee in ETH or WETH. + * Only a known 0x exchange can call this method. See + * (MixinExchangeManager). + * @param makerAddress The address of the order's maker. + * @param payerAddress The address of the protocol fee payer. + * @param protocolFee The protocol fee amount. This is either passed as ETH or + * transferred as WETH. + */ + public payProtocolFee( + makerAddress: string, + payerAddress: string, + protocolFee: BigNumber, + ): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('makerAddress', makerAddress); + assert.isString('payerAddress', payerAddress); + assert.isBigNumber('protocolFee', protocolFee); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ + makerAddress.toLowerCase(), + payerAddress.toLowerCase(), + protocolFee, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ + makerAddress.toLowerCase(), + payerAddress.toLowerCase(), + protocolFee, + ]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('payProtocolFee(address,address,uint256)', [ + makerAddress.toLowerCase(), + payerAddress.toLowerCase(), + protocolFee, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('payProtocolFee(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'payProtocolFee(address,address,uint256)', + [makerAddress.toLowerCase(), payerAddress.toLowerCase(), protocolFee], + ); + return abiEncodedTransactionData; + }, + }; + } + public poolIdByMaker(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('poolIdByMaker(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('poolIdByMaker(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('poolIdByMaker(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public poolStatsByEpoch( + index_0: string, + index_1: BigNumber, + ): ContractFunctionObj<[BigNumber, BigNumber, BigNumber]> { + const self = (this as any) as StakingContract; + assert.isString('index_0', index_0); + assert.isBigNumber('index_1', index_1); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('poolStatsByEpoch(bytes32,uint256)', [ + index_0, + index_1, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('poolStatsByEpoch(bytes32,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('poolStatsByEpoch(bytes32,uint256)', [ + index_0, + index_1, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Removes authorizion of an address. + * @param target Address to remove authorization from. + */ + public removeAuthorizedAddress(target: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('target', target); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Removes authorizion of an address. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + public removeAuthorizedAddressAtIndex(target: string, index: BigNumber): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('target', target); + assert.isBigNumber('index', index); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'removeAuthorizedAddressAtIndex(address,uint256)', + [target.toLowerCase(), index], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Removes an existing exchange address + * @param addr Address of exchange contract to remove + */ + public removeExchangeAddress(addr: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('addr', addr); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('removeExchangeAddress(address)', [addr.toLowerCase()]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('removeExchangeAddress(address)', [addr.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; + }, + 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 encodedData = self._strictEncodeArguments('removeExchangeAddress(address)', [addr.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeExchangeAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('removeExchangeAddress(address)', [ + addr.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public rewardDelegatedStakeWeight(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('rewardDelegatedStakeWeight()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('rewardDelegatedStakeWeight()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('rewardDelegatedStakeWeight()', []); + return abiEncodedTransactionData; + }, + }; + } + public rewardsByPoolId(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('rewardsByPoolId(bytes32)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('rewardsByPoolId(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('rewardsByPoolId(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Set all configurable parameters at once. + * @param _epochDurationInSeconds Minimum seconds between epochs. + * @param _rewardDelegatedStakeWeight How much delegated stake is weighted vs + * operator stake, in ppm. + * @param _minimumPoolStake Minimum amount of stake required in a pool to + * collect rewards. + * @param _cobbDouglasAlphaNumerator Numerator for cobb douglas alpha factor. + * @param _cobbDouglasAlphaDenominator Denominator for cobb douglas alpha + * factor. + */ + public setParams( + _epochDurationInSeconds: BigNumber, + _rewardDelegatedStakeWeight: number | BigNumber, + _minimumPoolStake: BigNumber, + _cobbDouglasAlphaNumerator: number | BigNumber, + _cobbDouglasAlphaDenominator: number | BigNumber, + ): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isBigNumber('_epochDurationInSeconds', _epochDurationInSeconds); + assert.isNumberOrBigNumber('_rewardDelegatedStakeWeight', _rewardDelegatedStakeWeight); + assert.isBigNumber('_minimumPoolStake', _minimumPoolStake); + assert.isNumberOrBigNumber('_cobbDouglasAlphaNumerator', _cobbDouglasAlphaNumerator); + assert.isNumberOrBigNumber('_cobbDouglasAlphaDenominator', _cobbDouglasAlphaDenominator); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('setParams(uint256,uint32,uint256,uint32,uint32)', [ + _epochDurationInSeconds, + _rewardDelegatedStakeWeight, + _minimumPoolStake, + _cobbDouglasAlphaNumerator, + _cobbDouglasAlphaDenominator, + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('setParams(uint256,uint32,uint256,uint32,uint32)', [ + _epochDurationInSeconds, + _rewardDelegatedStakeWeight, + _minimumPoolStake, + _cobbDouglasAlphaNumerator, + _cobbDouglasAlphaDenominator, + ]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('setParams(uint256,uint32,uint256,uint32,uint32)', [ + _epochDurationInSeconds, + _rewardDelegatedStakeWeight, + _minimumPoolStake, + _cobbDouglasAlphaNumerator, + _cobbDouglasAlphaDenominator, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('setParams(uint256,uint32,uint256,uint32,uint32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'setParams(uint256,uint32,uint256,uint32,uint32)', + [ + _epochDurationInSeconds, + _rewardDelegatedStakeWeight, + _minimumPoolStake, + _cobbDouglasAlphaNumerator, + _cobbDouglasAlphaDenominator, + ], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Stake ZRX tokens. Tokens are deposited into the ZRX Vault. + * Unstake to retrieve the ZRX. Stake is in the 'Active' status. + * @param amount of ZRX to stake. + */ + public stake(amount: BigNumber): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isBigNumber('amount', amount); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('stake(uint256)', [amount]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('stake(uint256)', [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; + }, + 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 encodedData = self._strictEncodeArguments('stake(uint256)', [amount]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('stake(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('stake(uint256)', [amount]); + return abiEncodedTransactionData; + }, + }; + } + public stakingContract(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('stakingContract()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('stakingContract()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('stakingContract()', []); + return abiEncodedTransactionData; + }, + }; + } + public transferOwnership(newOwner: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('newOwner', newOwner); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Unstake. Tokens are withdrawn from the ZRX Vault and returned to + * the staker. Stake must be in the 'undelegated' status in both the + * current and next epoch in order to be unstaked. + * @param amount of ZRX to unstake. + */ + public unstake(amount: BigNumber): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isBigNumber('amount', amount); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('unstake(uint256)', [amount]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('unstake(uint256)', [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; + }, + 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 encodedData = self._strictEncodeArguments('unstake(uint256)', [amount]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('unstake(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('unstake(uint256)', [amount]); + return abiEncodedTransactionData; + }, + }; + } + public validExchanges(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('validExchanges(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('validExchanges(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('validExchanges(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public wethReservedForPoolRewards(): ContractFunctionObj { + const self = (this as any) as StakingContract; + + return { + 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 encodedData = self._strictEncodeArguments('wethReservedForPoolRewards()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('wethReservedForPoolRewards()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('wethReservedForPoolRewards()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Withdraws the caller's WETH rewards that have accumulated + * until the last epoch. + * @param poolId Unique id of pool. + */ + public withdrawDelegatorRewards(poolId: string): ContractTxFunctionObj { + const self = (this as any) as StakingContract; + assert.isString('poolId', poolId); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [poolId]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [poolId]); + 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; + }, + 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 encodedData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [poolId]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withdrawDelegatorRewards(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('withdrawDelegatorRewards(bytes32)', [ + poolId, + ]); + return abiEncodedTransactionData; + }, + }; + } + + /** + * Subscribe to an event type emitted by the Staking contract. + * @param eventName The Staking 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: StakingEvents, + indexFilterValues: IndexedFilterValues, + callback: EventCallback, + isVerbose: boolean = false, + blockPollingIntervalMs?: number, + ): string { + assert.doesBelongToStringEnum('eventName', eventName, StakingEvents); + assert.doesConformToSchema('indexFilterValues', indexFilterValues, schemas.indexFilterValuesSchema); + assert.isFunction('callback', callback); + const subscriptionToken = this._subscriptionManager.subscribe( + this.address, + eventName, + indexFilterValues, + StakingContract.ABI(), + callback, + isVerbose, + blockPollingIntervalMs, + ); + return subscriptionToken; } /** * Cancel a subscription @@ -6426,6 +5595,12 @@ export class StakingContract extends BaseContract { StakingContract.ABI(), this._web3Wrapper, ); + StakingContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/staking_proxy.ts b/packages/abi-gen-wrappers/src/generated-wrappers/staking_proxy.ts index 0083595a0e..f30c275c1f 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/staking_proxy.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/staking_proxy.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -75,2049 +78,7 @@ export class StakingProxyContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('target', target); - const self = (this as any) as StakingProxyContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.addAuthorizedAddress.callAsync(target, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('target', target); - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.addAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingProxyContract; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(target: string): string { - assert.isString('target', target); - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ - target.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - public aggregatedStatsByEpoch = { - /** - * 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<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { - 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('aggregatedStatsByEpoch(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('aggregatedStatsByEpoch(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]>( - rawCallResult, - ); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Asserts that an epoch is between 5 and 30 days long. - */ - public assertValidStorageParams = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('assertValidStorageParams()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('assertValidStorageParams()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Attach a staking contract; future calls will be delegated to the staking contract. Note that this is callable only by an authorized address. - */ - public attachStakingContract = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param _stakingContract Address of staking contract. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - _stakingContract: string, - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('_stakingContract', _stakingContract); - const self = (this as any) as StakingProxyContract; - const encodedData = self._strictEncodeArguments('attachStakingContract(address)', [ - _stakingContract.toLowerCase(), - ]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.attachStakingContract.callAsync(_stakingContract, txDataWithDefaults); - } - - 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 _stakingContract Address of staking 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( - _stakingContract: string, - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('_stakingContract', _stakingContract); - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.attachStakingContract.sendTransactionAsync( - _stakingContract.toLowerCase(), - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param _stakingContract Address of staking contract. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(_stakingContract: string, txData?: Partial | undefined): Promise { - assert.isString('_stakingContract', _stakingContract); - const self = (this as any) as StakingProxyContract; - const encodedData = self._strictEncodeArguments('attachStakingContract(address)', [ - _stakingContract.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 _stakingContract Address of staking contract. - */ - async callAsync( - _stakingContract: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('_stakingContract', _stakingContract); - 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('attachStakingContract(address)', [ - _stakingContract.toLowerCase(), - ]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('attachStakingContract(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 _stakingContract Address of staking contract. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(_stakingContract: string): string { - assert.isString('_stakingContract', _stakingContract); - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('attachStakingContract(address)', [ - _stakingContract.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('attachStakingContract(address)'); - return abiEncoder.getSelector(); - }, - }; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('authorized(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Batch executes a series of calls to the staking contract. - */ - public batchExecute = { - /** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - * @param data An array of data that encodes a sequence of functions to - * call in the staking contracts. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async sendTransactionAsync( - data: string[], - txData?: Partial | undefined, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isArray('data', data); - const self = (this as any) as StakingProxyContract; - const encodedData = self._strictEncodeArguments('batchExecute(bytes[])', [data]); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.batchExecute.callAsync(data, txDataWithDefaults); - } - - 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 data An array of data that encodes a sequence of functions to - * call in the staking contracts. - * @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( - data: string[], - txData?: Partial, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isArray('data', data); - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.batchExecute.sendTransactionAsync(data, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.timeoutMs, - ); - })(), - ); - }, - /** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - * @param data An array of data that encodes a sequence of functions to - * call in the staking contracts. - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ - async estimateGasAsync(data: string[], txData?: Partial | undefined): Promise { - assert.isArray('data', data); - const self = (this as any) as StakingProxyContract; - const encodedData = self._strictEncodeArguments('batchExecute(bytes[])', [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 data An array of data that encodes a sequence of functions to - * call in the staking contracts. - */ - async callAsync( - data: string[], - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isArray('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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('batchExecute(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('batchExecute(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 data An array of data that encodes a sequence of functions to - * call in the staking contracts. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(data: string[]): string { - assert.isArray('data', data); - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('batchExecute(bytes[])', [data]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('batchExecute(bytes[])'); - return abiEncoder.getSelector(); - }, - }; - public cobbDouglasAlphaDenominator = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('cobbDouglasAlphaDenominator()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaDenominator()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public cobbDouglasAlphaNumerator = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('cobbDouglasAlphaNumerator()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaNumerator()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public currentEpoch = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('currentEpoch()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('currentEpoch()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public currentEpochStartTimeInSeconds = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('currentEpochStartTimeInSeconds()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('currentEpochStartTimeInSeconds()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * Detach the current staking contract. Note that this is callable only by an authorized address. - */ - public detachStakingContract = { - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const self = (this as any) as StakingProxyContract; - const encodedData = self._strictEncodeArguments('detachStakingContract()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.detachStakingContract.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.detachStakingContract.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('detachStakingContract()', []); - 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('detachStakingContract()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('detachStakingContract()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('detachStakingContract()', []); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('detachStakingContract()'); - return abiEncoder.getSelector(); - }, - }; - public epochDurationInSeconds = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('epochDurationInSeconds()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('epochDurationInSeconds()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public lastPoolId = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('lastPoolId()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('lastPoolId()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public minimumPoolStake = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('minimumPoolStake()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('minimumPoolStake()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('owner()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public poolIdByMaker = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('poolIdByMaker(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('poolIdByMaker(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public poolStatsByEpoch = { - /** - * 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: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[BigNumber, BigNumber, BigNumber]> { - assert.isString('index_0', index_0); - assert.isBigNumber('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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('poolStatsByEpoch(bytes32,uint256)', [index_0, index_1]); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('poolStatsByEpoch(bytes32,uint256)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber]>(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('target', target); - const self = (this as any) as StakingProxyContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.removeAuthorizedAddress.callAsync(target, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('target', target); - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.removeAuthorizedAddress.sendTransactionAsync(target.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingProxyContract; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(target: string): string { - assert.isString('target', target); - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ - target.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); - return abiEncoder.getSelector(); - }, - }; - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('target', target); - assert.isBigNumber('index', index); - const self = (this as any) as StakingProxyContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.removeAuthorizedAddressAtIndex.callAsync(target, index, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('target', target); - assert.isBigNumber('index', index); - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.removeAuthorizedAddressAtIndex.sendTransactionAsync( - target.toLowerCase(), - index, - txData, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingProxyContract; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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. - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(target: string, index: BigNumber): string { - assert.isString('target', target); - assert.isBigNumber('index', index); - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'removeAuthorizedAddressAtIndex(address,uint256)', - [target.toLowerCase(), index], - ); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - public rewardDelegatedStakeWeight = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('rewardDelegatedStakeWeight()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('rewardDelegatedStakeWeight()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public rewardsByPoolId = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('rewardsByPoolId(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('rewardsByPoolId(bytes32)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public stakingContract = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('stakingContract()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('stakingContract()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isString('newOwner', newOwner); - const self = (this as any) as StakingProxyContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferOwnership.callAsync(newOwner, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isString('newOwner', newOwner); - const self = (this as any) as StakingProxyContract; - const txHashPromise = self.transferOwnership.sendTransactionAsync(newOwner.toLowerCase(), txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 StakingProxyContract; - 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 StakingProxyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(newOwner: string): string { - assert.isString('newOwner', newOwner); - const self = (this as any) as StakingProxyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ - newOwner.toLowerCase(), - ]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as StakingProxyContract; - const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); - return abiEncoder.getSelector(); - }, - }; - public validExchanges = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('validExchanges(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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('validExchanges(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - public wethReservedForPoolRewards = { - /** - * 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 StakingProxyContract; - const encodedData = self._strictEncodeArguments('wethReservedForPoolRewards()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('wethReservedForPoolRewards()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -2737,6 +698,1822 @@ export class StakingProxyContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = StakingProxyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as StakingProxyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as StakingProxyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as StakingProxyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * Authorizes an address. + * @param target Address to authorize. + */ + public addAuthorizedAddress(target: string): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('target', target); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('addAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('addAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public aggregatedStatsByEpoch( + index_0: BigNumber, + ): ContractFunctionObj<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { + const self = (this as any) as StakingProxyContract; + assert.isBigNumber('index_0', index_0); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber, BigNumber, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('aggregatedStatsByEpoch(uint256)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('aggregatedStatsByEpoch(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + [BigNumber, BigNumber, BigNumber, BigNumber, BigNumber] + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('aggregatedStatsByEpoch(uint256)', [ + index_0, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Asserts that an epoch is between 5 and 30 days long. + */ + public assertValidStorageParams(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('assertValidStorageParams()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('assertValidStorageParams()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('assertValidStorageParams()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Attach a staking contract; future calls will be delegated to the staking contract. Note that this is callable only by an authorized address. + * @param _stakingContract Address of staking contract. + */ + public attachStakingContract(_stakingContract: string): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('_stakingContract', _stakingContract); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('attachStakingContract(address)', [ + _stakingContract.toLowerCase(), + ]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('attachStakingContract(address)', [ + _stakingContract.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; + }, + 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 encodedData = self._strictEncodeArguments('attachStakingContract(address)', [ + _stakingContract.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('attachStakingContract(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('attachStakingContract(address)', [ + _stakingContract.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public authorities(index_0: BigNumber): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isBigNumber('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorities(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('authorities(uint256)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + public authorized(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('authorized(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('authorized(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('authorized(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Batch executes a series of calls to the staking contract. + * @param data An array of data that encodes a sequence of functions to + * call in the staking contracts. + */ + public batchExecute(data: string[]): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isArray('data', data); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('batchExecute(bytes[])', [data]); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('batchExecute(bytes[])', [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; + }, + 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 encodedData = self._strictEncodeArguments('batchExecute(bytes[])', [data]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('batchExecute(bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('batchExecute(bytes[])', [data]); + return abiEncodedTransactionData; + }, + }; + } + public cobbDouglasAlphaDenominator(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('cobbDouglasAlphaDenominator()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaDenominator()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('cobbDouglasAlphaDenominator()', []); + return abiEncodedTransactionData; + }, + }; + } + public cobbDouglasAlphaNumerator(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('cobbDouglasAlphaNumerator()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('cobbDouglasAlphaNumerator()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('cobbDouglasAlphaNumerator()', []); + return abiEncodedTransactionData; + }, + }; + } + public currentEpoch(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('currentEpoch()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('currentEpoch()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('currentEpoch()', []); + return abiEncodedTransactionData; + }, + }; + } + public currentEpochStartTimeInSeconds(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('currentEpochStartTimeInSeconds()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('currentEpochStartTimeInSeconds()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('currentEpochStartTimeInSeconds()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Detach the current staking contract. Note that this is callable only by an authorized address. + */ + public detachStakingContract(): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('detachStakingContract()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('detachStakingContract()', []); + 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; + }, + 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 encodedData = self._strictEncodeArguments('detachStakingContract()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('detachStakingContract()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('detachStakingContract()', []); + return abiEncodedTransactionData; + }, + }; + } + public epochDurationInSeconds(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('epochDurationInSeconds()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('epochDurationInSeconds()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('epochDurationInSeconds()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Gets all authorized addresses. + * @returns Array of authorized addresses. + */ + public getAuthorizedAddresses(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('getAuthorizedAddresses()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('getAuthorizedAddresses()', []); + return abiEncodedTransactionData; + }, + }; + } + public lastPoolId(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('lastPoolId()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('lastPoolId()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('lastPoolId()', []); + return abiEncodedTransactionData; + }, + }; + } + public minimumPoolStake(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('minimumPoolStake()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('minimumPoolStake()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('minimumPoolStake()', []); + return abiEncodedTransactionData; + }, + }; + } + public owner(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('owner()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('owner()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('owner()', []); + return abiEncodedTransactionData; + }, + }; + } + public poolIdByMaker(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('poolIdByMaker(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('poolIdByMaker(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('poolIdByMaker(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public poolStatsByEpoch( + index_0: string, + index_1: BigNumber, + ): ContractFunctionObj<[BigNumber, BigNumber, BigNumber]> { + const self = (this as any) as StakingProxyContract; + assert.isString('index_0', index_0); + assert.isBigNumber('index_1', index_1); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[BigNumber, BigNumber, BigNumber]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('poolStatsByEpoch(bytes32,uint256)', [ + index_0, + index_1, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('poolStatsByEpoch(bytes32,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, BigNumber, BigNumber]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('poolStatsByEpoch(bytes32,uint256)', [ + index_0, + index_1, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Removes authorizion of an address. + * @param target Address to remove authorization from. + */ + public removeAuthorizedAddress(target: string): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('target', target); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddress(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('removeAuthorizedAddress(address)', [ + target.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Removes authorizion of an address. + * @param target Address to remove authorization from. + * @param index Index of target in authorities array. + */ + public removeAuthorizedAddressAtIndex(target: string, index: BigNumber): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('target', target); + assert.isBigNumber('index', index); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('removeAuthorizedAddressAtIndex(address,uint256)', [ + target.toLowerCase(), + index, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('removeAuthorizedAddressAtIndex(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'removeAuthorizedAddressAtIndex(address,uint256)', + [target.toLowerCase(), index], + ); + return abiEncodedTransactionData; + }, + }; + } + public rewardDelegatedStakeWeight(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('rewardDelegatedStakeWeight()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('rewardDelegatedStakeWeight()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('rewardDelegatedStakeWeight()', []); + return abiEncodedTransactionData; + }, + }; + } + public rewardsByPoolId(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('rewardsByPoolId(bytes32)', [index_0]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('rewardsByPoolId(bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('rewardsByPoolId(bytes32)', [index_0]); + return abiEncodedTransactionData; + }, + }; + } + public stakingContract(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('stakingContract()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('stakingContract()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('stakingContract()', []); + return abiEncodedTransactionData; + }, + }; + } + public transferOwnership(newOwner: string): ContractTxFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('newOwner', newOwner); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferOwnership(address)', [newOwner.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferOwnership(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferOwnership(address)', [ + newOwner.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public validExchanges(index_0: string): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('validExchanges(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('validExchanges(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('validExchanges(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public wethReservedForPoolRewards(): ContractFunctionObj { + const self = (this as any) as StakingProxyContract; + + return { + 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 encodedData = self._strictEncodeArguments('wethReservedForPoolRewards()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('wethReservedForPoolRewards()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('wethReservedForPoolRewards()', []); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the StakingProxy contract. * @param eventName The StakingProxy contract event you would like to subscribe to. @@ -2826,6 +2603,12 @@ export class StakingProxyContract extends BaseContract { StakingProxyContract.ABI(), this._web3Wrapper, ); + StakingProxyContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts b/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts index ee4032ab99..a8f5b15c5f 100644 --- a/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts +++ b/packages/abi-gen-wrappers/src/generated-wrappers/weth9.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -74,1089 +77,7 @@ export class WETH9Contract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('name()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.approve.callAsync(guy, wad, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as WETH9Contract; - const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('totalSupply()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transferFrom.callAsync(src, dst, wad, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, - opts, - ); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as WETH9Contract; - const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.withdraw.callAsync(wad, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('wad', wad); - const self = (this as any) as WETH9Contract; - const txHashPromise = self.withdraw.sendTransactionAsync(wad, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(wad: BigNumber): string { - assert.isBigNumber('wad', wad); - const self = (this as any) as WETH9Contract; - const abiEncodedTransactionData = self._strictEncodeArguments('withdraw(uint256)', [wad]); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as WETH9Contract; - const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('decimals()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('symbol()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.transfer.callAsync(dst, wad, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): 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, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - 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; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as WETH9Contract; - const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): 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(); - } - - if (opts.shouldValidate !== false) { - await self.deposit.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as WETH9Contract; - const txHashPromise = self.deposit.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as WETH9Contract; - const abiEncodedTransactionData = self._strictEncodeArguments('deposit()', []); - return abiEncodedTransactionData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as WETH9Contract; - const abiEncoder = self._lookupAbiEncoder('deposit()'); - return abiEncoder.getSelector(); - }, - }; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue(rawCallResult); - // tslint:enable boolean-naming - return result; - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -1513,6 +434,883 @@ export class WETH9Contract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = WETH9Contract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as WETH9Contract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + public name(): ContractFunctionObj { + const self = (this as any) as WETH9Contract; + + return { + 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 encodedData = self._strictEncodeArguments('name()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('name()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('name()', []); + return abiEncodedTransactionData; + }, + }; + } + public approve(guy: string, wad: BigNumber): ContractTxFunctionObj { + const self = (this as any) as WETH9Contract; + assert.isString('guy', guy); + assert.isBigNumber('wad', wad); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('approve(address,uint256)', [guy.toLowerCase(), wad]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('approve(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('approve(address,uint256)', [ + guy.toLowerCase(), + wad, + ]); + return abiEncodedTransactionData; + }, + }; + } + public totalSupply(): ContractFunctionObj { + const self = (this as any) as WETH9Contract; + + return { + 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 encodedData = self._strictEncodeArguments('totalSupply()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('totalSupply()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('totalSupply()', []); + return abiEncodedTransactionData; + }, + }; + } + public transferFrom(src: string, dst: string, wad: BigNumber): ContractTxFunctionObj { + const self = (this as any) as WETH9Contract; + assert.isString('src', src); + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + src.toLowerCase(), + dst.toLowerCase(), + wad, + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transferFrom(address,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transferFrom(address,address,uint256)', [ + src.toLowerCase(), + dst.toLowerCase(), + wad, + ]); + return abiEncodedTransactionData; + }, + }; + } + public withdraw(wad: BigNumber): ContractTxFunctionObj { + const self = (this as any) as WETH9Contract; + assert.isBigNumber('wad', wad); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + return abiEncodedTransactionData; + }, + }; + } + public decimals(): ContractFunctionObj { + const self = (this as any) as WETH9Contract; + + return { + 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 encodedData = self._strictEncodeArguments('decimals()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('decimals()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('decimals()', []); + return abiEncodedTransactionData; + }, + }; + } + public balanceOf(index_0: string): ContractFunctionObj { + const self = (this as any) as WETH9Contract; + assert.isString('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('balanceOf(address)', [index_0.toLowerCase()]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('balanceOf(address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('balanceOf(address)', [ + index_0.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + public symbol(): ContractFunctionObj { + const self = (this as any) as WETH9Contract; + + return { + 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 encodedData = self._strictEncodeArguments('symbol()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('symbol()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('symbol()', []); + return abiEncodedTransactionData; + }, + }; + } + public transfer(dst: string, wad: BigNumber): ContractTxFunctionObj { + const self = (this as any) as WETH9Contract; + assert.isString('dst', dst); + assert.isBigNumber('wad', wad); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('transfer(address,uint256)', [dst.toLowerCase(), wad]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('transfer(address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('transfer(address,uint256)', [ + dst.toLowerCase(), + wad, + ]); + return abiEncodedTransactionData; + }, + }; + } + public deposit(): ContractTxFunctionObj { + const self = (this as any) as WETH9Contract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('deposit()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('deposit()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('deposit()', []); + return abiEncodedTransactionData; + }, + }; + } + public allowance(index_0: string, index_1: string): ContractFunctionObj { + const self = (this as any) as WETH9Contract; + assert.isString('index_0', index_0); + assert.isString('index_1', index_1); + + return { + 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 encodedData = self._strictEncodeArguments('allowance(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('allowance(address,address)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('allowance(address,address)', [ + index_0.toLowerCase(), + index_1.toLowerCase(), + ]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the WETH9 contract. * @param eventName The WETH9 contract event you would like to subscribe to. @@ -1602,6 +1400,12 @@ export class WETH9Contract extends BaseContract { WETH9Contract.ABI(), this._web3Wrapper, ); + WETH9Contract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen-wrappers/src/index.ts b/packages/abi-gen-wrappers/src/index.ts index 71aa0b8454..be9d79a8bd 100644 --- a/packages/abi-gen-wrappers/src/index.ts +++ b/packages/abi-gen-wrappers/src/index.ts @@ -102,3 +102,11 @@ export { } from './generated-wrappers/coordinator_registry'; export * from '@0x/contract-addresses'; +export { + ContractEvent, + SendTransactionOpts, + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SubscriptionErrors, +} from '@0x/base-contract'; diff --git a/packages/abi-gen/CHANGELOG.json b/packages/abi-gen/CHANGELOG.json index 5ac4ed7b22..fe81217934 100644 --- a/packages/abi-gen/CHANGELOG.json +++ b/packages/abi-gen/CHANGELOG.json @@ -1,4 +1,13 @@ [ + { + "version": "4.4.0-beta.2", + "changes": [ + { + "note": "Refactored TS wrapper templates to result in a more succint interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details.", + "pr": 2284 + } + ] + }, { "version": "4.4.0-beta.1", "changes": [ diff --git a/packages/abi-gen/src/index.ts b/packages/abi-gen/src/index.ts index ef65285cd8..8a18eaf701 100644 --- a/packages/abi-gen/src/index.ts +++ b/packages/abi-gen/src/index.ts @@ -1,10 +1,8 @@ #!/usr/bin/env node - -import { execSync } from 'child_process'; - import { AbiEncoder, abiUtils, logUtils } from '@0x/utils'; import chalk from 'chalk'; import * as changeCase from 'change-case'; +import { execSync } from 'child_process'; import * as cliFormat from 'cli-format'; import { AbiDefinition, @@ -44,10 +42,6 @@ const args = yargs normalize: true, demandOption: true, }) - .option('debug', { - describe: 'Includes debug functions in the wrappers such as `getABIDecodedTransactionData`', - type: 'boolean', - }) .option('partials', { describe: 'Glob pattern for the partial template files', type: 'string', diff --git a/packages/abi-gen/src/types.ts b/packages/abi-gen/src/types.ts index dd1c8d9693..b02259f754 100644 --- a/packages/abi-gen/src/types.ts +++ b/packages/abi-gen/src/types.ts @@ -1,5 +1,4 @@ import { ContractAbi, EventAbi, MethodAbi } from 'ethereum-types'; - export enum ParamKind { Input = 'input', Output = 'output', diff --git a/packages/abi-gen/templates/TypeScript/contract.handlebars b/packages/abi-gen/templates/TypeScript/contract.handlebars index 2a2d56f845..8a06e04f6d 100644 --- a/packages/abi-gen/templates/TypeScript/contract.handlebars +++ b/packages/abi-gen/templates/TypeScript/contract.handlebars @@ -1,8 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract{{#if events}}, - SubscriptionManager{{/if}},PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + {{#if events~}}SubscriptionManager,{{/if~}} + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -20,12 +28,13 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { AwaitTransactionSuccessOpts, EventCallback, IndexedFilterValues, SendTransactionOpts, SimpleContractArtifact } from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; // tslint:enable:no-unused-variable + {{#if events}} export type {{contractName}}EventArgs = {{#each events}} @@ -56,27 +65,12 @@ export class {{contractName}}Contract extends BaseContract { {{else~}} public static deployedBytecode = '{{this.deployedBytecode}}'; {{/ifEquals~}} + private readonly _methodABIIndex: { [name:string]: number } = {}; + {{#if events~}} + private readonly _subscriptionManager: SubscriptionManager<{{contractName}}EventArgs, {{contractName}}Events>; + {{/if~}} -{{#each methods}} - {{#if this.devdoc.details}} - /** - * {{formatDocstringForMethodTs this.devdoc.details}} - */ - {{/if}} - public {{languageSpecificName}} = { - {{^this.constant}} - {{> method_tx contractName=../contractName}} - {{/this.constant}} - {{#ifEquals this.stateMutability "pure"}} - {{> method_call_pure contractName=../contractName}} - {{else}} - {{> method_call contractName=../contractName}} - {{/ifEquals}} - {{> method_abi_helper contractName=../contractName debug=../debug}} - }; -{{/each}} -{{#if events}}private readonly _subscriptionManager: SubscriptionManager<{{contractName}}EventArgs, {{contractName}}Events>; -{{/if}}public static async deployFrom0xArtifactAsync( + public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, txDefaults: Partial, @@ -169,7 +163,63 @@ export class {{contractName}}Contract extends BaseContract { {{/each}} ] as ContractAbi; return abi; - }{{#if events}} + } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = {{contractName}}Contract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as {{contractName}}Contract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as {{contractName}}Contract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as {{contractName}}Contract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + {{#each methods}} + {{#if this.devdoc.details}} + /** + * {{formatDocstringForMethodTs this.devdoc.details}} + {{> params_docstring inputs=inputs docstrings=devdoc.params}} + {{#if devdoc.return}} + * @returns {{devdoc.return}} + {{/if}} + */ + {{/if}} + public {{languageSpecificName}}( + {{> typed_params inputs=this.inputs}} + ): Contract{{^this.constant}}Tx{{/this.constant}}FunctionObj<{{> return_type outputs=outputs ~}}> { + const self = this as any as {{../contractName}}Contract; + {{#each inputs}} + {{#assertionType name type}}{{/assertionType}} + {{/each}} + + return { + {{^this.constant}} + {{> method_tx}} + {{/this.constant}} + {{> method_call stateMutability=this.stateMutability}} + } + }; + {{/each}} + + {{#if events}} /** * Subscribe to an event type emitted by the {{contractName}} contract. * @param eventName The {{contractName}} contract event you would like to subscribe to. @@ -246,11 +296,18 @@ export class {{contractName}}Contract extends BaseContract { deployedBytecode: string | undefined = {{contractName}}Contract.deployedBytecode, ) { super('{{contractName}}', {{contractName}}Contract.ABI(), address, supportedProvider, txDefaults, logDecodeDependencies, deployedBytecode); - classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']);{{#if events}} + classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + {{#if events~}} this._subscriptionManager = new SubscriptionManager<{{contractName}}EventArgs, {{contractName}}Events>( {{contractName}}Contract.ABI(), this._web3Wrapper, - );{{/if}} + );{{/if~}} + {{contractName}}Contract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }) } } diff --git a/packages/abi-gen/templates/TypeScript/partials/method_abi_helper.handlebars b/packages/abi-gen/templates/TypeScript/partials/method_abi_helper.handlebars deleted file mode 100644 index 64780645ea..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/method_abi_helper.handlebars +++ /dev/null @@ -1,86 +0,0 @@ -{{!-- if ((NOT constant) AND (NOT debug)), to avoid repetition bbecause we use all 4 functions if (debug) --}} -{{^if constant~}} -{{^if debug~}} -/** - * 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). -{{> params_docstring inputs=inputs docstrings=devdoc.params}} - * @returns The ABI encoded transaction data as a string - */ -getABIEncodedTransactionData( - {{> typed_params inputs=inputs}} - ): string { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - const self = this as any as {{contractName}}Contract; - const abiEncodedTransactionData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); - return abiEncodedTransactionData; -}, -/** - * Returns the 4 byte function selector as a hex string. - */ -getSelector(): string { - const self = this as any as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder('{{this.functionSignature}}'); - return abiEncoder.getSelector(); -} -{{/if~}} -{{/if~}} - -{{#if debug~}} -/** - * 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). -{{> params_docstring inputs=inputs docstrings=devdoc.params}} - * @returns The ABI encoded transaction data as a string - */ -getABIEncodedTransactionData( - {{> typed_params inputs=inputs}} - ): string { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - const self = this as any as {{contractName}}Contract; - const abiEncodedTransactionData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); - return abiEncodedTransactionData; -}, -/** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ -getABIDecodedTransactionData( - callData: string -): ({{> return_type outputs=inputs ~}}) { - const self = this as any as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder('{{this.functionSignature}}'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<{{> return_type outputs=inputs}}>(callData); - return abiDecodedCallData; -}, -/** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ -getABIDecodedReturnData( - returnData: string -): ({{> return_type outputs=outputs ~}}) { - const self = this as any as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder('{{this.functionSignature}}'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{{> return_type outputs=outputs}}>(returnData); - return abiDecodedReturnData; -}, -/** - * Returns the 4 byte function selector as a hex string. - */ -getSelector(): string { - const self = this as any as {{contractName}}Contract; - const abiEncoder = self._lookupAbiEncoder('{{this.functionSignature}}'); - return abiEncoder.getSelector(); -} -{{/if}} diff --git a/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars b/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars index cfb8faf7d1..25e07f1188 100644 --- a/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars +++ b/packages/abi-gen/templates/TypeScript/partials/method_call.handlebars @@ -1,20 +1,7 @@ -/** - * 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. -{{> params_docstring inputs=inputs docstrings=devdoc.params}} -{{#if devdoc.return}} - * @returns {{devdoc.return}} -{{/if}} - */ async callAsync( -{{> typed_params inputs=inputs}} callData: Partial = {}, defaultBlock?: BlockParam, ): Promise<{{> return_type outputs=outputs}}> { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ schemas.addressSchema, schemas.numberSchema, @@ -23,8 +10,14 @@ async callAsync( if (defaultBlock !== undefined) { assert.isBlockParam('defaultBlock', defaultBlock); } - const self = this as any as {{contractName}}Contract; const encodedData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); + let rawCallResult; + + {{#ifEquals this.stateMutability "pure"}} + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + {{else}} const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { to: self.address, @@ -34,13 +27,14 @@ async callAsync( self._web3Wrapper.getContractDefaults(), ); callDataWithDefaults.from = callDataWithDefaults.from ? callDataWithDefaults.from.toLowerCase() : callDataWithDefaults.from; - let rawCallResult; try { rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + {{/ifEquals}} } catch (err) { BaseContract._throwIfThrownErrorIsRevertError(err); throw err; } + BaseContract._throwIfCallResultIsRevertError(rawCallResult); const abiEncoder = self._lookupAbiEncoder('{{this.functionSignature}}'); // tslint:disable boolean-naming @@ -48,3 +42,7 @@ async callAsync( // tslint:enable boolean-naming return result; }, +getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); + return abiEncodedTransactionData; +}, diff --git a/packages/abi-gen/templates/TypeScript/partials/method_call_pure.handlebars b/packages/abi-gen/templates/TypeScript/partials/method_call_pure.handlebars deleted file mode 100644 index 2ec68190f9..0000000000 --- a/packages/abi-gen/templates/TypeScript/partials/method_call_pure.handlebars +++ /dev/null @@ -1,44 +0,0 @@ -/** - * 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. -{{> params_docstring inputs=inputs docstrings=devdoc.params}} -{{#if devdoc.return}} - * @returns {{devdoc.return}} -{{/if}} - */ -async callAsync( -{{> typed_params inputs=inputs}} - callData: Partial = {}, - defaultBlock?: BlockParam, -): Promise<{{> return_type outputs=outputs}}> { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - 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 {{contractName}}Contract; - const encodedData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('{{this.functionSignature}}'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{{> return_type outputs=outputs}}>(rawCallResult); - // tslint:enable boolean-naming - return result; -}, diff --git a/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars b/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars index de4e7eb324..6262c3d39e 100644 --- a/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars +++ b/packages/abi-gen/templates/TypeScript/partials/method_tx.handlebars @@ -1,19 +1,7 @@ -/** - * Sends an Ethereum transaction executing this method with the supplied parameters. This is a read/write - * Ethereum operation and will cost gas. - {{> params_docstring inputs=inputs docstrings=devdoc.params}} - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ async sendTransactionAsync( -{{> typed_params inputs=inputs}} -txData?: Partial | undefined, -opts: SendTransactionOpts = { shouldValidate: true }, + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, ): Promise { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - const self = this as any as {{contractName}}Contract; const encodedData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { @@ -28,10 +16,7 @@ opts: SendTransactionOpts = { shouldValidate: true }, } if (opts.shouldValidate !== false) { - await self.{{languageSpecificName}}.callAsync( - {{#each inputs~}} - {{name}}, - {{/each~}} + await this.callAsync( txDataWithDefaults, ); } @@ -39,28 +24,11 @@ opts: SendTransactionOpts = { shouldValidate: true }, 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. - {{> params_docstring inputs=inputs docstrings=devdoc.params}} - * @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( -{{> typed_params inputs=inputs}} txData?: Partial, opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, ): PromiseWithTransactionHash { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - const self = this as any as {{contractName}}Contract; - {{#if inputs}} - const txHashPromise = self.{{languageSpecificName}}.sendTransactionAsync({{> normalized_params input=inputs}}, txData, opts); - {{else}} - const txHashPromise = self.{{languageSpecificName}}.sendTransactionAsync(txData, opts); - {{/if}} + const txHashPromise = this.sendTransactionAsync(txData, opts); return new PromiseWithTransactionHash( txHashPromise, (async (): Promise => { @@ -73,20 +41,9 @@ awaitTransactionSuccessAsync( })(), ); }, -/** - * Estimates the gas cost of sending an Ethereum transaction calling this method with these arguments. - {{> params_docstring inputs=inputs docstrings=devdoc.params}} - * @param txData Additional data for transaction - * @returns The hash of the transaction - */ async estimateGasAsync( -{{> typed_params inputs=inputs}} txData?: Partial | undefined, ): Promise { - {{#each inputs}} - {{#assertionType name type}}{{/assertionType}} - {{/each}} - const self = this as any as {{contractName}}Contract; const encodedData = self._strictEncodeArguments('{{this.functionSignature}}', [{{> normalized_params inputs=inputs}}]); const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( { diff --git a/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts b/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts index 71fd822b91..b1ec054a4b 100644 --- a/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts +++ b/packages/abi-gen/test-cli/output/typescript/abi_gen_dummy.ts @@ -1,7 +1,16 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, SubscriptionManager, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + SubscriptionManager, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -19,13 +28,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -57,2974 +60,7 @@ export class AbiGenDummyContract extends BaseContract { */ public static deployedBytecode = '0x608060405234801561001057600080fd5b50600436106101d95760003560e01c806376f15d5b11610104578063bb607362116100a2578063d88be12f11610071578063d88be12f1461039b578063ee8b86fb146103a3578063f408fb3114610279578063fa315f9d146103b6576101d9565b8063bb60736214610353578063bdab168814610369578063cd3c0b971461037e578063d6d7618c14610386576101d9565b80638ee52b4e116100de5780638ee52b4e146103225780639a3b618514610335578063a3c2f6b61461033d578063ae2dae1714610345576101d9565b806376f15d5b146102f25780637833bec0146102fa5780637a791e6e1461031a576101d9565b80634303a5421161017c57806359c28add1161014b57806359c28add146102b45780635ba3c7c0146102c957806363d69c88146102d1578063647341eb146102e4576101d9565b80634303a542146102875780634582eab21461028f57806345fdbdb714610297578063586f84b21461029f576101d9565b80632e1a7d4d116101b85780632e1a7d4d146102245780633687617d1461023757806336b32396146102595780633e9ef66a14610279576101d9565b806209e437146101de5780630527c28f146101e85780631310e444146101fb575b600080fd5b6101e66103c4565b005b6101e66101f6366004610c7f565b610401565b61020e610209366004610d87565b610404565b60405161021b91906113e8565b60405180910390f35b6101e6610232366004610d87565b61040b565b61024a610245366004610efc565b61045c565b60405161021b93929190611151565b61026c610267366004610d0b565b6104fc565b60405161021b9190611094565b6101e66101f6366004610d4c565b61020e6105de565b6101e66105e5565b6101e661064a565b6102a761067c565b60405161021b9190611373565b6102bc610684565b60405161021b919061137e565b6101e661068c565b61026c6102df366004610c2e565b6106f1565b6101e66101f6366004610ec9565b61020e6106fa565b61030d610308366004610d9f565b610708565b60405161021b9190611287565b6101e66107c5565b61020e610330366004610d87565b6107ca565b6101e66107d0565b61020e6107db565b6101e66101f6366004610e39565b61035b6107e0565b60405161021b9291906113f1565b610371610819565b60405161021b91906110b5565b6101e661081e565b61038e610855565b60405161021b91906113d5565b61020e6109ae565b6101e66103b1366004610d87565b6101f6565b6101e66101f6366004610d87565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016103f690611250565b60405180910390fd5b565b50565b506107c790565b3373ffffffffffffffffffffffffffffffffffffffff167f7fcf532c15f0a6db0bd6d0e038bea71d30d808c7d98cb3bf7268a95bf5081b658260405161045191906113e8565b60405180910390a250565b505060408051808201825260048082527f1234567800000000000000000000000000000000000000000000000000000000602080840191909152835180850185528281527f87654321000000000000000000000000000000000000000000000000000000008183015284518086019095529184527f616d657400000000000000000000000000000000000000000000000000000000908401529093909250565b600060606040518060400160405280601c81526020017f19457468657265756d205369676e6564204d6573736167653a0a33320000000081525090506000818760405160200161054d929190611072565b604051602081830303815290604052805190602001209050600181878787604051600081526020016040526040516105889493929190611133565b6020604051602081039080840390855afa1580156105aa573d6000803e3d6000fd5b50506040517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0015198975050505050505050565b6107c75b90565b604080518082018252601481527f5245564552545f574954485f434f4e5354414e54000000000000000000000000602082015290517f08c379a00000000000000000000000000000000000000000000000000000000081526103f69190600401611193565b6040517f08c379a00000000000000000000000000000000000000000000000000000000081526004016103f690611219565b6105e26109b4565b6105e26109cc565b604080518082018252601581527f524551554952455f574954485f434f4e5354414e540000000000000000000000602082015290517f08c379a00000000000000000000000000000000000000000000000000000000081526103f69190600401611193565b50929392505050565b600080546001019081905590565b6107106109ec565b50604080516080810182529182528051808201825260048082527f123456780000000000000000000000000000000000000000000000000000000060208381019190915280850192909252825180840184528181527f87654321000000000000000000000000000000000000000000000000000000008184015284840152825180840190935282527f616d65740000000000000000000000000000000000000000000000000000000090820152606082015290565b6103ff565b60010190565b600080546001019055565b600190565b60408051808201909152600581527f68656c6c6f0000000000000000000000000000000000000000000000000000006020820152600191565b606090565b7f61a6029a4c7ddee5824d171331eecbd015d26a271310a223718b837facb5b77160405161084b906111ad565b60405180910390a1565b61085d610a1a565b6040805160028082526060828101909352816020015b60608152602001906001900390816108735790505090506040518060400160405280600581526020017f3078313233000000000000000000000000000000000000000000000000000000815250816000815181106108cd57fe5b60200260200101819052506040518060400160405280600581526020017f30783332310000000000000000000000000000000000000000000000000000008152508160018151811061091b57fe5b6020908102919091018101919091526040805160c0810182526005608082018181527f307831323300000000000000000000000000000000000000000000000000000060a0840152825281840152808201939093528051808201909152600381527f6162630000000000000000000000000000000000000000000000000000000000918101919091526060820152905090565b6104d290565b60405180602001604052806109c7610a48565b905290565b60405180604001604052806109df610a1a565b8152602001606081525090565b60405180608001604052806109ff610a5b565b81526020016060815260200160608152602001606081525090565b604051806080016040528060608152602001600063ffffffff16815260200160608152602001606081525090565b6040518060200160405280600081525090565b60405180606001604052806000815260200160608152602001606081525090565b600082601f830112610a8c578081fd5b8135610a9f610a9a82611431565b61140a565b8181529150602080830190840160005b83811015610adc57610ac78760208435890101610ae6565b83526020928301929190910190600101610aaf565b5050505092915050565b600082601f830112610af6578081fd5b813567ffffffffffffffff811115610b0c578182fd5b610b3d60207fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0601f8401160161140a565b9150808252836020828501011115610b5457600080fd5b8060208401602084013760009082016020015292915050565b600060808284031215610b7e578081fd5b610b88608061140a565b9050813567ffffffffffffffff80821115610ba257600080fd5b610bae85838601610ae6565b8352610bbd8560208601610c14565b60208401526040840135915080821115610bd657600080fd5b610be285838601610a7c565b60408401526060840135915080821115610bfb57600080fd5b50610c0884828501610ae6565b60608301525092915050565b803563ffffffff81168114610c2857600080fd5b92915050565b600080600080600060a08688031215610c45578081fd5b8535610c5081611481565b945060208601359350604086013592506060860135610c6e81611481565b949793965091946080013592915050565b60006020808385031215610c91578182fd5b823567ffffffffffffffff811115610ca7578283fd5b80840185601f820112610cb8578384fd5b80359150610cc8610a9a83611431565b82815283810190828501865b85811015610cfd57610ceb8a888435880101610ae6565b84529286019290860190600101610cd4565b509098975050505050505050565b60008060008060808587031215610d20578384fd5b84359350602085013560ff81168114610d37578384fd5b93969395505050506040820135916060013590565b600060208284031215610d5d578081fd5b813567ffffffffffffffff811115610d73578182fd5b610d7f84828501610ae6565b949350505050565b600060208284031215610d98578081fd5b5035919050565b600060208284031215610db0578081fd5b813567ffffffffffffffff80821115610dc7578283fd5b81840160608187031215610dd9578384fd5b610de3606061140a565b925080358352602081013582811115610dfa578485fd5b610e0687828401610ae6565b602085015250604081013582811115610e1d578485fd5b610e2987828401610ae6565b6040850152509195945050505050565b600060208284031215610e4a578081fd5b813567ffffffffffffffff80821115610e61578283fd5b81840160408187031215610e73578384fd5b610e7d604061140a565b9250803582811115610e8d578485fd5b610e9987828401610b6d565b845250602081013582811115610ead578485fd5b610eb987828401610ae6565b6020850152509195945050505050565b600060208284031215610eda578081fd5b813567ffffffffffffffff811115610ef0578182fd5b610d7f84828501610b6d565b600080600060608486031215610f10578081fd5b83359250602084013567ffffffffffffffff80821115610f2e578283fd5b610f3a87838801610ae6565b93506040860135915080821115610f4f578283fd5b50610f5c86828701610ae6565b9150509250925092565b60008151808452610f7e816020860160208601611451565b601f017fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0169290920160200192915050565b6000815160808452610fc56080850182610f66565b6020915063ffffffff828501511682860152604084015185820360408701528181518084528484019150848582028501018584018794505b8285101561104b577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0868303018452611037828251610f66565b600195909501949387019391508601610ffd565b506060880151955088810360608a01526110658187610f66565b9998505050505050505050565b60008351611084818460208801611451565b9190910191825250602001919050565b73ffffffffffffffffffffffffffffffffffffffff91909116815260200190565b6000602080830181845280855180835260408601915060408482028701019250838701855b82811015611126577fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffc0888603018452611114858351610fb0565b945092850192908501906001016110da565b5092979650505050505050565b93845260ff9290921660208401526040830152606082015260800190565b6000606082526111646060830186610f66565b82810360208401526111768186610f66565b83810360408501526111888186610f66565b979650505050505050565b6000602082526111a66020830184610f66565b9392505050565b60408082526004908201527f123456780000000000000000000000000000000000000000000000000000000060608201526080602082018190526005908201527f6c6f72656d00000000000000000000000000000000000000000000000000000060a082015260c00190565b6020808252600d908201527f53494d504c455f52455645525400000000000000000000000000000000000000604082015260600190565b6020808252600e908201527f53494d504c455f52455155495245000000000000000000000000000000000000604082015260600190565b600060208252825160806020840152805160a08401526020810151606060c08501526112b7610100850182610f66565b604083015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff608582030160e08601526112f28183610f66565b9250505060208401517fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe0808584030160408601526113308383610f66565b604087015193508186820301606087015261134b8185610f66565b92505060608601519250808583030160808601525061136a8183610f66565b95945050505050565b905151815260200190565b60006020825282516040602084015261139a6060840182610fb0565b602085015191507fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffe084820301604085015261136a8183610f66565b6000602082526111a66020830184610fb0565b90815260200190565b600083825260406020830152610d7f6040830184610f66565b60405181810167ffffffffffffffff8111828210171561142957600080fd5b604052919050565b600067ffffffffffffffff821115611447578081fd5b5060209081020190565b60005b8381101561146c578181015183820152602001611454565b8381111561147b576000848401525b50505050565b73ffffffffffffffffffffffffffffffffffffffff8116811461040157600080fdfea365627a7a723158204f5b227587475ada330d11bfb46020f41172555bd06234eaaad1a7d10a4c2a396c6578706572696d656e74616cf564736f6c634300050c0040'; - /** - * a method that accepts an array of bytes - */ - public acceptsAnArrayOfBytes = { - /** - * 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 a the array of bytes being accepted - */ - async callAsync(a: string[], callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isArray('a', a); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('acceptsAnArrayOfBytes(bytes[])', [a]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('acceptsAnArrayOfBytes(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 a the array of bytes being accepted - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(a: string[]): string { - assert.isArray('a', a); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('acceptsAnArrayOfBytes(bytes[])', [a]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [string[]] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('acceptsAnArrayOfBytes(bytes[])'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[string[]]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('acceptsAnArrayOfBytes(bytes[])'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('acceptsAnArrayOfBytes(bytes[])'); - return abiEncoder.getSelector(); - }, - }; - public acceptsBytes = { - /** - * 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(a: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('a', a); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('acceptsBytes(bytes)', [a]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('acceptsBytes(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(a: string): string { - assert.isString('a', a); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('acceptsBytes(bytes)', [a]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [string] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('acceptsBytes(bytes)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[string]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('acceptsBytes(bytes)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('acceptsBytes(bytes)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Tests decoding when the input and output are complex. - */ - public complexInputComplexOutput = { - /** - * 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( - complexInput: { foo: BigNumber; bar: string; car: string }, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ - input: { foo: BigNumber; bar: string; car: string }; - lorem: string; - ipsum: string; - dolor: string; - }> { - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('complexInputComplexOutput((uint256,bytes,string))', [ - complexInput, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('complexInputComplexOutput((uint256,bytes,string))'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - input: { foo: BigNumber; bar: string; car: string }; - lorem: string; - ipsum: string; - dolor: 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(complexInput: { foo: BigNumber; bar: string; car: string }): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'complexInputComplexOutput((uint256,bytes,string))', - [complexInput], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): { foo: BigNumber; bar: string; car: string } { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('complexInputComplexOutput((uint256,bytes,string))'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<{ foo: BigNumber; bar: string; car: string }>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData( - returnData: string, - ): { input: { foo: BigNumber; bar: string; car: string }; lorem: string; ipsum: string; dolor: string } { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('complexInputComplexOutput((uint256,bytes,string))'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ - input: { foo: BigNumber; bar: string; car: string }; - lorem: string; - ipsum: string; - dolor: string; - }>(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('complexInputComplexOutput((uint256,bytes,string))'); - return abiEncoder.getSelector(); - }, - }; - /** - * test that devdocs will be generated and - * that multiline devdocs will look okay - */ - public ecrecoverFn = { - /** - * 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 description of some hash. Let's make this line super long to - * demonstrate hanging indents for method params. It has to be more than - * one hundred twenty columns. - * @param v some v, recovery id - * @param r ECDSA r output - * @param s ECDSA s output - * @returns the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code. - */ - async callAsync( - hash: string, - v: number | BigNumber, - r: string, - s: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('hash', hash); - assert.isNumberOrBigNumber('v', v); - assert.isString('r', r); - assert.isString('s', s); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('ecrecoverFn(bytes32,uint8,bytes32,bytes32)', [ - hash, - v, - r, - s, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('ecrecoverFn(bytes32,uint8,bytes32,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). - * @param hash description of some hash. Let's make this line super long to - * demonstrate hanging indents for method params. It has to be more than - * one hundred twenty columns. - * @param v some v, recovery id - * @param r ECDSA r output - * @param s ECDSA s output - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(hash: string, v: number | BigNumber, r: string, s: string): string { - assert.isString('hash', hash); - assert.isNumberOrBigNumber('v', v); - assert.isString('r', r); - assert.isString('s', s); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'ecrecoverFn(bytes32,uint8,bytes32,bytes32)', - [hash, v, r, s], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('ecrecoverFn(bytes32,uint8,bytes32,bytes32)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('ecrecoverFn(bytes32,uint8,bytes32,bytes32)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('ecrecoverFn(bytes32,uint8,bytes32,bytes32)'); - return abiEncoder.getSelector(); - }, - }; - public emitSimpleEvent = { - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const self = (this as any) as AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('emitSimpleEvent()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.emitSimpleEvent.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as AbiGenDummyContract; - const txHashPromise = self.emitSimpleEvent.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('emitSimpleEvent()', []); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('emitSimpleEvent()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('emitSimpleEvent()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('emitSimpleEvent()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('emitSimpleEvent()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('emitSimpleEvent()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('emitSimpleEvent()'); - return abiEncoder.getSelector(); - }, - }; - public methodReturningArrayOfStructs = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('methodReturningArrayOfStructs()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('methodReturningArrayOfStructs()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue< - Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('methodReturningArrayOfStructs()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodReturningArrayOfStructs()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData( - returnData: string, - ): Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodReturningArrayOfStructs()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue< - Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> - >(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodReturningArrayOfStructs()'); - return abiEncoder.getSelector(); - }, - }; - public methodReturningMultipleValues = { - /** - * 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<[BigNumber, string]> { - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('methodReturningMultipleValues()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('methodReturningMultipleValues()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[BigNumber, 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('methodReturningMultipleValues()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodReturningMultipleValues()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): [BigNumber, string] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodReturningMultipleValues()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<[BigNumber, string]>(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodReturningMultipleValues()'); - return abiEncoder.getSelector(); - }, - }; - public methodUsingNestedStructWithInnerStructNotUsedElsewhere = { - /** - * 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<{ innerStruct: { aField: 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments( - 'methodUsingNestedStructWithInnerStructNotUsedElsewhere()', - [], - ); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('methodUsingNestedStructWithInnerStructNotUsedElsewhere()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ innerStruct: { aField: 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'methodUsingNestedStructWithInnerStructNotUsedElsewhere()', - [], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodUsingNestedStructWithInnerStructNotUsedElsewhere()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): { innerStruct: { aField: BigNumber } } { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodUsingNestedStructWithInnerStructNotUsedElsewhere()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ innerStruct: { aField: BigNumber } }>( - returnData, - ); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('methodUsingNestedStructWithInnerStructNotUsedElsewhere()'); - return abiEncoder.getSelector(); - }, - }; - /** - * Tests decoding when the input and output are complex and have more than one argument. - */ - public multiInputMultiOutput = { - /** - * 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, - index_2: string, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<[string, string, string]> { - assert.isBigNumber('index_0', index_0); - assert.isString('index_1', index_1); - assert.isString('index_2', index_2); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('multiInputMultiOutput(uint256,bytes,string)', [ - index_0, - index_1, - index_2, - ]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('multiInputMultiOutput(uint256,bytes,string)'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<[string, string, 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(index_0: BigNumber, index_1: string, index_2: string): string { - assert.isBigNumber('index_0', index_0); - assert.isString('index_1', index_1); - assert.isString('index_2', index_2); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'multiInputMultiOutput(uint256,bytes,string)', - [index_0, index_1, index_2], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [BigNumber, string, string] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('multiInputMultiOutput(uint256,bytes,string)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[BigNumber, string, string]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): [string, string, string] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('multiInputMultiOutput(uint256,bytes,string)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<[string, string, string]>(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('multiInputMultiOutput(uint256,bytes,string)'); - return abiEncoder.getSelector(); - }, - }; - public nestedStructInput = { - /** - * 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( - n: { - innerStruct: { - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }; - description: 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments( - 'nestedStructInput(((bytes,uint32,bytes[],string),string))', - [n], - ); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('nestedStructInput(((bytes,uint32,bytes[],string),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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(n: { - innerStruct: { - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }; - description: string; - }): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'nestedStructInput(((bytes,uint32,bytes[],string),string))', - [n], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData( - callData: string, - ): [ - { - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: string; - } - ] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nestedStructInput(((bytes,uint32,bytes[],string),string))'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode< - [ - { - innerStruct: { - someBytes: string; - anInteger: number; - aDynamicArrayOfBytes: string[]; - aString: string; - }; - description: string; - } - ] - >(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nestedStructInput(((bytes,uint32,bytes[],string),string))'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nestedStructInput(((bytes,uint32,bytes[],string),string))'); - return abiEncoder.getSelector(); - }, - }; - public nestedStructOutput = { - /** - * 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<{ - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: string; - }> { - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nestedStructOutput()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('nestedStructOutput()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('nestedStructOutput()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nestedStructOutput()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData( - returnData: string, - ): { - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: string; - } { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nestedStructOutput()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ - innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; - description: string; - }>(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nestedStructOutput()'); - return abiEncoder.getSelector(); - }, - }; - /** - * Tests decoding when both input and output are empty. - */ - public noInputNoOutput = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('noInputNoOutput()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('noInputNoOutput()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('noInputNoOutput()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('noInputNoOutput()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('noInputNoOutput()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('noInputNoOutput()'); - return abiEncoder.getSelector(); - }, - }; - /** - * Tests decoding when input is empty and output is non-empty. - */ - public noInputSimpleOutput = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('noInputSimpleOutput()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('noInputSimpleOutput()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('noInputSimpleOutput()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('noInputSimpleOutput()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('noInputSimpleOutput()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('noInputSimpleOutput()'); - return abiEncoder.getSelector(); - }, - }; - public nonPureMethod = { - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const self = (this as any) as AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nonPureMethod()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.nonPureMethod.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as AbiGenDummyContract; - const txHashPromise = self.nonPureMethod.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nonPureMethod()', []); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nonPureMethod()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('nonPureMethod()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('nonPureMethod()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nonPureMethod()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nonPureMethod()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nonPureMethod()'); - return abiEncoder.getSelector(); - }, - }; - public nonPureMethodThatReturnsNothing = { - /** - * 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - const self = (this as any) as AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); - const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...txData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - if (txDataWithDefaults.from !== undefined) { - txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); - } - - if (opts.shouldValidate !== false) { - await self.nonPureMethodThatReturnsNothing.callAsync(txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - const self = (this as any) as AbiGenDummyContract; - const txHashPromise = self.nonPureMethodThatReturnsNothing.sendTransactionAsync(txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); - const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( - { - to: self.address, - ...callData, - data: encodedData, - }, - self._web3Wrapper.getContractDefaults(), - ); - callDataWithDefaults.from = callDataWithDefaults.from - ? callDataWithDefaults.from.toLowerCase() - : callDataWithDefaults.from; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - const abiEncoder = self._lookupAbiEncoder('nonPureMethodThatReturnsNothing()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nonPureMethodThatReturnsNothing()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nonPureMethodThatReturnsNothing()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('nonPureMethodThatReturnsNothing()'); - return abiEncoder.getSelector(); - }, - }; - public overloadedMethod2 = { - /** - * 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(a: string, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isString('a', a); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('overloadedMethod(string)', [a]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(a: string): string { - assert.isString('a', a); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('overloadedMethod(string)', [a]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [string] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(string)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[string]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(string)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(string)'); - return abiEncoder.getSelector(); - }, - }; - public overloadedMethod1 = { - /** - * 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(a: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('a', a); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('overloadedMethod(int256)', [a]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(int256)'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(a: BigNumber): string { - assert.isBigNumber('a', a); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('overloadedMethod(int256)', [a]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [BigNumber] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(int256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[BigNumber]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(int256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('overloadedMethod(int256)'); - return abiEncoder.getSelector(); - }, - }; - public pureFunctionWithConstant = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('pureFunctionWithConstant()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('pureFunctionWithConstant()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('pureFunctionWithConstant()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('pureFunctionWithConstant()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('pureFunctionWithConstant()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('pureFunctionWithConstant()'); - return abiEncoder.getSelector(); - }, - }; - public requireWithConstant = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('requireWithConstant()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('requireWithConstant()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('requireWithConstant()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('requireWithConstant()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('requireWithConstant()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('requireWithConstant()'); - return abiEncoder.getSelector(); - }, - }; - public revertWithConstant = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('revertWithConstant()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('revertWithConstant()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('revertWithConstant()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('revertWithConstant()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('revertWithConstant()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('revertWithConstant()'); - return abiEncoder.getSelector(); - }, - }; - /** - * Tests decoding when input is not empty but output is empty. - */ - public simpleInputNoOutput = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('simpleInputNoOutput(uint256)', [index_0]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('simpleInputNoOutput(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(index_0: BigNumber): string { - assert.isBigNumber('index_0', index_0); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('simpleInputNoOutput(uint256)', [index_0]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [BigNumber] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleInputNoOutput(uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[BigNumber]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleInputNoOutput(uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleInputNoOutput(uint256)'); - return abiEncoder.getSelector(); - }, - }; - /** - * Tests decoding when both input and output are non-empty. - */ - public simpleInputSimpleOutput = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('simpleInputSimpleOutput(uint256)', [index_0]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('simpleInputSimpleOutput(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(index_0: BigNumber): string { - assert.isBigNumber('index_0', index_0); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('simpleInputSimpleOutput(uint256)', [ - index_0, - ]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleInputSimpleOutput(uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleInputSimpleOutput(uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleInputSimpleOutput(uint256)'); - return abiEncoder.getSelector(); - }, - }; - public simplePureFunction = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('simplePureFunction()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('simplePureFunction()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('simplePureFunction()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simplePureFunction()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simplePureFunction()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simplePureFunction()'); - return abiEncoder.getSelector(); - }, - }; - public simplePureFunctionWithInput = { - /** - * 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(x: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('x', x); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('simplePureFunctionWithInput(uint256)', [x]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('simplePureFunctionWithInput(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(x: BigNumber): string { - assert.isBigNumber('x', x); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('simplePureFunctionWithInput(uint256)', [x]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simplePureFunctionWithInput(uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simplePureFunctionWithInput(uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simplePureFunctionWithInput(uint256)'); - return abiEncoder.getSelector(); - }, - }; - public simpleRequire = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('simpleRequire()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('simpleRequire()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('simpleRequire()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleRequire()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleRequire()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleRequire()'); - return abiEncoder.getSelector(); - }, - }; - public simpleRevert = { - /** - * 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('simpleRevert()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('simpleRevert()'); - // 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('simpleRevert()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleRevert()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleRevert()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('simpleRevert()'); - return abiEncoder.getSelector(); - }, - }; - public structInput = { - /** - * 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( - s: { someBytes: string; anInteger: number | BigNumber; aDynamicArrayOfBytes: string[]; aString: 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('structInput((bytes,uint32,bytes[],string))', [s]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('structInput((bytes,uint32,bytes[],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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(s: { - someBytes: string; - anInteger: number | BigNumber; - aDynamicArrayOfBytes: string[]; - aString: string; - }): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'structInput((bytes,uint32,bytes[],string))', - [s], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData( - callData: string, - ): [{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('structInput((bytes,uint32,bytes[],string))'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode< - [{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }] - >(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('structInput((bytes,uint32,bytes[],string))'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('structInput((bytes,uint32,bytes[],string))'); - return abiEncoder.getSelector(); - }, - }; - /** - * a method that returns a struct - */ - public structOutput = { - /** - * 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 a Struct struct - */ - async callAsync( - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> { - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments('structOutput()', []); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('structOutput()'); - // tslint:disable boolean-naming - const result = abiEncoder.strictDecodeReturnValue<{ - someBytes: string; - anInteger: number; - aDynamicArrayOfBytes: string[]; - aString: 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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('structOutput()', []); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('structOutput()'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData( - returnData: string, - ): { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string } { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('structOutput()'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue<{ - someBytes: string; - anInteger: number; - aDynamicArrayOfBytes: string[]; - aString: string; - }>(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('structOutput()'); - return abiEncoder.getSelector(); - }, - }; - public withAddressInput = { - /** - * 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( - x: string, - a: BigNumber, - b: BigNumber, - y: string, - c: BigNumber, - callData: Partial = {}, - defaultBlock?: BlockParam, - ): Promise { - assert.isString('x', x); - assert.isBigNumber('a', a); - assert.isBigNumber('b', b); - assert.isString('y', y); - assert.isBigNumber('c', c); - 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 AbiGenDummyContract; - const encodedData = self._strictEncodeArguments( - 'withAddressInput(address,uint256,uint256,address,uint256)', - [x.toLowerCase(), a, b, y.toLowerCase(), c], - ); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('withAddressInput(address,uint256,uint256,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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(x: string, a: BigNumber, b: BigNumber, y: string, c: BigNumber): string { - assert.isString('x', x); - assert.isBigNumber('a', a); - assert.isBigNumber('b', b); - assert.isString('y', y); - assert.isBigNumber('c', c); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments( - 'withAddressInput(address,uint256,uint256,address,uint256)', - [x.toLowerCase(), a, b, y.toLowerCase(), c], - ); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('withAddressInput(address,uint256,uint256,address,uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('withAddressInput(address,uint256,uint256,address,uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('withAddressInput(address,uint256,uint256,address,uint256)'); - return abiEncoder.getSelector(); - }, - }; - 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, - opts: SendTransactionOpts = { shouldValidate: true }, - ): Promise { - assert.isBigNumber('wad', wad); - const self = (this as any) as AbiGenDummyContract; - 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(); - } - - if (opts.shouldValidate !== false) { - await self.withdraw.callAsync(wad, txDataWithDefaults); - } - - 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, - opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, - ): PromiseWithTransactionHash { - assert.isBigNumber('wad', wad); - const self = (this as any) as AbiGenDummyContract; - const txHashPromise = self.withdraw.sendTransactionAsync(wad, txData, opts); - return new PromiseWithTransactionHash( - txHashPromise, - (async (): Promise => { - // When the transaction hash resolves, wait for it to be mined. - return self._web3Wrapper.awaitTransactionSuccessAsync( - await txHashPromise, - opts.pollingIntervalMs, - opts.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 AbiGenDummyContract; - 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 AbiGenDummyContract; - 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; - let rawCallResult; - try { - rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(wad: BigNumber): string { - assert.isBigNumber('wad', wad); - const self = (this as any) as AbiGenDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('withdraw(uint256)', [wad]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): [BigNumber] { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode<[BigNumber]>(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): void { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as AbiGenDummyContract; - const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; private readonly _subscriptionManager: SubscriptionManager; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, @@ -3765,6 +801,1615 @@ export class AbiGenDummyContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = AbiGenDummyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as AbiGenDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as AbiGenDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as AbiGenDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + /** + * a method that accepts an array of bytes + * @param a the array of bytes being accepted + */ + public acceptsAnArrayOfBytes(a: string[]): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isArray('a', a); + + return { + 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 encodedData = self._strictEncodeArguments('acceptsAnArrayOfBytes(bytes[])', [a]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('acceptsAnArrayOfBytes(bytes[])'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('acceptsAnArrayOfBytes(bytes[])', [a]); + return abiEncodedTransactionData; + }, + }; + } + public acceptsBytes(a: string): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isString('a', a); + + return { + 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 encodedData = self._strictEncodeArguments('acceptsBytes(bytes)', [a]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('acceptsBytes(bytes)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('acceptsBytes(bytes)', [a]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Tests decoding when the input and output are complex. + */ + public complexInputComplexOutput(complexInput: { + foo: BigNumber; + bar: string; + car: string; + }): ContractFunctionObj<{ + input: { foo: BigNumber; bar: string; car: string }; + lorem: string; + ipsum: string; + dolor: string; + }> { + const self = (this as any) as AbiGenDummyContract; + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + input: { foo: BigNumber; bar: string; car: string }; + lorem: string; + ipsum: string; + dolor: string; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('complexInputComplexOutput((uint256,bytes,string))', [ + complexInput, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('complexInputComplexOutput((uint256,bytes,string))'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + input: { foo: BigNumber; bar: string; car: string }; + lorem: string; + ipsum: string; + dolor: string; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'complexInputComplexOutput((uint256,bytes,string))', + [complexInput], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * test that devdocs will be generated and + * that multiline devdocs will look okay + * @param hash description of some hash. Let's make this line super long to + * demonstrate hanging indents for method params. It has to be more than + * one hundred twenty columns. + * @param v some v, recovery id + * @param r ECDSA r output + * @param s ECDSA s output + * @returns the signerAddress that created this signature. this line too is super long in order to demonstrate the proper hanging indentation in generated code. + */ + public ecrecoverFn(hash: string, v: number | BigNumber, r: string, s: string): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isString('hash', hash); + assert.isNumberOrBigNumber('v', v); + assert.isString('r', r); + assert.isString('s', s); + + return { + 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 encodedData = self._strictEncodeArguments('ecrecoverFn(bytes32,uint8,bytes32,bytes32)', [ + hash, + v, + r, + s, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('ecrecoverFn(bytes32,uint8,bytes32,bytes32)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'ecrecoverFn(bytes32,uint8,bytes32,bytes32)', + [hash, v, r, s], + ); + return abiEncodedTransactionData; + }, + }; + } + public emitSimpleEvent(): ContractTxFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('emitSimpleEvent()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('emitSimpleEvent()', []); + 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; + }, + 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 encodedData = self._strictEncodeArguments('emitSimpleEvent()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('emitSimpleEvent()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('emitSimpleEvent()', []); + return abiEncodedTransactionData; + }, + }; + } + public methodReturningArrayOfStructs(): ContractFunctionObj< + Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> + > { + const self = (this as any) as AbiGenDummyContract; + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise< + Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> + > { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('methodReturningArrayOfStructs()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('methodReturningArrayOfStructs()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue< + Array<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> + >(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('methodReturningArrayOfStructs()', []); + return abiEncodedTransactionData; + }, + }; + } + public methodReturningMultipleValues(): ContractFunctionObj<[BigNumber, string]> { + const self = (this as any) as AbiGenDummyContract; + + return { + async callAsync(callData: Partial = {}, defaultBlock?: BlockParam): Promise<[BigNumber, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('methodReturningMultipleValues()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('methodReturningMultipleValues()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[BigNumber, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('methodReturningMultipleValues()', []); + return abiEncodedTransactionData; + }, + }; + } + public methodUsingNestedStructWithInnerStructNotUsedElsewhere(): ContractFunctionObj<{ + innerStruct: { aField: BigNumber }; + }> { + const self = (this as any) as AbiGenDummyContract; + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ innerStruct: { aField: BigNumber } }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments( + 'methodUsingNestedStructWithInnerStructNotUsedElsewhere()', + [], + ); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('methodUsingNestedStructWithInnerStructNotUsedElsewhere()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ innerStruct: { aField: BigNumber } }>( + rawCallResult, + ); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'methodUsingNestedStructWithInnerStructNotUsedElsewhere()', + [], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * Tests decoding when the input and output are complex and have more than one argument. + */ + public multiInputMultiOutput( + index_0: BigNumber, + index_1: string, + index_2: string, + ): ContractFunctionObj<[string, string, string]> { + const self = (this as any) as AbiGenDummyContract; + assert.isBigNumber('index_0', index_0); + assert.isString('index_1', index_1); + assert.isString('index_2', index_2); + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<[string, string, string]> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('multiInputMultiOutput(uint256,bytes,string)', [ + index_0, + index_1, + index_2, + ]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('multiInputMultiOutput(uint256,bytes,string)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<[string, string, string]>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'multiInputMultiOutput(uint256,bytes,string)', + [index_0, index_1, index_2], + ); + return abiEncodedTransactionData; + }, + }; + } + public nestedStructInput(n: { + innerStruct: { + someBytes: string; + anInteger: number | BigNumber; + aDynamicArrayOfBytes: string[]; + aString: string; + }; + description: string; + }): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments( + 'nestedStructInput(((bytes,uint32,bytes[],string),string))', + [n], + ); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('nestedStructInput(((bytes,uint32,bytes[],string),string))'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'nestedStructInput(((bytes,uint32,bytes[],string),string))', + [n], + ); + return abiEncodedTransactionData; + }, + }; + } + public nestedStructOutput(): ContractFunctionObj<{ + innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; + description: string; + }> { + const self = (this as any) as AbiGenDummyContract; + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ + innerStruct: { someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }; + description: string; + }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('nestedStructOutput()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('nestedStructOutput()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + innerStruct: { + someBytes: string; + anInteger: number; + aDynamicArrayOfBytes: string[]; + aString: string; + }; + description: string; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('nestedStructOutput()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Tests decoding when both input and output are empty. + */ + public noInputNoOutput(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('noInputNoOutput()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('noInputNoOutput()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('noInputNoOutput()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Tests decoding when input is empty and output is non-empty. + */ + public noInputSimpleOutput(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('noInputSimpleOutput()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('noInputSimpleOutput()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('noInputSimpleOutput()', []); + return abiEncodedTransactionData; + }, + }; + } + public nonPureMethod(): ContractTxFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('nonPureMethod()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('nonPureMethod()', []); + 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; + }, + 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 encodedData = self._strictEncodeArguments('nonPureMethod()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('nonPureMethod()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('nonPureMethod()', []); + return abiEncodedTransactionData; + }, + }; + } + public nonPureMethodThatReturnsNothing(): ContractTxFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + const encodedData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); + const txDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...txData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + if (txDataWithDefaults.from !== undefined) { + txDataWithDefaults.from = txDataWithDefaults.from.toLowerCase(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + const encodedData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); + 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; + }, + 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 encodedData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('nonPureMethodThatReturnsNothing()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('nonPureMethodThatReturnsNothing()', []); + return abiEncodedTransactionData; + }, + }; + } + public overloadedMethod2(a: string): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isString('a', a); + + return { + 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 encodedData = self._strictEncodeArguments('overloadedMethod(string)', [a]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('overloadedMethod(string)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('overloadedMethod(string)', [a]); + return abiEncodedTransactionData; + }, + }; + } + public overloadedMethod1(a: BigNumber): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isBigNumber('a', a); + + return { + 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 encodedData = self._strictEncodeArguments('overloadedMethod(int256)', [a]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('overloadedMethod(int256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('overloadedMethod(int256)', [a]); + return abiEncodedTransactionData; + }, + }; + } + public pureFunctionWithConstant(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('pureFunctionWithConstant()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('pureFunctionWithConstant()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('pureFunctionWithConstant()', []); + return abiEncodedTransactionData; + }, + }; + } + public requireWithConstant(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('requireWithConstant()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('requireWithConstant()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('requireWithConstant()', []); + return abiEncodedTransactionData; + }, + }; + } + public revertWithConstant(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('revertWithConstant()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('revertWithConstant()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('revertWithConstant()', []); + return abiEncodedTransactionData; + }, + }; + } + /** + * Tests decoding when input is not empty but output is empty. + */ + public simpleInputNoOutput(index_0: BigNumber): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isBigNumber('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('simpleInputNoOutput(uint256)', [index_0]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('simpleInputNoOutput(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('simpleInputNoOutput(uint256)', [ + index_0, + ]); + return abiEncodedTransactionData; + }, + }; + } + /** + * Tests decoding when both input and output are non-empty. + */ + public simpleInputSimpleOutput(index_0: BigNumber): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isBigNumber('index_0', index_0); + + return { + 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 encodedData = self._strictEncodeArguments('simpleInputSimpleOutput(uint256)', [index_0]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('simpleInputSimpleOutput(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('simpleInputSimpleOutput(uint256)', [ + index_0, + ]); + return abiEncodedTransactionData; + }, + }; + } + public simplePureFunction(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('simplePureFunction()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('simplePureFunction()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('simplePureFunction()', []); + return abiEncodedTransactionData; + }, + }; + } + public simplePureFunctionWithInput(x: BigNumber): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isBigNumber('x', x); + + return { + 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 encodedData = self._strictEncodeArguments('simplePureFunctionWithInput(uint256)', [x]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('simplePureFunctionWithInput(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('simplePureFunctionWithInput(uint256)', [ + x, + ]); + return abiEncodedTransactionData; + }, + }; + } + public simpleRequire(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('simpleRequire()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('simpleRequire()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('simpleRequire()', []); + return abiEncodedTransactionData; + }, + }; + } + public simpleRevert(): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('simpleRevert()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('simpleRevert()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('simpleRevert()', []); + return abiEncodedTransactionData; + }, + }; + } + public structInput(s: { + someBytes: string; + anInteger: number | BigNumber; + aDynamicArrayOfBytes: string[]; + aString: string; + }): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + + return { + 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 encodedData = self._strictEncodeArguments('structInput((bytes,uint32,bytes[],string))', [s]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('structInput((bytes,uint32,bytes[],string))'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'structInput((bytes,uint32,bytes[],string))', + [s], + ); + return abiEncodedTransactionData; + }, + }; + } + /** + * a method that returns a struct + * @returns a Struct struct + */ + public structOutput(): ContractFunctionObj<{ + someBytes: string; + anInteger: number; + aDynamicArrayOfBytes: string[]; + aString: string; + }> { + const self = (this as any) as AbiGenDummyContract; + + return { + async callAsync( + callData: Partial = {}, + defaultBlock?: BlockParam, + ): Promise<{ someBytes: string; anInteger: number; aDynamicArrayOfBytes: string[]; aString: string }> { + assert.doesConformToSchema('callData', callData, schemas.callDataSchema, [ + schemas.addressSchema, + schemas.numberSchema, + schemas.jsNumber, + ]); + if (defaultBlock !== undefined) { + assert.isBlockParam('defaultBlock', defaultBlock); + } + const encodedData = self._strictEncodeArguments('structOutput()', []); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('structOutput()'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue<{ + someBytes: string; + anInteger: number; + aDynamicArrayOfBytes: string[]; + aString: string; + }>(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('structOutput()', []); + return abiEncodedTransactionData; + }, + }; + } + public withAddressInput( + x: string, + a: BigNumber, + b: BigNumber, + y: string, + c: BigNumber, + ): ContractFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isString('x', x); + assert.isBigNumber('a', a); + assert.isBigNumber('b', b); + assert.isString('y', y); + assert.isBigNumber('c', c); + + return { + 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 encodedData = self._strictEncodeArguments( + 'withAddressInput(address,uint256,uint256,address,uint256)', + [x.toLowerCase(), a, b, y.toLowerCase(), c], + ); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withAddressInput(address,uint256,uint256,address,uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments( + 'withAddressInput(address,uint256,uint256,address,uint256)', + [x.toLowerCase(), a, b, y.toLowerCase(), c], + ); + return abiEncodedTransactionData; + }, + }; + } + public withdraw(wad: BigNumber): ContractTxFunctionObj { + const self = (this as any) as AbiGenDummyContract; + assert.isBigNumber('wad', wad); + + return { + async sendTransactionAsync( + txData?: Partial | undefined, + opts: SendTransactionOpts = { shouldValidate: true }, + ): Promise { + 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(); + } + + if (opts.shouldValidate !== false) { + await this.callAsync(txDataWithDefaults); + } + + const txHash = await self._web3Wrapper.sendTransactionAsync(txDataWithDefaults); + return txHash; + }, + awaitTransactionSuccessAsync( + txData?: Partial, + opts: AwaitTransactionSuccessOpts = { shouldValidate: true }, + ): PromiseWithTransactionHash { + const txHashPromise = this.sendTransactionAsync(txData, opts); + return new PromiseWithTransactionHash( + txHashPromise, + (async (): Promise => { + // When the transaction hash resolves, wait for it to be mined. + return self._web3Wrapper.awaitTransactionSuccessAsync( + await txHashPromise, + opts.pollingIntervalMs, + opts.timeoutMs, + ); + })(), + ); + }, + async estimateGasAsync(txData?: Partial | undefined): Promise { + 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; + }, + 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 encodedData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + let rawCallResult; + + const callDataWithDefaults = await BaseContract._applyDefaultsToTxDataAsync( + { + to: self.address, + ...callData, + data: encodedData, + }, + self._web3Wrapper.getContractDefaults(), + ); + callDataWithDefaults.from = callDataWithDefaults.from + ? callDataWithDefaults.from.toLowerCase() + : callDataWithDefaults.from; + try { + rawCallResult = await self._web3Wrapper.callAsync(callDataWithDefaults, defaultBlock); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('withdraw(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('withdraw(uint256)', [wad]); + return abiEncodedTransactionData; + }, + }; + } + /** * Subscribe to an event type emitted by the AbiGenDummy contract. * @param eventName The AbiGenDummy contract event you would like to subscribe to. @@ -3854,6 +2499,12 @@ export class AbiGenDummyContract extends BaseContract { AbiGenDummyContract.ABI(), this._web3Wrapper, ); + AbiGenDummyContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts b/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts index 39d6a9f45e..f36975f234 100644 --- a/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts +++ b/packages/abi-gen/test-cli/output/typescript/lib_dummy.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -38,6 +40,7 @@ export class LibDummyContract extends BaseContract { * @ignore */ public static deployedBytecode: string | undefined; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -109,6 +112,34 @@ export class LibDummyContract extends BaseContract { const abi = [] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = LibDummyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as LibDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as LibDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as LibDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -126,6 +157,12 @@ export class LibDummyContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + LibDummyContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts b/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts index b1721f5ca3..fb3801014c 100644 --- a/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts +++ b/packages/abi-gen/test-cli/output/typescript/test_lib_dummy.ts @@ -1,7 +1,15 @@ // tslint:disable:no-consecutive-blank-lines ordered-imports align trailing-comma enum-naming // tslint:disable:whitespace no-unbound-method no-trailing-whitespace // tslint:disable:no-unused-variable -import { BaseContract, PromiseWithTransactionHash } from '@0x/base-contract'; +import { + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SendTransactionOpts, + BaseContract, + PromiseWithTransactionHash, + methodAbiToFunctionSignature, +} from '@0x/base-contract'; import { schemas } from '@0x/json-schemas'; import { BlockParam, @@ -18,13 +26,7 @@ import { SupportedProvider, } from 'ethereum-types'; import { BigNumber, classUtils, logUtils, providerUtils } from '@0x/utils'; -import { - AwaitTransactionSuccessOpts, - EventCallback, - IndexedFilterValues, - SendTransactionOpts, - SimpleContractArtifact, -} from '@0x/types'; +import { EventCallback, IndexedFilterValues, SimpleContractArtifact } from '@0x/types'; import { Web3Wrapper } from '@0x/web3-wrapper'; import { assert } from '@0x/assert'; import * as ethers from 'ethers'; @@ -39,166 +41,7 @@ export class TestLibDummyContract extends BaseContract { */ public static deployedBytecode = '0x6080604052348015600f57600080fd5b506004361060325760003560e01c806322935e921460375780632b82fdf0146063575b600080fd5b605160048036036020811015604b57600080fd5b5035607d565b60408051918252519081900360200190f35b605160048036036020811015607757600080fd5b5035608c565b60006086826095565b92915050565b6000608682609c565b6104d20190565b6001019056fea265627a7a72315820863e53f0da474a1275d583d88852313fe053941e79bddd5279abd812b31e020c64736f6c634300050c0032'; - public publicAddConstant = { - /** - * 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(x: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('x', x); - 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 TestLibDummyContract; - const encodedData = self._strictEncodeArguments('publicAddConstant(uint256)', [x]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('publicAddConstant(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(x: BigNumber): string { - assert.isBigNumber('x', x); - const self = (this as any) as TestLibDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('publicAddConstant(uint256)', [x]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): BigNumber { - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder('publicAddConstant(uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder('publicAddConstant(uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder('publicAddConstant(uint256)'); - return abiEncoder.getSelector(); - }, - }; - public publicAddOne = { - /** - * 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(x: BigNumber, callData: Partial = {}, defaultBlock?: BlockParam): Promise { - assert.isBigNumber('x', x); - 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 TestLibDummyContract; - const encodedData = self._strictEncodeArguments('publicAddOne(uint256)', [x]); - const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); - - let rawCallResult; - try { - rawCallResult = await self._evmExecAsync(encodedDataBytes); - } catch (err) { - BaseContract._throwIfThrownErrorIsRevertError(err); - throw err; - } - BaseContract._throwIfCallResultIsRevertError(rawCallResult); - - const abiEncoder = self._lookupAbiEncoder('publicAddOne(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). - * @returns The ABI encoded transaction data as a string - */ - getABIEncodedTransactionData(x: BigNumber): string { - assert.isBigNumber('x', x); - const self = (this as any) as TestLibDummyContract; - const abiEncodedTransactionData = self._strictEncodeArguments('publicAddOne(uint256)', [x]); - return abiEncodedTransactionData; - }, - /** - * Decode the ABI-encoded transaction data into its input arguments - * @param callData The ABI-encoded transaction data - * @returns An array representing the input arguments in order. Keynames of nested structs are preserved. - */ - getABIDecodedTransactionData(callData: string): BigNumber { - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder('publicAddOne(uint256)'); - // tslint:disable boolean-naming - const abiDecodedCallData = abiEncoder.strictDecode(callData); - return abiDecodedCallData; - }, - /** - * Decode the ABI-encoded return data from a transaction - * @param returnData the data returned after transaction execution - * @returns An array representing the output results in order. Keynames of nested structs are preserved. - */ - getABIDecodedReturnData(returnData: string): BigNumber { - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder('publicAddOne(uint256)'); - // tslint:disable boolean-naming - const abiDecodedReturnData = abiEncoder.strictDecodeReturnValue(returnData); - return abiDecodedReturnData; - }, - /** - * Returns the 4 byte function selector as a hex string. - */ - getSelector(): string { - const self = (this as any) as TestLibDummyContract; - const abiEncoder = self._lookupAbiEncoder('publicAddOne(uint256)'); - return abiEncoder.getSelector(); - }, - }; + private readonly _methodABIIndex: { [name: string]: number } = {}; public static async deployFrom0xArtifactAsync( artifact: ContractArtifact | SimpleContractArtifact, supportedProvider: SupportedProvider, @@ -309,6 +152,111 @@ export class TestLibDummyContract extends BaseContract { ] as ContractAbi; return abi; } + + public getFunctionSignature(methodName: string): string { + const index = this._methodABIIndex[methodName]; + const methodAbi = TestLibDummyContract.ABI()[index] as MethodAbi; // tslint:disable-line:no-unnecessary-type-assertion + const functionSignature = methodAbiToFunctionSignature(methodAbi); + return functionSignature; + } + public getABIDecodedTransactionData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as TestLibDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecode(callData); + return abiDecodedCallData; + } + public getABIDecodedReturnData(methodName: string, callData: string): T { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as TestLibDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + const abiDecodedCallData = abiEncoder.strictDecodeReturnValue(callData); + return abiDecodedCallData; + } + public getSelector(methodName: string): string { + const functionSignature = this.getFunctionSignature(methodName); + const self = (this as any) as TestLibDummyContract; + const abiEncoder = self._lookupAbiEncoder(functionSignature); + return abiEncoder.getSelector(); + } + + public publicAddConstant(x: BigNumber): ContractFunctionObj { + const self = (this as any) as TestLibDummyContract; + assert.isBigNumber('x', x); + + return { + 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 encodedData = self._strictEncodeArguments('publicAddConstant(uint256)', [x]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('publicAddConstant(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('publicAddConstant(uint256)', [x]); + return abiEncodedTransactionData; + }, + }; + } + public publicAddOne(x: BigNumber): ContractFunctionObj { + const self = (this as any) as TestLibDummyContract; + assert.isBigNumber('x', x); + + return { + 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 encodedData = self._strictEncodeArguments('publicAddOne(uint256)', [x]); + let rawCallResult; + + const encodedDataBytes = Buffer.from(encodedData.substr(2), 'hex'); + try { + rawCallResult = await self._evmExecAsync(encodedDataBytes); + } catch (err) { + BaseContract._throwIfThrownErrorIsRevertError(err); + throw err; + } + + BaseContract._throwIfCallResultIsRevertError(rawCallResult); + const abiEncoder = self._lookupAbiEncoder('publicAddOne(uint256)'); + // tslint:disable boolean-naming + const result = abiEncoder.strictDecodeReturnValue(rawCallResult); + // tslint:enable boolean-naming + return result; + }, + getABIEncodedTransactionData(): string { + const abiEncodedTransactionData = self._strictEncodeArguments('publicAddOne(uint256)', [x]); + return abiEncodedTransactionData; + }, + }; + } + constructor( address: string, supportedProvider: SupportedProvider, @@ -326,6 +274,12 @@ export class TestLibDummyContract extends BaseContract { deployedBytecode, ); classUtils.bindAll(this, ['_abiEncoderByFunctionSignature', 'address', '_web3Wrapper']); + TestLibDummyContract.ABI().forEach((item, index) => { + if (item.type === 'function') { + const methodAbi = item as MethodAbi; + this._methodABIIndex[methodAbi.name] = index; + } + }); } } diff --git a/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts b/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts index 948f909c7a..5dfc7eb503 100644 --- a/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts +++ b/packages/abi-gen/test-cli/test_typescript/test/abi_gen_dummy_test.ts @@ -1,3 +1,4 @@ +import { ContractFunctionObj } from '@0x/base-contract'; import { BlockchainLifecycle, devConstants, web3Factory } from '@0x/dev-utils'; import { Web3ProviderEngine } from '@0x/subproviders'; import { BigNumber, providerUtils, StringRevertError } from '@0x/utils'; @@ -33,10 +34,15 @@ const blockchainLifecycle = new BlockchainLifecycle(web3Wrapper); describe('AbiGenDummy Contract', () => { let abiGenDummy: AbiGenDummyContract; - const runTestAsync = async (contractMethod: any, input: any, output: any) => { - const transaction = contractMethod.getABIEncodedTransactionData(input); + const runTestAsync = async ( + contractMethodName: string, + contractMethod: ContractFunctionObj, + input: any, + output: any, + ) => { + const transaction = contractMethod.getABIEncodedTransactionData(); // try decoding transaction - const decodedInput = contractMethod.getABIDecodedTransactionData(transaction); + const decodedInput = abiGenDummy.getABIDecodedTransactionData(contractMethodName, transaction); expect(decodedInput, 'decoded input').to.be.deep.equal(input); // execute transaction const rawOutput = await web3Wrapper.callAsync({ @@ -44,7 +50,7 @@ describe('AbiGenDummy Contract', () => { data: transaction, }); // try decoding output - const decodedOutput = contractMethod.getABIDecodedReturnData(rawOutput); + const decodedOutput = abiGenDummy.getABIDecodedReturnData(contractMethodName, rawOutput); expect(decodedOutput, 'decoded output').to.be.deep.equal(output); }; before(async () => { @@ -62,46 +68,46 @@ describe('AbiGenDummy Contract', () => { }); describe('simplePureFunction', () => { it('should call simplePureFunction', async () => { - const result = await abiGenDummy.simplePureFunction.callAsync(); + const result = await abiGenDummy.simplePureFunction().callAsync(); expect(result).to.deep.equal(new BigNumber(1)); }); }); describe('simplePureFunctionWithInput', () => { it('should call simplePureFunctionWithInput', async () => { - const result = await abiGenDummy.simplePureFunctionWithInput.callAsync(new BigNumber(5)); + const result = await abiGenDummy.simplePureFunctionWithInput(new BigNumber(5)).callAsync(); expect(result).to.deep.equal(new BigNumber(6)); }); }); describe('pureFunctionWithConstant', () => { it('should call pureFunctionWithConstant', async () => { - const result = await abiGenDummy.pureFunctionWithConstant.callAsync(); + const result = await abiGenDummy.pureFunctionWithConstant().callAsync(); expect(result).to.deep.equal(new BigNumber(1234)); }); }); describe('simpleRevert', () => { it('should call simpleRevert', async () => { - expect(abiGenDummy.simpleRevert.callAsync()) + expect(abiGenDummy.simpleRevert().callAsync()) .to.eventually.be.rejectedWith(StringRevertError) .and.deep.equal(new StringRevertError('SIMPLE_REVERT')); }); }); describe('revertWithConstant', () => { it('should call revertWithConstant', async () => { - expect(abiGenDummy.revertWithConstant.callAsync()) + expect(abiGenDummy.revertWithConstant().callAsync()) .to.eventually.be.rejectedWith(StringRevertError) .and.deep.equal(new StringRevertError('REVERT_WITH_CONSTANT')); }); }); describe('simpleRequire', () => { it('should call simpleRequire', async () => { - expect(abiGenDummy.simpleRequire.callAsync()) + expect(abiGenDummy.simpleRequire().callAsync()) .to.eventually.be.rejectedWith(StringRevertError) .and.deep.equal(new StringRevertError('SIMPLE_REQUIRE')); }); }); describe('requireWithConstant', () => { it('should call requireWithConstant', async () => { - expect(abiGenDummy.requireWithConstant.callAsync()) + expect(abiGenDummy.requireWithConstant().callAsync()) .to.eventually.be.rejectedWith(StringRevertError) .and.deep.equal(new StringRevertError('REQUIRE_WITH_CONSTANT')); }); @@ -115,7 +121,7 @@ describe('AbiGenDummy Contract', () => { someBytes: '0x3078313233', }; it('should be able to handle struct output', async () => { - const result = await abiGenDummy.structOutput.callAsync(); + const result = await abiGenDummy.structOutput().callAsync(); expect(result).to.deep.equal(sampleStruct); }); }); @@ -133,7 +139,7 @@ describe('AbiGenDummy Contract', () => { const v_decimal = parseInt(v, 16) + 27; // v: (0 or 1) => (27 or 28) // tslint:enable:custom-no-magic-numbers - const result = await abiGenDummy.ecrecoverFn.callAsync(message, v_decimal, r, s); + const result = await abiGenDummy.ecrecoverFn(message, v_decimal, r, s).callAsync(); expect(result).to.equal(signerAddress); }); }); @@ -174,7 +180,7 @@ describe('AbiGenDummy Contract', () => { toBlock: BlockParamLiteral.Latest, }; it('should get logs with decoded args emitted by EventWithStruct', async () => { - await abiGenDummy.emitSimpleEvent.awaitTransactionSuccessAsync(); + await abiGenDummy.emitSimpleEvent().awaitTransactionSuccessAsync(); const eventName = AbiGenDummyEvents.SimpleEvent; const indexFilterValues = {}; const logs = await abiGenDummy.getLogsAsync(eventName, blockRange, indexFilterValues); @@ -182,7 +188,7 @@ describe('AbiGenDummy Contract', () => { expect(logs[0].event).to.be.equal(eventName); }); it('should only get the logs with the correct event name', async () => { - await abiGenDummy.emitSimpleEvent.awaitTransactionSuccessAsync(); + await abiGenDummy.emitSimpleEvent().awaitTransactionSuccessAsync(); const differentEventName = AbiGenDummyEvents.Withdrawal; const indexFilterValues = {}; const logs = await abiGenDummy.getLogsAsync(differentEventName, blockRange, indexFilterValues); @@ -190,8 +196,8 @@ describe('AbiGenDummy Contract', () => { }); it('should only get the logs with the correct indexed fields', async () => { const [addressOne, addressTwo] = await web3Wrapper.getAvailableAddressesAsync(); - await abiGenDummy.withdraw.awaitTransactionSuccessAsync(new BigNumber(1), { from: addressOne }); - await abiGenDummy.withdraw.awaitTransactionSuccessAsync(new BigNumber(1), { from: addressTwo }); + await abiGenDummy.withdraw(new BigNumber(1)).awaitTransactionSuccessAsync({ from: addressOne }); + await abiGenDummy.withdraw(new BigNumber(1)).awaitTransactionSuccessAsync({ from: addressTwo }); const eventName = AbiGenDummyEvents.Withdrawal; const indexFilterValues = { _owner: addressOne, @@ -214,7 +220,7 @@ describe('AbiGenDummy Contract', () => { const a = new BigNumber(1); const b = new BigNumber(2); const c = new BigNumber(3); - const output = await abiGenDummy.withAddressInput.callAsync(xAddress, a, b, yAddress, c); + const output = await abiGenDummy.withAddressInput(xAddress, a, b, yAddress, c).callAsync(); expect(output).to.equal(xAddress.toLowerCase()); }); @@ -224,22 +230,22 @@ describe('AbiGenDummy Contract', () => { it('should successfully encode/decode (no input / no output)', async () => { const input = undefined; const output = undefined; - await runTestAsync(abiGenDummy.noInputNoOutput, input, output); + await runTestAsync('noInputNoOutput', abiGenDummy.noInputNoOutput(), input, output); }); it('should successfully encode/decode (no input / simple output)', async () => { const input = undefined; const output = new BigNumber(1991); - await runTestAsync(abiGenDummy.noInputSimpleOutput, input, output); + await runTestAsync('noInputSimpleOutput', abiGenDummy.noInputSimpleOutput(), input, output); }); it('should successfully encode/decode (simple input / no output)', async () => { const input = new BigNumber(1991); const output = undefined; - await runTestAsync(abiGenDummy.simpleInputNoOutput, input, output); + await runTestAsync('simpleInputNoOutput', abiGenDummy.simpleInputNoOutput(input), input, output); }); it('should successfully encode/decode (simple input / simple output)', async () => { const input = new BigNumber(16); const output = new BigNumber(1991); - await runTestAsync(abiGenDummy.simpleInputSimpleOutput, input, output); + await runTestAsync('simpleInputSimpleOutput', abiGenDummy.simpleInputSimpleOutput(input), input, output); }); it('should successfully encode/decode (complex input / complex output)', async () => { const input = { @@ -253,18 +259,21 @@ describe('AbiGenDummy Contract', () => { ipsum: '0x87654321', dolor: 'amet', }; - await runTestAsync(abiGenDummy.complexInputComplexOutput, input, output); + await runTestAsync( + 'complexInputComplexOutput', + abiGenDummy.complexInputComplexOutput(input), + input, + output, + ); }); it('should successfully encode/decode (multi-input / multi-output)', async () => { const input = [new BigNumber(1991), '0x1234', 'zoom zoom']; const output = ['0x12345678', '0x87654321', 'amet']; - const transaction = abiGenDummy.multiInputMultiOutput.getABIEncodedTransactionData( - input[0] as BigNumber, - input[1] as string, - input[2] as string, - ); + const transaction = abiGenDummy + .multiInputMultiOutput(input[0] as BigNumber, input[1] as string, input[2] as string) + .getABIEncodedTransactionData(); // try decoding transaction - const decodedInput = abiGenDummy.multiInputMultiOutput.getABIDecodedTransactionData(transaction); + const decodedInput = abiGenDummy.getABIDecodedTransactionData('multiInputMultiOutput', transaction); expect(decodedInput, 'decoded input').to.be.deep.equal(input); // execute transaction const rawOutput = await web3Wrapper.callAsync({ @@ -272,14 +281,14 @@ describe('AbiGenDummy Contract', () => { data: transaction, }); // try decoding output - const decodedOutput = abiGenDummy.multiInputMultiOutput.getABIDecodedReturnData(rawOutput); + const decodedOutput = abiGenDummy.getABIDecodedReturnData('multiInputMultiOutput', rawOutput); expect(decodedOutput, 'decoded output').to.be.deep.equal(output); }); }); describe('awaitTransactionSuccessAsync', async () => { it('should successfully call the non pure function', async () => { expect( - abiGenDummy.nonPureMethod.awaitTransactionSuccessAsync({}, { pollingIntervalMs: 10, timeoutMs: 100 }), + abiGenDummy.nonPureMethod().awaitTransactionSuccessAsync({}, { pollingIntervalMs: 10, timeoutMs: 100 }), ).to.be.fulfilled(''); }); }); @@ -309,12 +318,12 @@ describe('Lib dummy contract', () => { }); it('should call a library function', async () => { - const result = await libDummy.publicAddOne.callAsync(new BigNumber(1)); + const result = await libDummy.publicAddOne(new BigNumber(1)).callAsync(); expect(result).to.deep.equal(new BigNumber(2)); }); it('should call a library function referencing a constant', async () => { - const result = await libDummy.publicAddConstant.callAsync(new BigNumber(1)); + const result = await libDummy.publicAddConstant(new BigNumber(1)).callAsync(); expect(result).to.deep.equal(new BigNumber(1235)); }); }); diff --git a/packages/asset-buyer/src/asset_buyer.ts b/packages/asset-buyer/src/asset_buyer.ts index 7bdbafd41c..cbe6786d20 100644 --- a/packages/asset-buyer/src/asset_buyer.ts +++ b/packages/asset-buyer/src/asset_buyer.ts @@ -177,7 +177,7 @@ export class AssetBuyer { ): Promise { assert.isETHAddressHex('tokenAddress', tokenAddress); assert.isBigNumber('assetBuyAmount', assetBuyAmount); - const assetData = await this._contractWrappers.devUtils.encodeERC20AssetData.callAsync(tokenAddress); + const assetData = await this._contractWrappers.devUtils.encodeERC20AssetData(tokenAddress).callAsync(); const buyQuote = this.getBuyQuoteAsync(assetData, assetBuyAmount, options); return buyQuote; } @@ -267,19 +267,20 @@ export class AssetBuyer { // if no ethAmount is provided, default to the worst ethAmount from buyQuote const value = ethAmount || worstCaseQuoteInfo.totalEthAmount; - const txHash = await this._contractWrappers.forwarder.marketBuyOrdersWithEth.sendTransactionAsync( - orders, - assetBuyAmount, - orders.map(o => o.signature), - formattedFeePercentage, - feeRecipient, - { + const txHash = await this._contractWrappers.forwarder + .marketBuyOrdersWithEth( + orders, + assetBuyAmount, + orders.map(o => o.signature), + formattedFeePercentage, + feeRecipient, + ) + .sendTransactionAsync({ value, from: finalTakerAddress.toLowerCase(), gas: gasLimit, gasPrice, - }, - ); + }); return txHash; } catch (err) { @@ -360,17 +361,17 @@ export class AssetBuyer { * Will throw if WETH does not exist for the current chain. */ private async _getEtherTokenAssetDataOrThrowAsync(): Promise { - return this._contractWrappers.devUtils.encodeERC20AssetData.callAsync( - this._contractWrappers.contractAddresses.etherToken, - ); + return this._contractWrappers.devUtils + .encodeERC20AssetData(this._contractWrappers.contractAddresses.etherToken) + .callAsync(); } /** * Get the assetData that represents the ZRX token. * Will throw if ZRX does not exist for the current chain. */ private async _getZrxTokenAssetDataOrThrowAsync(): Promise { - return this._contractWrappers.devUtils.encodeERC20AssetData.callAsync( - this._contractWrappers.contractAddresses.zrxToken, - ); + return this._contractWrappers.devUtils + .encodeERC20AssetData(this._contractWrappers.contractAddresses.zrxToken) + .callAsync(); } } diff --git a/packages/asset-buyer/src/utils/order_provider_response_processor.ts b/packages/asset-buyer/src/utils/order_provider_response_processor.ts index defd5452c9..c19bab17dc 100644 --- a/packages/asset-buyer/src/utils/order_provider_response_processor.ts +++ b/packages/asset-buyer/src/utils/order_provider_response_processor.ts @@ -44,10 +44,9 @@ export const orderProviderResponseProcessor = { if (orderValidator !== undefined) { const takerAddresses = _.map(filteredOrders, () => constants.NULL_ADDRESS); try { - const [ordersInfo, tradersInfo] = await orderValidator.getOrdersAndTradersInfo.callAsync( - filteredOrders, - takerAddresses, - ); + const [ordersInfo, tradersInfo] = await orderValidator + .getOrdersAndTradersInfo(filteredOrders, takerAddresses) + .callAsync(); const ordersAndTradersInfo = ordersInfo.map((orderInfo, index) => { return { orderInfo, diff --git a/packages/asset-swapper/package.json b/packages/asset-swapper/package.json index 99143ed144..0da4e80e4a 100644 --- a/packages/asset-swapper/package.json +++ b/packages/asset-swapper/package.json @@ -59,7 +59,7 @@ }, "devDependencies": { "@0x/contracts-test-utils": "^3.2.0-beta.1", - "@0x/mesh-rpc-client": "^4.0.1-beta", + "@0x/mesh-rpc-client": "^6.0.1-beta", "@0x/ts-doc-gen": "^0.0.22", "@0x/tslint-config": "^3.1.0-beta.1", "@types/lodash": "4.14.104", diff --git a/packages/asset-swapper/src/quote_consumers/exchange_swap_quote_consumer.ts b/packages/asset-swapper/src/quote_consumers/exchange_swap_quote_consumer.ts index 7e79b930c7..996a652c10 100644 --- a/packages/asset-swapper/src/quote_consumers/exchange_swap_quote_consumer.ts +++ b/packages/asset-swapper/src/quote_consumers/exchange_swap_quote_consumer.ts @@ -144,28 +144,22 @@ export class ExchangeSwapQuoteConsumer implements SwapQuoteConsumerBase o.signature), - { + txHash = await this._contractWrappers.exchange + .marketBuyOrdersNoThrow(orders, makerAssetFillAmount, orders.map(o => o.signature)) + .sendTransactionAsync({ from: finalTakerAddress, gas: gasLimit, gasPrice, - }, - ); + }); } else { const { takerAssetFillAmount } = quote; - txHash = await this._contractWrappers.exchange.marketSellOrdersNoThrow.sendTransactionAsync( - orders, - takerAssetFillAmount, - orders.map(o => o.signature), - { + txHash = await this._contractWrappers.exchange + .marketSellOrdersNoThrow(orders, takerAssetFillAmount, orders.map(o => o.signature)) + .sendTransactionAsync({ from: finalTakerAddress, gas: gasLimit, gasPrice, - }, - ); + }); } return txHash; } catch (err) { diff --git a/packages/asset-swapper/src/quote_consumers/forwarder_swap_quote_consumer.ts b/packages/asset-swapper/src/quote_consumers/forwarder_swap_quote_consumer.ts index a709fa53db..82420df4a9 100644 --- a/packages/asset-swapper/src/quote_consumers/forwarder_swap_quote_consumer.ts +++ b/packages/asset-swapper/src/quote_consumers/forwarder_swap_quote_consumer.ts @@ -196,32 +196,29 @@ export class ForwarderSwapQuoteConsumer implements SwapQuoteConsumerBase o.signature), - formattedFeePercentage, - feeRecipient, - { + txHash = await this._contractWrappers.forwarder + .marketBuyOrdersWithEth( + orders, + makerAssetFillAmount, + orders.map(o => o.signature), + formattedFeePercentage, + feeRecipient, + ) + .sendTransactionAsync({ value, from: finalTakerAddress.toLowerCase(), gas: gasLimit, gasPrice, - }, - ); + }); } else { - txHash = await this._contractWrappers.forwarder.marketSellOrdersWithEth.sendTransactionAsync( - orders, - orders.map(o => o.signature), - formattedFeePercentage, - feeRecipient, - { + txHash = await this._contractWrappers.forwarder + .marketSellOrdersWithEth(orders, orders.map(o => o.signature), formattedFeePercentage, feeRecipient) + .sendTransactionAsync({ value, from: finalTakerAddress.toLowerCase(), gas: gasLimit, gasPrice, - }, - ); + }); } return txHash; } catch (err) { @@ -236,8 +233,8 @@ export class ForwarderSwapQuoteConsumer implements SwapQuoteConsumerBase { - return this._contractWrappers.devUtils.encodeERC20AssetData.callAsync( - this._contractWrappers.contractAddresses.etherToken, - ); + return this._contractWrappers.devUtils + .encodeERC20AssetData(this._contractWrappers.contractAddresses.etherToken) + .callAsync(); } } diff --git a/packages/asset-swapper/src/swap_quoter.ts b/packages/asset-swapper/src/swap_quoter.ts index c6b5635124..5d2d39bd8c 100644 --- a/packages/asset-swapper/src/swap_quoter.ts +++ b/packages/asset-swapper/src/swap_quoter.ts @@ -214,8 +214,12 @@ export class SwapQuoter { assert.isETHAddressHex('makerTokenAddress', makerTokenAddress); assert.isETHAddressHex('takerTokenAddress', takerTokenAddress); assert.isBigNumber('makerAssetBuyAmount', makerAssetBuyAmount); - const makerAssetData = await this._contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress); - const takerAssetData = await this._contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress); + const makerAssetData = await this._contractWrappers.devUtils + .encodeERC20AssetData(makerTokenAddress) + .callAsync(); + const takerAssetData = await this._contractWrappers.devUtils + .encodeERC20AssetData(takerTokenAddress) + .callAsync(); const swapQuote = this.getMarketBuySwapQuoteForAssetDataAsync( makerAssetData, takerAssetData, @@ -244,8 +248,12 @@ export class SwapQuoter { assert.isETHAddressHex('makerTokenAddress', makerTokenAddress); assert.isETHAddressHex('takerTokenAddress', takerTokenAddress); assert.isBigNumber('takerAssetSellAmount', takerAssetSellAmount); - const makerAssetData = await this._contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress); - const takerAssetData = await this._contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress); + const makerAssetData = await this._contractWrappers.devUtils + .encodeERC20AssetData(makerTokenAddress) + .callAsync(); + const takerAssetData = await this._contractWrappers.devUtils + .encodeERC20AssetData(takerTokenAddress) + .callAsync(); const swapQuote = this.getMarketSellSwapQuoteForAssetDataAsync( makerAssetData, takerAssetData, @@ -372,10 +380,9 @@ export class SwapQuoter { takerAddress: string, ): Promise<[boolean, boolean]> { const orderValidator = this._contractWrappers.orderValidator; - const balanceAndAllowance = await orderValidator.getBalanceAndAllowance.callAsync( - takerAddress, - swapQuote.takerAssetData, - ); + const balanceAndAllowance = await orderValidator + .getBalanceAndAllowance(takerAddress, swapQuote.takerAssetData) + .callAsync(); const allowance = balanceAndAllowance[1]; return [ allowance.isGreaterThanOrEqualTo(swapQuote.bestCaseQuoteInfo.totalTakerTokenAmount), @@ -395,9 +402,9 @@ export class SwapQuoter { * Will throw if ZRX does not exist for the current chain. */ private async _getZrxTokenAssetDataOrThrowAsync(): Promise { - return this._contractWrappers.devUtils.encodeERC20AssetData.callAsync( - this._contractWrappers.contractAddresses.zrxToken, - ); + return this._contractWrappers.devUtils + .encodeERC20AssetData(this._contractWrappers.contractAddresses.zrxToken) + .callAsync(); } /** diff --git a/packages/asset-swapper/src/utils/order_provider_response_processor.ts b/packages/asset-swapper/src/utils/order_provider_response_processor.ts index 82531d0ff4..92442fa52c 100644 --- a/packages/asset-swapper/src/utils/order_provider_response_processor.ts +++ b/packages/asset-swapper/src/utils/order_provider_response_processor.ts @@ -45,10 +45,9 @@ export const orderProviderResponseProcessor = { if (orderValidator !== undefined) { const takerAddresses = _.map(filteredOrders, () => constants.NULL_ADDRESS); try { - const [ordersInfo, tradersInfo] = await orderValidator.getOrdersAndTradersInfo.callAsync( - filteredOrders, - takerAddresses, - ); + const [ordersInfo, tradersInfo] = await orderValidator + .getOrdersAndTradersInfo(filteredOrders, takerAddresses) + .callAsync(); const ordersAndTradersInfo: any[] = ordersInfo.map((orderInfo, index) => { const singleOrderAndTraderInfo = { orderInfo, diff --git a/packages/asset-swapper/src/utils/swap_quote_consumer_utils.ts b/packages/asset-swapper/src/utils/swap_quote_consumer_utils.ts index 3a1fd1c9d8..87be11f339 100644 --- a/packages/asset-swapper/src/utils/swap_quote_consumer_utils.ts +++ b/packages/asset-swapper/src/utils/swap_quote_consumer_utils.ts @@ -52,7 +52,7 @@ export const swapQuoteConsumerUtils = { ): Promise<[BigNumber, BigNumber]> { const web3Wrapper = new Web3Wrapper(provider); const ethBalance = await web3Wrapper.getBalanceInWeiAsync(takerAddress); - const wethBalance = await contractWrappers.weth9.balanceOf.callAsync(takerAddress); + const wethBalance = await contractWrappers.weth9.balanceOf(takerAddress).callAsync(); return [ethBalance, wethBalance]; }, isValidForwarderSwapQuote(swapQuote: SwapQuote, wethAssetData: string): boolean { @@ -84,9 +84,9 @@ export const swapQuoteConsumerUtils = { provider: Provider, opts: Partial, ): Promise { - const wethAssetData = await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - contractWrappers.contractAddresses.etherToken, - ); + const wethAssetData = await contractWrappers.devUtils + .encodeERC20AssetData(contractWrappers.contractAddresses.etherToken) + .callAsync(); if (swapQuoteConsumerUtils.isValidForwarderSwapQuote(quote, wethAssetData)) { if (opts.takerAddress !== undefined) { assert.isETHAddressHex('takerAddress', opts.takerAddress); 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 f48f28c856..880435e249 100644 --- a/packages/asset-swapper/test/exchange_swap_quote_consumer_test.ts +++ b/packages/asset-swapper/test/exchange_swap_quote_consumer_test.ts @@ -66,9 +66,9 @@ describe('ExchangeSwapQuoteConsumer', () => { [coinbaseAddress, takerAddress, makerAddress, feeRecipient] = userAddresses; [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); [makerAssetData, takerAssetData, wethAssetData] = [ - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(contractAddresses.etherToken), + await contractWrappers.devUtils.encodeERC20AssetData(makerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(takerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(contractAddresses.etherToken).callAsync(), ]; erc20TokenContract = new ERC20TokenContract(makerTokenAddress, provider); @@ -79,12 +79,12 @@ describe('ExchangeSwapQuoteConsumer', () => { takerAddress, makerAssetData, takerAssetData, - makerFeeAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - contractAddresses.zrxToken, - ), - takerFeeAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - contractAddresses.zrxToken, - ), + makerFeeAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(contractAddresses.zrxToken) + .callAsync(), + takerFeeAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(contractAddresses.zrxToken) + .callAsync(), exchangeAddress: contractAddresses.exchange, chainId, }; @@ -132,24 +132,24 @@ describe('ExchangeSwapQuoteConsumer', () => { * Does not test the validity of the state change performed by the forwarder smart contract */ it('should perform a marketSell execution when provided a MarketSell type swapQuote', async () => { - let makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketSellSwapQuote, { takerAddress }); - makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should perform a marketBuy execution when provided a MarketBuy type swapQuote', async () => { - let makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketBuySwapQuote, { takerAddress }); - makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); }); @@ -192,8 +192,8 @@ describe('ExchangeSwapQuoteConsumer', () => { describe('getCalldataOrThrow', () => { describe('valid swap quote', async () => { it('provide correct and optimized calldata options with default options for a marketSell SwapQuote (no affiliate fees)', async () => { - let makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); const { calldataHexString, toAddress } = await swapQuoteConsumer.getCalldataOrThrowAsync( @@ -207,14 +207,14 @@ describe('ExchangeSwapQuoteConsumer', () => { data: calldataHexString, gas: 4000000, }); - makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('provide correct and optimized calldata options with default options for a marketBuy SwapQuote (no affiliate fees)', async () => { - let makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); const { calldataHexString, toAddress } = await swapQuoteConsumer.getCalldataOrThrowAsync( @@ -228,8 +228,8 @@ describe('ExchangeSwapQuoteConsumer', () => { data: calldataHexString, gas: 4000000, }); - makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); }); 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 6102ac862a..2cdbd90386 100644 --- a/packages/asset-swapper/test/forwarder_swap_quote_consumer_test.ts +++ b/packages/asset-swapper/test/forwarder_swap_quote_consumer_test.ts @@ -66,9 +66,9 @@ describe('ForwarderSwapQuoteConsumer', () => { [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); erc20Token = new ERC20TokenContract(makerTokenAddress, provider); [makerAssetData, takerAssetData, wethAssetData] = [ - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(contractAddresses.etherToken), + await contractWrappers.devUtils.encodeERC20AssetData(makerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(takerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(contractAddresses.etherToken).callAsync(), ]; }); after(async () => { @@ -84,11 +84,11 @@ describe('ForwarderSwapQuoteConsumer', () => { new BigNumber(0), ); - await erc20Token.transfer.sendTransactionAsync(makerAddress, totalFillableAmount, { + await erc20Token.transfer(makerAddress, totalFillableAmount).sendTransactionAsync({ from: coinbaseAddress, }); - await erc20Token.approve.sendTransactionAsync(erc20ProxyAddress, UNLIMITED_ALLOWANCE, { + await erc20Token.approve(erc20ProxyAddress, UNLIMITED_ALLOWANCE).sendTransactionAsync({ from: makerAddress, }); orders = await getSignedOrdersWithNoFeesAsync( @@ -154,32 +154,32 @@ describe('ForwarderSwapQuoteConsumer', () => { * Does not test the validity of the state change performed by the forwarder smart contract */ it('should perform a marketSell execution when provided a MarketSell type swapQuote', async () => { - let makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketSellSwapQuote, { takerAddress }); - makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(0.5).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(new BigNumber(9.5).multipliedBy(ONE_ETH_IN_WEI)); }); it('should perform a marketBuy execution when provided a MarketBuy type swapQuote', async () => { - let makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketBuySwapQuote, { takerAddress }); - makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); }); it('should perform a marketBuy execution with affiliate fees', async () => { - let makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); const feeRecipientEthBalanceBefore = await web3Wrapper.getBalanceInWeiAsync(feeRecipient); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); @@ -188,8 +188,8 @@ describe('ForwarderSwapQuoteConsumer', () => { feePercentage: 0.05, feeRecipient, }); - makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); const feeRecipientEthBalanceAfter = await web3Wrapper.getBalanceInWeiAsync(feeRecipient); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); @@ -200,15 +200,15 @@ describe('ForwarderSwapQuoteConsumer', () => { // TODO(david) Finish marketSell affiliate fee excution testing // it('should perform a marketSell execution with affiliate fees', async () => { - // let makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - // let takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + // let makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + // let takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); // const feeRecipientEthBalanceBefore = await web3Wrapper.getBalanceInWeiAsync(feeRecipient); // expect(makerBalance).to.bignumber.equal((new BigNumber(10)).multipliedBy(ONE_ETH_IN_WEI)); // expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); // console.log(makerBalance, takerBalance, feeRecipientEthBalanceBefore); // await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketSellSwapQuote, { takerAddress, feePercentage: 0.05, feeRecipient }); - // makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - // takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + // makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + // takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); // const feeRecipientEthBalanceAfter = await web3Wrapper.getBalanceInWeiAsync(feeRecipient); // console.log(makerBalance, takerBalance, feeRecipientEthBalanceAfter); // expect(makerBalance).to.bignumber.equal((new BigNumber(0.5)).multipliedBy(ONE_ETH_IN_WEI)); @@ -364,8 +364,8 @@ describe('ForwarderSwapQuoteConsumer', () => { describe('valid swap quote', async () => { it('provide correct and optimized calldata options with default options for a marketSell SwapQuote (no affiliate fees)', async () => { - let makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); const { calldataHexString, toAddress } = await swapQuoteConsumer.getCalldataOrThrowAsync( @@ -380,14 +380,14 @@ describe('ForwarderSwapQuoteConsumer', () => { value: marketSellSwapQuote.worstCaseQuoteInfo.totalTakerTokenAmount, gas: 4000000, }); - makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(0.5).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(new BigNumber(9.5).multipliedBy(ONE_ETH_IN_WEI)); }); it('provide correct and optimized calldata options with default options for a marketBuy SwapQuote (no affiliate fees)', async () => { - let makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - let takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + let makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + let takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); const { calldataHexString, toAddress } = await swapQuoteConsumer.getCalldataOrThrowAsync( @@ -402,8 +402,8 @@ describe('ForwarderSwapQuoteConsumer', () => { value: marketBuySwapQuote.worstCaseQuoteInfo.totalTakerTokenAmount, gas: 4000000, }); - makerBalance = await erc20Token.balanceOf.callAsync(makerAddress); - takerBalance = await erc20Token.balanceOf.callAsync(takerAddress); + makerBalance = await erc20Token.balanceOf(makerAddress).callAsync(); + takerBalance = await erc20Token.balanceOf(takerAddress).callAsync(); expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); }); diff --git a/packages/asset-swapper/test/swap_quote_consumer_test.ts b/packages/asset-swapper/test/swap_quote_consumer_test.ts index e8329f1115..69cc975158 100644 --- a/packages/asset-swapper/test/swap_quote_consumer_test.ts +++ b/packages/asset-swapper/test/swap_quote_consumer_test.ts @@ -60,9 +60,9 @@ describe('SwapQuoteConsumer', () => { [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); erc20Token = new ERC20TokenContract(makerTokenAddress, provider); [makerAssetData, takerAssetData, wethAssetData] = [ - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(contractAddresses.etherToken), + await contractWrappers.devUtils.encodeERC20AssetData(makerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(takerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(contractAddresses.etherToken).callAsync(), ]; }); after(async () => { @@ -78,11 +78,11 @@ describe('SwapQuoteConsumer', () => { new BigNumber(0), ); - await erc20Token.transfer.sendTransactionAsync(makerAddress, totalFillableAmount, { + await erc20Token.transfer(makerAddress, totalFillableAmount).sendTransactionAsync({ from: coinbaseAddress, }); - await erc20Token.approve.sendTransactionAsync(erc20ProxyAddress, UNLIMITED_ALLOWANCE, { + await erc20Token.approve(erc20ProxyAddress, UNLIMITED_ALLOWANCE).sendTransactionAsync({ from: makerAddress, }); orders = await getSignedOrdersWithNoFeesAsync( @@ -116,24 +116,24 @@ describe('SwapQuoteConsumer', () => { // * Does not test the validity of the state change performed by the forwarder smart contract // */ // it('should perform an asset swap with Forwarder contract when provided corresponding useExtensionContract option', async () => { - // let makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - // let takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + // let makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + // let takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); // expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); // expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); // await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketSellSwapQuote, { takerAddress, useExtensionContract: ConsumerType.Forwarder }); - // makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - // takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + // makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + // takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); // expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); // expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); // }); // it('should perform an asset swap with Exchange contract when provided corresponding useExtensionContract option', async () => { - // let makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - // let takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + // let makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + // let takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); // expect(makerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); // expect(takerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); // await swapQuoteConsumer.executeSwapQuoteOrThrowAsync(marketBuySwapQuote, { takerAddress }); - // makerBalance = await erc20TokenContract.balanceOf.callAsync(makerAddress); - // takerBalance = await erc20TokenContract.balanceOf.callAsync(takerAddress); + // makerBalance = await erc20TokenContract.balanceOf(makerAddress).callAsync(); + // takerBalance = await erc20TokenContract.balanceOf(takerAddress).callAsync(); // expect(takerBalance).to.bignumber.equal(new BigNumber(10).multipliedBy(ONE_ETH_IN_WEI)); // expect(makerBalance).to.bignumber.equal(constants.ZERO_AMOUNT); // }); 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 b5e782c96a..cc9b02728f 100644 --- a/packages/asset-swapper/test/swap_quote_consumer_utils_test.ts +++ b/packages/asset-swapper/test/swap_quote_consumer_utils_test.ts @@ -52,9 +52,9 @@ describe('swapQuoteConsumerUtils', () => { [takerAddress, makerAddress] = userAddresses; [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); [makerAssetData, takerAssetData, wethAssetData] = [ - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(contractAddresses.etherToken), + await contractWrappers.devUtils.encodeERC20AssetData(makerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(takerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(contractAddresses.etherToken).callAsync(), ]; swapQuoteConsumer = new SwapQuoteConsumer(provider, { @@ -145,7 +145,7 @@ describe('swapQuoteConsumerUtils', () => { }); it('should return exchange consumer if takerAsset is wEth and taker has enough weth', async () => { const etherInWei = new BigNumber(20).multipliedBy(ONE_ETH_IN_WEI); - await contractWrappers.weth9.deposit.sendTransactionAsync({ value: etherInWei, from: takerAddress }); + await contractWrappers.weth9.deposit().sendTransactionAsync({ value: etherInWei, from: takerAddress }); const extensionContractType = await swapQuoteConsumer.getOptimalExtensionContractTypeAsync( forwarderSwapQuote, { takerAddress }, @@ -154,7 +154,7 @@ describe('swapQuoteConsumerUtils', () => { }); it('should return forwarder consumer if takerAsset is wEth and takerAddress has no available balance in either weth or eth (defaulting behavior)', async () => { const etherInWei = new BigNumber(50).multipliedBy(ONE_ETH_IN_WEI); - await contractWrappers.weth9.deposit.sendTransactionAsync({ value: etherInWei, from: takerAddress }); + await contractWrappers.weth9.deposit().sendTransactionAsync({ value: etherInWei, from: takerAddress }); const extensionContractType = await swapQuoteConsumer.getOptimalExtensionContractTypeAsync( largeForwarderSwapQuote, { takerAddress }, diff --git a/packages/base-contract/CHANGELOG.json b/packages/base-contract/CHANGELOG.json index 0eab06df15..37d5dc32ac 100644 --- a/packages/base-contract/CHANGELOG.json +++ b/packages/base-contract/CHANGELOG.json @@ -9,6 +9,14 @@ { "note": "Remove duplicate types `IndexedFilterValues`, `DecodedLogEvent`, `EventCallback`", "pr": 2243 + }, + { + "note": "Added ContractFunctionObj type and supporting types", + "pr": 2325 + }, + { + "note": "Added AwaitTransactionSuccessOpts and SendTransactionOpts", + "pr": 2325 } ], "timestamp": 1573159180 diff --git a/packages/base-contract/src/index.ts b/packages/base-contract/src/index.ts index a1c5937be2..1eb2d0fd67 100644 --- a/packages/base-contract/src/index.ts +++ b/packages/base-contract/src/index.ts @@ -29,11 +29,20 @@ import { default as VM } from 'ethereumjs-vm'; import PStateManager from 'ethereumjs-vm/dist/state/promisified'; import * as _ from 'lodash'; +export { methodAbiToFunctionSignature } from './utils'; + import { formatABIDataItem } from './utils'; export { SubscriptionManager } from './subscription_manager'; -export * from './types'; +export { + ContractEvent, + SendTransactionOpts, + AwaitTransactionSuccessOpts, + ContractFunctionObj, + ContractTxFunctionObj, + SubscriptionErrors, +} from './types'; export interface AbiEncoderByFunctionSignature { [key: string]: AbiEncoder.Method; diff --git a/packages/base-contract/src/types.ts b/packages/base-contract/src/types.ts index 5414dd2090..e834668e46 100644 --- a/packages/base-contract/src/types.ts +++ b/packages/base-contract/src/types.ts @@ -1,4 +1,6 @@ -import { LogEntryEvent } from 'ethereum-types'; +import { BlockParam, CallData, LogEntryEvent, TransactionReceiptWithDecodedLogs, TxData } from 'ethereum-types'; + +import { PromiseWithTransactionHash } from './index'; export type LogEvent = LogEntryEvent; @@ -18,3 +20,36 @@ export enum SubscriptionErrors { SubscriptionNotFound = 'SUBSCRIPTION_NOT_FOUND', SubscriptionAlreadyPresent = 'SUBSCRIPTION_ALREADY_PRESENT', } + +/** + * Used with `sendTransactionAsync` + * * shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before + * broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default=true. + */ +export interface SendTransactionOpts { + shouldValidate?: boolean; +} + +/** + * Used with `awaitTransactionSuccessAsync` + * * pollingIntervalMs: Determine polling intervals in milliseconds + * * timeoutMs: Determines timeout in milliseconds + */ +export interface AwaitTransactionSuccessOpts extends SendTransactionOpts { + pollingIntervalMs?: number; + timeoutMs?: number; +} + +export interface ContractFunctionObj { + callAsync(callData?: Partial, defaultBlock?: BlockParam): Promise; + getABIEncodedTransactionData(): string; +} + +export interface ContractTxFunctionObj extends ContractFunctionObj { + sendTransactionAsync(txData?: Partial, opts?: SendTransactionOpts): Promise; + awaitTransactionSuccessAsync( + txData?: Partial, + opts?: AwaitTransactionSuccessOpts, + ): PromiseWithTransactionHash; + estimateGasAsync(txData?: Partial): Promise; +} diff --git a/packages/base-contract/src/utils.ts b/packages/base-contract/src/utils.ts index 61f176df5d..24273051f2 100644 --- a/packages/base-contract/src/utils.ts +++ b/packages/base-contract/src/utils.ts @@ -1,4 +1,4 @@ -import { DataItem } from 'ethereum-types'; +import { DataItem, MethodAbi } from 'ethereum-types'; import * as _ from 'lodash'; // tslint:disable-next-line:completed-docs @@ -23,3 +23,22 @@ export function formatABIDataItem(abi: DataItem, value: any, formatter: (type: s return formatter(abi.type, value); } } + +function dataItemsToABIString(dataItems: DataItem[]): string { + const types = dataItems.map(item => { + if (item.components) { + return `(${dataItemsToABIString(item.components)})`; + } else { + return item.type; + } + }); + return `${types.join(',')}`; +} +/** + * Takes a MethodAbi and returns a function signature for ABI encoding/decoding + * @return a function signature as a string, e.g. 'functionName(uint256, bytes[])' + */ +export function methodAbiToFunctionSignature(methodAbi: MethodAbi): string { + const inputs = dataItemsToABIString(methodAbi.inputs); + return `${methodAbi.name}(${inputs})`; +} diff --git a/packages/contract-wrappers/CHANGELOG.json b/packages/contract-wrappers/CHANGELOG.json index b458b6b125..74404c2265 100644 --- a/packages/contract-wrappers/CHANGELOG.json +++ b/packages/contract-wrappers/CHANGELOG.json @@ -5,6 +5,14 @@ { "note": "[Breaking] Remove `erc20Proxy`, `erc721Proxy` and `dutchAuction` wrappers", "pr": 2324 + }, + { + "note": "[Breaking] Big refactor of contract wrapper interface. See https://github.com/0xProject/0x-monorepo/pull/2325 for details", + "pr": 2325 + }, + { + "note": "Export types `ContractFunctionObj` and `ContractTxFunctionObj`", + "pr": 2325 } ] }, diff --git a/packages/contract-wrappers/src/coordinator_wrapper.ts b/packages/contract-wrappers/src/coordinator_wrapper.ts index 40250ba9cb..75708f87ab 100644 --- a/packages/contract-wrappers/src/coordinator_wrapper.ts +++ b/packages/contract-wrappers/src/coordinator_wrapper.ts @@ -24,7 +24,6 @@ import { CoordinatorServerResponse, } 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 @@ -110,12 +109,9 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData( - 'fillOrder', - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); + const data = this._exchangeInstance + .fillOrder(signedOrder, takerAssetFillAmount, signedOrder.signature) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, [signedOrder], orderTransactionOpts); return txHash; } @@ -143,12 +139,9 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData( - 'fillOrKillOrder', - signedOrder, - takerAssetFillAmount, - signedOrder.signature, - ); + const data = this._exchangeInstance + .fillOrKillOrder(signedOrder, takerAssetFillAmount, signedOrder.signature) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, [signedOrder], orderTransactionOpts); return txHash; } @@ -183,12 +176,9 @@ export class CoordinatorWrapper { await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); const signatures = signedOrders.map(o => o.signature); - const data = this._getAbiEncodedTransactionData( - 'batchFillOrders', - signedOrders, - takerAssetFillAmounts, - signatures, - ); + const data = this._exchangeInstance + .batchFillOrders(signedOrders, takerAssetFillAmounts, signatures) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -218,12 +208,9 @@ export class CoordinatorWrapper { await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); const signatures = signedOrders.map(o => o.signature); - const data = this._getAbiEncodedTransactionData( - 'batchFillOrdersNoThrow', - signedOrders, - takerAssetFillAmounts, - signatures, - ); + const data = this._exchangeInstance + .batchFillOrdersNoThrow(signedOrders, takerAssetFillAmounts, signatures) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -253,12 +240,9 @@ export class CoordinatorWrapper { await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); const signatures = signedOrders.map(o => o.signature); - const data = this._getAbiEncodedTransactionData( - 'batchFillOrKillOrders', - signedOrders, - takerAssetFillAmounts, - signatures, - ); + const data = this._exchangeInstance + .batchFillOrKillOrders(signedOrders, takerAssetFillAmounts, signatures) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -286,12 +270,9 @@ export class CoordinatorWrapper { await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); const signatures = signedOrders.map(o => o.signature); - const data = this._getAbiEncodedTransactionData( - 'marketBuyOrdersNoThrow', - signedOrders, - makerAssetFillAmount, - signatures, - ); + const data = this._exchangeInstance + .marketBuyOrdersNoThrow(signedOrders, makerAssetFillAmount, signatures) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -319,12 +300,9 @@ export class CoordinatorWrapper { await assert.isSenderAddressAsync('takerAddress', takerAddress, this._web3Wrapper); const signatures = signedOrders.map(o => o.signature); - const data = this._getAbiEncodedTransactionData( - 'marketSellOrdersNoThrow', - signedOrders, - takerAssetFillAmount, - signatures, - ); + const data = this._exchangeInstance + .marketSellOrdersNoThrow(signedOrders, takerAssetFillAmount, signatures) + .getABIEncodedTransactionData(); const txHash = await this._handleFillsAsync(data, takerAddress, signedOrders, orderTransactionOpts); return txHash; } @@ -341,7 +319,7 @@ export class CoordinatorWrapper { assert.isETHAddressHex('feeRecipientAddress', order.feeRecipientAddress); assert.isSenderAddressAsync('makerAddress', order.makerAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData('cancelOrder', order); + const data = this._exchangeInstance.cancelOrder(order).getABIEncodedTransactionData(); const transaction = await this._generateSignedZeroExTransactionAsync(data, order.makerAddress); const endpoint = await this._getServerEndpointOrThrowAsync(order.feeRecipientAddress); @@ -375,7 +353,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orders', orders, schemas.ordersSchema); const makerAddress = getMakerAddressOrThrow(orders); assert.isSenderAddressAsync('makerAddress', makerAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData('batchCancelOrders', orders); + const data = this._exchangeInstance.batchCancelOrders(orders).getABIEncodedTransactionData(); const serverEndpointsToOrders = await this._mapServerEndpointsToOrdersAsync(orders); @@ -433,7 +411,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('makerAddress', order.makerAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData('cancelOrder', order); + const data = this._exchangeInstance.cancelOrder(order).getABIEncodedTransactionData(); const transaction = await this._generateSignedZeroExTransactionAsync(data, order.makerAddress); const approvalSignatures = new Array(); @@ -466,7 +444,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('makerAddress', makerAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData('batchCancelOrders', orders); + const data = this._exchangeInstance.batchCancelOrders(orders).getABIEncodedTransactionData(); const transaction = await this._generateSignedZeroExTransactionAsync(data, makerAddress); const approvalSignatures = new Array(); @@ -501,7 +479,7 @@ export class CoordinatorWrapper { assert.doesConformToSchema('orderTransactionOpts', orderTransactionOpts, orderTxOptsSchema, [txOptsSchema]); await assert.isSenderAddressAsync('senderAddress', senderAddress, this._web3Wrapper); - const data = this._getAbiEncodedTransactionData('cancelOrdersUpTo', targetOrderEpoch); + const data = this._exchangeInstance.cancelOrdersUpTo(targetOrderEpoch).getABIEncodedTransactionData(); const transaction = await this._generateSignedZeroExTransactionAsync(data, senderAddress); const approvalSignatures = new Array(); @@ -543,13 +521,15 @@ export class CoordinatorWrapper { assert.isHexString('approvalSignature', approvalSignature); } - await this._contractInstance.assertValidCoordinatorApprovals.callAsync( - transaction, - txOrigin, - transactionSignature, - approvalExpirationTimeSeconds, - approvalSignatures, - ); + await this._contractInstance + .assertValidCoordinatorApprovals( + transaction, + txOrigin, + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ) + .callAsync(); } /** @@ -561,14 +541,10 @@ export class CoordinatorWrapper { public async getSignerAddressAsync(hash: string, signature: string): Promise { assert.isHexString('hash', hash); assert.isHexString('signature', signature); - const signerAddress = await this._contractInstance.getSignerAddress.callAsync(hash, signature); + const signerAddress = await this._contractInstance.getSignerAddress(hash, signature).callAsync(); return signerAddress; } - private _getAbiEncodedTransactionData(methodName: K, ...args: any[]): string { - return getAbiEncodedTransactionData(this._exchangeInstance, methodName, ...args); - } - private async _handleFillsAsync( data: string, takerAddress: string, @@ -665,7 +641,7 @@ export class CoordinatorWrapper { feeRecipient: string, registryInstance: CoordinatorRegistryContract, ): Promise { - const coordinatorOperatorEndpoint = await registryInstance.getCoordinatorEndpoint.callAsync(feeRecipient); + const coordinatorOperatorEndpoint = await registryInstance.getCoordinatorEndpoint(feeRecipient).callAsync(); if (coordinatorOperatorEndpoint === '' || coordinatorOperatorEndpoint === undefined) { throw new Error( `No Coordinator server endpoint found in Coordinator Registry for feeRecipientAddress: ${feeRecipient}. Registry contract address: ${ @@ -744,33 +720,35 @@ export class CoordinatorWrapper { orderTransactionOpts: OrderTransactionOpts, ): Promise { if (orderTransactionOpts.shouldValidate) { - await this._contractInstance.executeTransaction.callAsync( - transaction, - txOrigin, - transactionSignature, - approvalExpirationTimeSeconds, - approvalSignatures, - { + await this._contractInstance + .executeTransaction( + transaction, + txOrigin, + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ) + .callAsync({ from: txOrigin, gas: orderTransactionOpts.gasLimit, gasPrice: orderTransactionOpts.gasPrice, nonce: orderTransactionOpts.nonce, - }, - ); + }); } - const txHash = await this._contractInstance.executeTransaction.sendTransactionAsync( - transaction, - txOrigin, - transactionSignature, - approvalExpirationTimeSeconds, - approvalSignatures, - { + const txHash = await this._contractInstance + .executeTransaction( + transaction, + txOrigin, + transactionSignature, + approvalExpirationTimeSeconds, + approvalSignatures, + ) + .sendTransactionAsync({ from: txOrigin, gas: orderTransactionOpts.gasLimit, gasPrice: orderTransactionOpts.gasPrice, nonce: orderTransactionOpts.nonce, - }, - ); + }); return txHash; } diff --git a/packages/contract-wrappers/src/index.ts b/packages/contract-wrappers/src/index.ts index bb485fd048..48a6c6c80d 100644 --- a/packages/contract-wrappers/src/index.ts +++ b/packages/contract-wrappers/src/index.ts @@ -133,8 +133,6 @@ export { SignedZeroExTransaction, SimpleEvmOutput, SimpleEvmBytecodeOutput, - AwaitTransactionSuccessOpts, - SendTransactionOpts, EIP712DomainWithDefaultSchema, EventCallback, DecodedLogEvent, @@ -142,3 +140,9 @@ export { } from '@0x/types'; export { AbiDecoder, DecodedCalldata } from '@0x/utils'; +export { + AwaitTransactionSuccessOpts, + SendTransactionOpts, + ContractFunctionObj, + ContractTxFunctionObj, +} from '@0x/base-contract'; diff --git a/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts b/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts deleted file mode 100644 index 79ebd8833b..0000000000 --- a/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { ExchangeContract } from '@0x/abi-gen-wrappers'; - -/** - * 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/test/calldata_decoder_test.ts b/packages/contract-wrappers/test/calldata_decoder_test.ts index e205e63725..15f74a34e1 100644 --- a/packages/contract-wrappers/test/calldata_decoder_test.ts +++ b/packages/contract-wrappers/test/calldata_decoder_test.ts @@ -7,7 +7,6 @@ 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'; @@ -56,48 +55,48 @@ describe('ABI Decoding Calldata', () => { // Values are arbitrary, with the exception of maker addresses (generated above). orderLeft = { makerAddress: makerAddressLeft, - makerAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), + makerAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), makerAssetAmount: new BigNumber(10), takerAddress: '0x0000000000000000000000000000000000000000', - takerAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), + takerAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), takerAssetAmount: new BigNumber(1), feeRecipientAddress, makerFee: new BigNumber(0), takerFee: new BigNumber(0), - makerFeeAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), - takerFeeAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), + makerFeeAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), + takerFeeAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), senderAddress: '0x0000000000000000000000000000000000000000', expirationTimeSeconds: new BigNumber(1549498915), salt: new BigNumber(217), }; orderRight = { makerAddress: makerAddressRight, - makerAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), + makerAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), makerAssetAmount: new BigNumber(1), takerAddress: '0x0000000000000000000000000000000000000000', - takerAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), + takerAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), takerAssetAmount: new BigNumber(8), feeRecipientAddress, makerFee: new BigNumber(0), takerFee: new BigNumber(0), - makerFeeAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), - takerFeeAssetData: await contractWrappers.devUtils.encodeERC20AssetData.callAsync( - defaultERC20MakerAssetAddress, - ), + makerFeeAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), + takerFeeAssetData: await contractWrappers.devUtils + .encodeERC20AssetData(defaultERC20MakerAssetAddress) + .callAsync(), senderAddress: '0x0000000000000000000000000000000000000000', expirationTimeSeconds: new BigNumber(1549498915), salt: new BigNumber(50010), @@ -107,14 +106,9 @@ describe('ABI Decoding Calldata', () => { const orderFactoryRight = new OrderFactory(privateKeyRight, orderRight); signedOrderRight = await orderFactoryRight.newSignedOrderAsync(domainInfo); // Encode match orders transaction - matchOrdersTxData = getAbiEncodedTransactionData( - contractWrappers.exchange, - 'matchOrders', - signedOrderLeft, - signedOrderRight, - signedOrderLeft.signature, - signedOrderRight.signature, - ); + matchOrdersTxData = contractWrappers.exchange + .matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature) + .getABIEncodedTransactionData(); }); describe('decode', () => { diff --git a/packages/contract-wrappers/test/coordinator_wrapper_test.ts b/packages/contract-wrappers/test/coordinator_wrapper_test.ts index 6589f2ce3c..ff459a4b5a 100644 --- a/packages/contract-wrappers/test/coordinator_wrapper_test.ts +++ b/packages/contract-wrappers/test/coordinator_wrapper_test.ts @@ -85,9 +85,9 @@ describe.skip('CoordinatorWrapper', () => { [makerTokenAddress, takerTokenAddress] = tokenUtils.getDummyERC20TokenAddresses(); feeTokenAddress = contractAddresses.zrxToken; [makerAssetData, takerAssetData, feeAssetData] = [ - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(makerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(takerTokenAddress), - await contractWrappers.devUtils.encodeERC20AssetData.callAsync(feeTokenAddress), + await contractWrappers.devUtils.encodeERC20AssetData(makerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(takerTokenAddress).callAsync(), + await contractWrappers.devUtils.encodeERC20AssetData(feeTokenAddress).callAsync(), ]; // Configure order defaults @@ -190,32 +190,29 @@ describe.skip('CoordinatorWrapper', () => { // register coordinator server await web3Wrapper.awaitTransactionSuccessAsync( - await coordinatorRegistryInstance.setCoordinatorEndpoint.sendTransactionAsync( - `${coordinatorEndpoint}${coordinatorPort}`, - { + await coordinatorRegistryInstance + .setCoordinatorEndpoint(`${coordinatorEndpoint}${coordinatorPort}`) + .sendTransactionAsync({ from: feeRecipientAddressOne, - }, - ), + }), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await coordinatorRegistryInstance.setCoordinatorEndpoint.sendTransactionAsync( - `${coordinatorEndpoint}${coordinatorPort}`, - { + await coordinatorRegistryInstance + .setCoordinatorEndpoint(`${coordinatorEndpoint}${coordinatorPort}`) + .sendTransactionAsync({ from: feeRecipientAddressTwo, - }, - ), + }), constants.AWAIT_TRANSACTION_MINED_MS, ); // register another coordinator server await web3Wrapper.awaitTransactionSuccessAsync( - await coordinatorRegistryInstance.setCoordinatorEndpoint.sendTransactionAsync( - `${coordinatorEndpoint}${anotherCoordinatorPort}`, - { + await coordinatorRegistryInstance + .setCoordinatorEndpoint(`${coordinatorEndpoint}${anotherCoordinatorPort}`) + .sendTransactionAsync({ from: feeRecipientAddressThree, - }, - ), + }), constants.AWAIT_TRANSACTION_MINED_MS, ); }); @@ -238,12 +235,12 @@ describe.skip('CoordinatorWrapper', () => { }); describe('test setup', () => { it('should have coordinator registry which returns an endpoint', async () => { - const setCoordinatorEndpoint = await coordinatorRegistryInstance.getCoordinatorEndpoint.callAsync( - feeRecipientAddressOne, - ); - const anotherSetCoordinatorEndpoint = await coordinatorRegistryInstance.getCoordinatorEndpoint.callAsync( - feeRecipientAddressThree, - ); + const setCoordinatorEndpoint = await coordinatorRegistryInstance + .getCoordinatorEndpoint(feeRecipientAddressOne) + .callAsync(); + const anotherSetCoordinatorEndpoint = await coordinatorRegistryInstance + .getCoordinatorEndpoint(feeRecipientAddressThree) + .callAsync(); expect(setCoordinatorEndpoint).to.be.equal(`${coordinatorEndpoint}${coordinatorPort}`); expect(anotherSetCoordinatorEndpoint).to.be.equal(`${coordinatorEndpoint}${anotherCoordinatorPort}`); }); @@ -386,10 +383,9 @@ describe.skip('CoordinatorWrapper', () => { txHash = await contractWrappers.coordinator.hardCancelOrdersUpToAsync(targetOrderEpoch, makerAddress); await web3Wrapper.awaitTransactionSuccessAsync(txHash, constants.AWAIT_TRANSACTION_MINED_MS); - const orderEpoch = await contractWrappers.exchange.orderEpoch.callAsync( - makerAddress, - contractWrappers.coordinator.address, - ); + const orderEpoch = await contractWrappers.exchange + .orderEpoch(makerAddress, contractWrappers.coordinator.address) + .callAsync(); expect(orderEpoch).to.be.bignumber.equal(targetOrderEpoch.plus(1)); }); }); @@ -406,7 +402,7 @@ describe.skip('CoordinatorWrapper', () => { }); it('should throw error when coordinator endpoint is malformed', async () => { await web3Wrapper.awaitTransactionSuccessAsync( - await coordinatorRegistryInstance.setCoordinatorEndpoint.sendTransactionAsync('localhost', { + await coordinatorRegistryInstance.setCoordinatorEndpoint('localhost').sendTransactionAsync({ from: feeRecipientAddressFour, }), constants.AWAIT_TRANSACTION_MINED_MS, diff --git a/packages/contract-wrappers/test/utils/token_utils.ts b/packages/contract-wrappers/test/utils/token_utils.ts index 903fa5b09d..cf98bddb6a 100644 --- a/packages/contract-wrappers/test/utils/token_utils.ts +++ b/packages/contract-wrappers/test/utils/token_utils.ts @@ -28,7 +28,7 @@ export const tokenUtils = { async mintDummyERC721Async(address: string, tokenOwner: string): Promise { const erc721 = new DummyERC721TokenContract(address, provider, txDefaults); const tokenId = generatePseudoRandomSalt(); - const txHash = await erc721.mint.sendTransactionAsync(tokenOwner, tokenId); + const txHash = await erc721.mint(tokenOwner, tokenId).sendTransactionAsync(); web3Wrapper.awaitTransactionSuccessAsync(txHash); return tokenId; }, diff --git a/packages/migrations/src/migration.ts b/packages/migrations/src/migration.ts index 41c2644922..a2247ffc29 100644 --- a/packages/migrations/src/migration.ts +++ b/packages/migrations/src/migration.ts @@ -153,26 +153,26 @@ export async function runMigrationsAsync( artifacts, ); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, txDefaults); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, txDefaults); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, txDefaults); - await multiAssetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, txDefaults); + await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync(txDefaults); + await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync(txDefaults); + await erc1155Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync(txDefaults); + await multiAssetProxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync(txDefaults); // MultiAssetProxy - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, txDefaults); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, txDefaults); - await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, txDefaults); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, txDefaults); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, txDefaults); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, txDefaults); - await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(staticCallProxy.address, txDefaults); + await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync(txDefaults); + await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync(txDefaults); + await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync(txDefaults); + await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync(txDefaults); + await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync(txDefaults); + await multiAssetProxy.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync(txDefaults); + await multiAssetProxy.registerAssetProxy(staticCallProxy.address).awaitTransactionSuccessAsync(txDefaults); // Register the Asset Proxies to the Exchange - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, txDefaults); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, txDefaults); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, txDefaults); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(multiAssetProxy.address, txDefaults); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(staticCallProxy.address, txDefaults); + await exchange.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync(txDefaults); + await exchange.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync(txDefaults); + await exchange.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync(txDefaults); + await exchange.registerAssetProxy(multiAssetProxy.address).awaitTransactionSuccessAsync(txDefaults); + await exchange.registerAssetProxy(staticCallProxy.address).awaitTransactionSuccessAsync(txDefaults); // Forwarder const forwarder = await ForwarderContract.deployFrom0xArtifactAsync( @@ -230,16 +230,16 @@ export async function runMigrationsAsync( // // Transfer Ownership to the Asset Proxy Owner // await web3Wrapper.awaitTransactionSuccessAsync( - // await erc20Proxy.transferOwnership.sendTransactionAsync(assetProxyOwner.address, txDefaults), + // await erc20Proxy.transferOwnership(assetProxyOwner.address).sendTransactionAsync(txDefaults), // ); // await web3Wrapper.awaitTransactionSuccessAsync( - // await erc721Proxy.transferOwnership.sendTransactionAsync(assetProxyOwner.address, txDefaults), + // await erc721Proxy.transferOwnership(assetProxyOwner.address).sendTransactionAsync(txDefaults), // ); // await web3Wrapper.awaitTransactionSuccessAsync( - // await erc1155Proxy.transferOwnership.sendTransactionAsync(assetProxyOwner.address, txDefaults), + // await erc1155Proxy.transferOwnership(assetProxyOwner.address).sendTransactionAsync(txDefaults), // ); // await web3Wrapper.awaitTransactionSuccessAsync( - // await multiAssetProxy.transferOwnership.sendTransactionAsync(assetProxyOwner.address, txDefaults), + // await multiAssetProxy.transferOwnership(assetProxyOwner.address).sendTransactionAsync(txDefaults), // ); // Fake the above transactions so our nonce increases and we result with the same addresses @@ -250,9 +250,9 @@ export async function runMigrationsAsync( } // Fund the Forwarder with ZRX - const zrxDecimals = await zrxToken.decimals.callAsync(); + const zrxDecimals = await zrxToken.decimals().callAsync(); const zrxForwarderAmount = Web3Wrapper.toBaseUnitAmount(new BigNumber(5000), zrxDecimals); - await zrxToken.transfer.awaitTransactionSuccessAsync(forwarder.address, zrxForwarderAmount, txDefaults); + await zrxToken.transfer(forwarder.address, zrxForwarderAmount).awaitTransactionSuccessAsync(txDefaults); // CoordinatorRegistry const coordinatorRegistry = await CoordinatorRegistryContract.deployFrom0xArtifactAsync( diff --git a/packages/migrations/src/test_contract_configs.ts b/packages/migrations/src/test_contract_configs.ts index 3fe2ac5bfa..b3f21d7d91 100644 --- a/packages/migrations/src/test_contract_configs.ts +++ b/packages/migrations/src/test_contract_configs.ts @@ -54,30 +54,30 @@ async function testContractConfigsAsync(provider: SupportedProvider): Promise { - const exchangeOwner = await exchangeV2.owner.callAsync(); + const exchangeOwner = await exchangeV2.owner().callAsync(); warnIfMismatch(exchangeOwner, governor.address, 'Unexpected ExchangeV2 owner'); - const registeredERC20Proxy = await exchangeV2.getAssetProxy.callAsync(AssetProxyId.ERC20); + const registeredERC20Proxy = await exchangeV2.getAssetProxy(AssetProxyId.ERC20).callAsync(); warnIfMismatch(registeredERC20Proxy, erc20Proxy.address, 'Unexpected ERC20Proxy registered in ExchangeV2'); - const registeredERC721Proxy = await exchangeV2.getAssetProxy.callAsync(AssetProxyId.ERC721); + const registeredERC721Proxy = await exchangeV2.getAssetProxy(AssetProxyId.ERC721).callAsync(); warnIfMismatch(registeredERC721Proxy, erc721Proxy.address, 'Unexpected ERC721Proxy registered in ExchangeV2'); - const registeredERC1155Proxy = await exchangeV2.getAssetProxy.callAsync(AssetProxyId.ERC1155); + const registeredERC1155Proxy = await exchangeV2.getAssetProxy(AssetProxyId.ERC1155).callAsync(); warnIfMismatch( registeredERC1155Proxy, erc1155Proxy.address, 'Unexpected ERC1155Proxy registered in ExchangeV2', ); - const registeredMultiAssetProxy = await exchangeV2.getAssetProxy.callAsync(AssetProxyId.MultiAsset); + const registeredMultiAssetProxy = await exchangeV2.getAssetProxy(AssetProxyId.MultiAsset).callAsync(); warnIfMismatch( registeredMultiAssetProxy, multiAssetProxy.address, 'Unexpected MultiAssetProxy registered in ExchangeV2', ); - const registeredStaticCallProxy = await exchangeV2.getAssetProxy.callAsync(AssetProxyId.StaticCall); + const registeredStaticCallProxy = await exchangeV2.getAssetProxy(AssetProxyId.StaticCall).callAsync(); warnIfMismatch( registeredStaticCallProxy, addresses.staticCallProxy, @@ -86,165 +86,171 @@ async function testContractConfigsAsync(provider: SupportedProvider): Promise { - const exchangeOwner = await exchange.owner.callAsync(); + const exchangeOwner = await exchange.owner().callAsync(); warnIfMismatch(exchangeOwner, governor.address, 'Unexpected Exchange owner'); - const registeredERC20Proxy = await exchange.getAssetProxy.callAsync(AssetProxyId.ERC20); + const registeredERC20Proxy = await exchange.getAssetProxy(AssetProxyId.ERC20).callAsync(); warnIfMismatch(registeredERC20Proxy, erc20Proxy.address, 'Unexpected ERC20Proxy registered in Exchange'); - const registeredERC721Proxy = await exchange.getAssetProxy.callAsync(AssetProxyId.ERC721); + const registeredERC721Proxy = await exchange.getAssetProxy(AssetProxyId.ERC721).callAsync(); warnIfMismatch(registeredERC721Proxy, erc721Proxy.address, 'Unexpected ERC721Proxy registered in Exchange'); - const registeredERC1155Proxy = await exchange.getAssetProxy.callAsync(AssetProxyId.ERC1155); + const registeredERC1155Proxy = await exchange.getAssetProxy(AssetProxyId.ERC1155).callAsync(); warnIfMismatch(registeredERC1155Proxy, erc1155Proxy.address, 'Unexpected ERC1155Proxy registered in Exchange'); - const registeredMultiAssetProxy = await exchange.getAssetProxy.callAsync(AssetProxyId.MultiAsset); + const registeredMultiAssetProxy = await exchange.getAssetProxy(AssetProxyId.MultiAsset).callAsync(); warnIfMismatch( registeredMultiAssetProxy, multiAssetProxy.address, 'Unexpected MultiAssetProxy registered in Exchange', ); - const registeredStaticCallProxy = await exchange.getAssetProxy.callAsync(AssetProxyId.StaticCall); + const registeredStaticCallProxy = await exchange.getAssetProxy(AssetProxyId.StaticCall).callAsync(); warnIfMismatch( registeredStaticCallProxy, addresses.staticCallProxy, 'Unexpected StaticCallProxy registered in Exchange', ); - const registeredERC20BridgeProxy = await exchange.getAssetProxy.callAsync(AssetProxyId.ERC20Bridge); + const registeredERC20BridgeProxy = await exchange.getAssetProxy(AssetProxyId.ERC20Bridge).callAsync(); warnIfMismatch( registeredERC20BridgeProxy, addresses.erc20BridgeProxy, 'Unexpected ERC20BridgeProxy registered in Exchange', ); - const protocolFeeCollector = await exchange.protocolFeeCollector.callAsync(); + const protocolFeeCollector = await exchange.protocolFeeCollector().callAsync(); warnIfMismatch(protocolFeeCollector, addresses.stakingProxy, 'Unexpected StakingProxy attached to Exchange'); - const protocolFeeMultiplier = await exchange.protocolFeeMultiplier.callAsync(); + const protocolFeeMultiplier = await exchange.protocolFeeMultiplier().callAsync(); warnIfMismatch(protocolFeeMultiplier.toString(), '150000', 'Unexpected protocolFeeMultiplier in Exchange'); } async function verifyAssetProxyConfigsAsync(): Promise { // Verify ERC20Proxy configs - const erc20ProxyOwner = await erc20Proxy.owner.callAsync(); + const erc20ProxyOwner = await erc20Proxy.owner().callAsync(); warnIfMismatch(erc20ProxyOwner, governor.address, 'Unexpected ERC20Proxy owner'); - const erc20AuthorizedAddresses = await erc20Proxy.getAuthorizedAddresses.callAsync(); + const erc20AuthorizedAddresses = await erc20Proxy.getAuthorizedAddresses().callAsync(); warnIfMismatch(erc20AuthorizedAddresses.length, 4, 'Unexpected number of authorized addresses in ERC20Proxy'); - const isExchangeV2AuthorizedInERC20Proxy = await erc20Proxy.authorized.callAsync(exchangeV2.address); + const isExchangeV2AuthorizedInERC20Proxy = await erc20Proxy.authorized(exchangeV2.address).callAsync(); warnIfMismatch(isExchangeV2AuthorizedInERC20Proxy, true, 'ExchangeV2 not authorized in ERC20Proxy'); - const isExchangeAuthorizedInERC20Proxy = await erc20Proxy.authorized.callAsync(exchange.address); + const isExchangeAuthorizedInERC20Proxy = await erc20Proxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC20Proxy, true, 'Exchange not authorized in ERC20Proxy'); - const isMAPAuthorizedInER20Proxy = await erc20Proxy.authorized.callAsync(multiAssetProxy.address); + const isMAPAuthorizedInER20Proxy = await erc20Proxy.authorized(multiAssetProxy.address).callAsync(); warnIfMismatch(isMAPAuthorizedInER20Proxy, true, 'MultiAssetProxy not authorized in ERC20Proxy'); - const isZrxVaultAuthorizedInER20Proxy = await erc20Proxy.authorized.callAsync(zrxVault.address); + const isZrxVaultAuthorizedInER20Proxy = await erc20Proxy.authorized(zrxVault.address).callAsync(); warnIfMismatch(isZrxVaultAuthorizedInER20Proxy, true, 'ZrxVault not authorized in ERC20Proxy'); // Verify ERC721Proxy configs - const erc721ProxyOwner = await erc721Proxy.owner.callAsync(); + const erc721ProxyOwner = await erc721Proxy.owner().callAsync(); warnIfMismatch(erc721ProxyOwner, governor.address, 'Unexpected ERC721Proxy owner'); - const erc721AuthorizedAddresses = await erc721Proxy.getAuthorizedAddresses.callAsync(); + const erc721AuthorizedAddresses = await erc721Proxy.getAuthorizedAddresses().callAsync(); warnIfMismatch(erc721AuthorizedAddresses.length, 3, 'Unexpected number of authorized addresses in ERC721Proxy'); - const isExchangeV2AuthorizedInERC721Proxy = await erc721Proxy.authorized.callAsync(exchangeV2.address); + const isExchangeV2AuthorizedInERC721Proxy = await erc721Proxy.authorized(exchangeV2.address).callAsync(); warnIfMismatch(isExchangeV2AuthorizedInERC721Proxy, true, 'ExchangeV2 not authorized in ERC721Proxy'); - const isExchangeAuthorizedInERC721Proxy = await erc721Proxy.authorized.callAsync(exchange.address); + const isExchangeAuthorizedInERC721Proxy = await erc721Proxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC721Proxy, true, 'Exchange not authorized in ERC721Proxy'); - const isMAPAuthorizedInER721Proxy = await erc721Proxy.authorized.callAsync(multiAssetProxy.address); + const isMAPAuthorizedInER721Proxy = await erc721Proxy.authorized(multiAssetProxy.address).callAsync(); warnIfMismatch(isMAPAuthorizedInER721Proxy, true, 'MultiAssetProxy not authorized in ERC721Proxy'); // Verify ERC1155Proxy configs - const erc1155ProxyOwner = await erc1155Proxy.owner.callAsync(); + const erc1155ProxyOwner = await erc1155Proxy.owner().callAsync(); warnIfMismatch(erc1155ProxyOwner, governor.address, 'Unexpected ERC1155Proxy owner'); - const erc1155AuthorizedAddresses = await erc1155Proxy.getAuthorizedAddresses.callAsync(); + const erc1155AuthorizedAddresses = await erc1155Proxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( erc1155AuthorizedAddresses.length, 3, 'Unexpected number of authorized addresses in ERC1155Proxy', ); - const isExchangeV2AuthorizedInERC1155Proxy = await erc1155Proxy.authorized.callAsync(exchangeV2.address); + const isExchangeV2AuthorizedInERC1155Proxy = await erc1155Proxy.authorized(exchangeV2.address).callAsync(); warnIfMismatch(isExchangeV2AuthorizedInERC1155Proxy, true, 'ExchangeV2 not authorized in ERC1155Proxy'); - const isExchangeAuthorizedInERC1155Proxy = await erc1155Proxy.authorized.callAsync(exchange.address); + const isExchangeAuthorizedInERC1155Proxy = await erc1155Proxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC1155Proxy, true, 'Exchange not authorized in ERC1155Proxy'); - const isMAPAuthorizedInERC1155Proxy = await erc1155Proxy.authorized.callAsync(multiAssetProxy.address); + const isMAPAuthorizedInERC1155Proxy = await erc1155Proxy.authorized(multiAssetProxy.address).callAsync(); warnIfMismatch(isMAPAuthorizedInERC1155Proxy, true, 'MultiAssetProxy not authorized in ERC1155Proxy'); // Verify ERC20BridgeProxy configs - const erc20BridgeProxyOwner = await erc20BridgeProxy.owner.callAsync(); + const erc20BridgeProxyOwner = await erc20BridgeProxy.owner().callAsync(); warnIfMismatch(erc20BridgeProxyOwner, governor.address, 'Unexpected ERC20BridgeProxy owner'); - const erc20BridgeAuthorizedAddresses = await erc20BridgeProxy.getAuthorizedAddresses.callAsync(); + const erc20BridgeAuthorizedAddresses = await erc20BridgeProxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( erc20BridgeAuthorizedAddresses.length, 2, 'Unexpected number of authorized addresses in ERC20BridgeProxy', ); - const isExchangeAuthorizedInERC20BridgeProxy = await erc20BridgeProxy.authorized.callAsync(exchange.address); + const isExchangeAuthorizedInERC20BridgeProxy = await erc20BridgeProxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInERC20BridgeProxy, true, 'Exchange not authorized in ERC20BridgeProxy'); - const isMAPAuthorizedInERC20BridgeProxy = await erc20BridgeProxy.authorized.callAsync(multiAssetProxy.address); + const isMAPAuthorizedInERC20BridgeProxy = await erc20BridgeProxy + .authorized(multiAssetProxy.address) + .callAsync(); warnIfMismatch(isMAPAuthorizedInERC20BridgeProxy, true, 'MultiAssetProxy not authorized in ERC20BridgeProxy'); // Verify MultiAssetProxy configs - const multiAssetProxyOwner = await multiAssetProxy.owner.callAsync(); + const multiAssetProxyOwner = await multiAssetProxy.owner().callAsync(); warnIfMismatch(multiAssetProxyOwner, governor.address, 'Unexpected MultiAssetProxy owner'); - const multiAssetProxyAuthorizedAddresses = await multiAssetProxy.getAuthorizedAddresses.callAsync(); + const multiAssetProxyAuthorizedAddresses = await multiAssetProxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( multiAssetProxyAuthorizedAddresses.length, 2, 'Unexpected number of authorized addresses in MultiAssetProxy', ); - const isExchangeV2AuthorizedInMultiAssetProxy = await multiAssetProxy.authorized.callAsync(exchangeV2.address); + const isExchangeV2AuthorizedInMultiAssetProxy = await multiAssetProxy + .authorized(exchangeV2.address) + .callAsync(); warnIfMismatch(isExchangeV2AuthorizedInMultiAssetProxy, true, 'ExchangeV2 not authorized in MultiAssetProxy'); - const isExchangeAuthorizedInMultiAssetProxy = await multiAssetProxy.authorized.callAsync(exchange.address); + const isExchangeAuthorizedInMultiAssetProxy = await multiAssetProxy.authorized(exchange.address).callAsync(); warnIfMismatch(isExchangeAuthorizedInMultiAssetProxy, true, 'Exchange not authorized in MultiAssetProxy'); - const registeredERC20ProxyInMAP = await multiAssetProxy.getAssetProxy.callAsync(AssetProxyId.ERC20); + const registeredERC20ProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.ERC20).callAsync(); warnIfMismatch( registeredERC20ProxyInMAP, erc20Proxy.address, 'Unexpected ERC20Proxy registered in MultiAssetProxy', ); - const registeredERC721ProxyInMAP = await multiAssetProxy.getAssetProxy.callAsync(AssetProxyId.ERC721); + const registeredERC721ProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.ERC721).callAsync(); warnIfMismatch( registeredERC721ProxyInMAP, erc721Proxy.address, 'Unexpected ERC721Proxy registered in MultiAssetProxy', ); - const registeredERC1155ProxyInMAP = await multiAssetProxy.getAssetProxy.callAsync(AssetProxyId.ERC1155); + const registeredERC1155ProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.ERC1155).callAsync(); warnIfMismatch( registeredERC1155ProxyInMAP, erc1155Proxy.address, 'Unexpected ERC1155Proxy registered in MultiAssetProxy', ); - const registeredStaticCallProxyInMAP = await multiAssetProxy.getAssetProxy.callAsync(AssetProxyId.StaticCall); + const registeredStaticCallProxyInMAP = await multiAssetProxy.getAssetProxy(AssetProxyId.StaticCall).callAsync(); warnIfMismatch( registeredStaticCallProxyInMAP, addresses.staticCallProxy, 'Unexpected StaticCallProxy registered in MultiAssetProxy', ); - const registeredERC20BridgeProxyInMAP = await multiAssetProxy.getAssetProxy.callAsync(AssetProxyId.ERC20Bridge); + const registeredERC20BridgeProxyInMAP = await multiAssetProxy + .getAssetProxy(AssetProxyId.ERC20Bridge) + .callAsync(); warnIfMismatch( registeredERC20BridgeProxyInMAP, addresses.erc20BridgeProxy, @@ -253,43 +259,43 @@ async function testContractConfigsAsync(provider: SupportedProvider): Promise { - const stakingLogicAddress = await stakingProxy.stakingContract.callAsync(); + const stakingLogicAddress = await stakingProxy.stakingContract().callAsync(); warnIfMismatch(stakingLogicAddress, addresses.staking, 'Unexpected Staking contract attached to StakingProxy'); - const zrxVaultAddress = await stakingContract.getZrxVault.callAsync(); + const zrxVaultAddress = await stakingContract.getZrxVault().callAsync(); warnIfMismatch(zrxVaultAddress, addresses.zrxVault, 'Unexpected ZrxVault set in StakingProxy'); - const wethAddress = await stakingContract.getWethContract.callAsync(); + const wethAddress = await stakingContract.getWethContract().callAsync(); warnIfMismatch(wethAddress, addresses.etherToken, 'Unexpected WETH contract set in StakingProxy'); - const stakingProxyOwner = await stakingProxy.owner.callAsync(); + const stakingProxyOwner = await stakingProxy.owner().callAsync(); warnIfMismatch(stakingProxyOwner, addresses.zeroExGovernor, 'Unexpected StakingProxy owner'); - const stakingProxyAuthorizedAddresses = await stakingProxy.getAuthorizedAddresses.callAsync(); + const stakingProxyAuthorizedAddresses = await stakingProxy.getAuthorizedAddresses().callAsync(); warnIfMismatch( stakingProxyAuthorizedAddresses.length, 1, 'Unexpected number of authorized addresses in StakingProxy', ); - const isGovernorAuthorizedInStakingProxy = await stakingProxy.authorized.callAsync(addresses.zeroExGovernor); + const isGovernorAuthorizedInStakingProxy = await stakingProxy.authorized(addresses.zeroExGovernor).callAsync(); warnIfMismatch(isGovernorAuthorizedInStakingProxy, true, 'ZeroExGovernor not authorized in StakingProxy'); - const zrxVaultOwner = await zrxVault.owner.callAsync(); + const zrxVaultOwner = await zrxVault.owner().callAsync(); warnIfMismatch(zrxVaultOwner, addresses.zeroExGovernor, 'Unexpected ZrxVault owner'); - const zrxVaultAuthorizedAddresses = await zrxVault.getAuthorizedAddresses.callAsync(); + const zrxVaultAuthorizedAddresses = await zrxVault.getAuthorizedAddresses().callAsync(); warnIfMismatch(zrxVaultAuthorizedAddresses.length, 1, 'Unexpected number of authorized addresses in ZrxVault'); - const isGovernorAuthorizedInZrxVault = await zrxVault.authorized.callAsync(addresses.zeroExGovernor); + const isGovernorAuthorizedInZrxVault = await zrxVault.authorized(addresses.zeroExGovernor).callAsync(); warnIfMismatch(isGovernorAuthorizedInZrxVault, true, 'ZeroExGovernor not authorized in ZrxVault'); - const zrxAssetProxy = await zrxVault.zrxAssetProxy.callAsync(); + const zrxAssetProxy = await zrxVault.zrxAssetProxy().callAsync(); warnIfMismatch(zrxAssetProxy, addresses.erc20Proxy, 'Unexpected ERC20Proxy set in ZrxVault'); - const zrxVaultStakingProxy = await zrxVault.stakingProxyAddress.callAsync(); + const zrxVaultStakingProxy = await zrxVault.stakingProxyAddress().callAsync(); warnIfMismatch(zrxVaultStakingProxy, addresses.stakingProxy, 'Unexpected StakingProxy set in ZrxVault'); - const params = await stakingContract.getParams.callAsync(); + const params = await stakingContract.getParams().callAsync(); warnIfMismatch( params[0].toNumber(), configs.staking.epochDurationInSeconds.toNumber(), @@ -320,10 +326,9 @@ async function testContractConfigsAsync(provider: SupportedProvider): Promise { const timelockRegistrations = await getTimelockRegistrationsAsync(provider); for (const timelockRegistration of timelockRegistrations) { - const actualRegistration = await governor.functionCallTimeLocks.callAsync( - timelockRegistration.functionSelector, - timelockRegistration.destination, - ); + const actualRegistration = await governor + .functionCallTimeLocks(timelockRegistration.functionSelector, timelockRegistration.destination) + .callAsync(); warnIfMismatch( actualRegistration[0], true, @@ -340,7 +345,7 @@ async function testContractConfigsAsync(provider: SupportedProvider): Promise { - const txReceipt = await governor.submitTransaction.awaitTransactionSuccessAsync( - destination, - constants.ZERO_AMOUNT, - data, - ); + const { logs } = await governor + .submitTransaction(destination, constants.ZERO_AMOUNT, data) + .awaitTransactionSuccessAsync(); // tslint:disable-next-line:no-unnecessary-type-assertion - const txId = (txReceipt.logs[0] as LogWithDecodedArgs).args.transactionId; + const txId = (logs[0] as LogWithDecodedArgs).args.transactionId; logUtils.log(`${txId} submitted`); - await governor.executeTransaction.awaitTransactionSuccessAsync(txId); + await governor.executeTransaction(txId).awaitTransactionSuccessAsync(); logUtils.log(`${txId} executed`); } @@ -105,38 +103,38 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t ); logUtils.log('Configuring Exchange...'); - await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync(stakingProxy.address); - await exchange.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(new BigNumber(150000)); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(deployedAddresses.erc20Proxy); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(deployedAddresses.erc721Proxy); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(deployedAddresses.erc1155Proxy); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(deployedAddresses.multiAssetProxy); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(deployedAddresses.staticCallProxy); - await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc20BridgeProxy.address); - await exchange.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await exchange.setProtocolFeeCollectorAddress(stakingProxy.address).awaitTransactionSuccessAsync(); + await exchange.setProtocolFeeMultiplier(new BigNumber(150000)).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(deployedAddresses.erc20Proxy).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(deployedAddresses.erc721Proxy).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(deployedAddresses.erc1155Proxy).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(deployedAddresses.multiAssetProxy).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(deployedAddresses.staticCallProxy).awaitTransactionSuccessAsync(); + await exchange.registerAssetProxy(erc20BridgeProxy.address).awaitTransactionSuccessAsync(); + await exchange.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('Exchange configured!'); logUtils.log('Configuring ERC20BridgeProxy...'); - await erc20BridgeProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address); - await erc20BridgeProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(deployedAddresses.multiAssetProxy); - await erc20BridgeProxy.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await erc20BridgeProxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync(); + await erc20BridgeProxy.addAuthorizedAddress(deployedAddresses.multiAssetProxy).awaitTransactionSuccessAsync(); + await erc20BridgeProxy.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('ERC20BridgeProxy configured!'); logUtils.log('Configuring ZrxVault...'); - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(txDefaults.from); - await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy.address); - await zrxVault.removeAuthorizedAddress.awaitTransactionSuccessAsync(txDefaults.from); - await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address); - await zrxVault.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await zrxVault.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(); + await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync(); + await zrxVault.removeAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(); + await zrxVault.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync(); + await zrxVault.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('ZrxVault configured!'); logUtils.log('Configuring StakingProxy...'); - await stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(txDefaults.from); + await stakingProxy.addAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(); const staking = new StakingContract(stakingProxy.address, provider, txDefaults); - await staking.addExchangeAddress.awaitTransactionSuccessAsync(exchange.address); - await stakingProxy.removeAuthorizedAddress.awaitTransactionSuccessAsync(txDefaults.from); - await stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address); - await stakingProxy.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await staking.addExchangeAddress(exchange.address).awaitTransactionSuccessAsync(); + await stakingProxy.removeAuthorizedAddress(txDefaults.from).awaitTransactionSuccessAsync(); + await stakingProxy.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync(); + await stakingProxy.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('StakingProxy configured!'); logUtils.log('Transfering ownership of 2.0 contracts...'); @@ -144,27 +142,27 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t await submitAndExecuteTransactionAsync( oldAssetProxyOwner, deployedAddresses.exchangeV2, // Exchange 2.1 address - ownableInterface.transferOwnership.getABIEncodedTransactionData(governor.address), + ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(), ); await submitAndExecuteTransactionAsync( oldAssetProxyOwner, deployedAddresses.erc20Proxy, - ownableInterface.transferOwnership.getABIEncodedTransactionData(governor.address), + ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(), ); await submitAndExecuteTransactionAsync( oldAssetProxyOwner, deployedAddresses.erc721Proxy, - ownableInterface.transferOwnership.getABIEncodedTransactionData(governor.address), + ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(), ); await submitAndExecuteTransactionAsync( oldAssetProxyOwner, deployedAddresses.erc1155Proxy, - ownableInterface.transferOwnership.getABIEncodedTransactionData(governor.address), + ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(), ); await submitAndExecuteTransactionAsync( oldAssetProxyOwner, deployedAddresses.multiAssetProxy, - ownableInterface.transferOwnership.getABIEncodedTransactionData(governor.address), + ownableInterface.transferOwnership(governor.address).getABIEncodedTransactionData(), ); logUtils.log('Ownership transferred!'); @@ -172,27 +170,27 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t // AssetProxy configs { destination: deployedAddresses.erc20Proxy, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(exchange.address), + data: authorizableInterface.addAuthorizedAddress(exchange.address).getABIEncodedTransactionData(), }, { destination: deployedAddresses.erc20Proxy, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(zrxVault.address), + data: authorizableInterface.addAuthorizedAddress(zrxVault.address).getABIEncodedTransactionData(), }, { destination: deployedAddresses.erc721Proxy, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(exchange.address), + data: authorizableInterface.addAuthorizedAddress(exchange.address).getABIEncodedTransactionData(), }, { destination: deployedAddresses.erc1155Proxy, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(exchange.address), + data: authorizableInterface.addAuthorizedAddress(exchange.address).getABIEncodedTransactionData(), }, { destination: deployedAddresses.multiAssetProxy, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(exchange.address), + data: authorizableInterface.addAuthorizedAddress(exchange.address).getABIEncodedTransactionData(), }, { destination: deployedAddresses.multiAssetProxy, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(erc20BridgeProxy.address), + data: exchange.registerAssetProxy(erc20BridgeProxy.address).getABIEncodedTransactionData(), }, ]; @@ -221,7 +219,7 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t chainId, ); - const wethAssetData = await devUtils.encodeERC20AssetData.callAsync(deployedAddresses.etherToken); + const wethAssetData = await devUtils.encodeERC20AssetData(deployedAddresses.etherToken).callAsync(); const forwarder = await ForwarderContract.deployFrom0xArtifactAsync( forwarderArtifacts.Forwarder, provider, @@ -230,7 +228,7 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t exchange.address, wethAssetData, ); - await forwarder.approveMakerAssetProxy.awaitTransactionSuccessAsync(deployedAddresses.etherToken); + await forwarder.approveMakerAssetProxy(deployedAddresses.etherToken).awaitTransactionSuccessAsync(); } (async () => { diff --git a/packages/migrations/src/utils/timelocks.ts b/packages/migrations/src/utils/timelocks.ts index dff5c7a5d6..6b09fcf542 100644 --- a/packages/migrations/src/utils/timelocks.ts +++ b/packages/migrations/src/utils/timelocks.ts @@ -34,65 +34,65 @@ export async function getTimelockRegistrationsAsync(provider: SupportedProvider) // AssetProxy timelocks { destination: deployedAddresses.erc20Proxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc20Proxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc721Proxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc721Proxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc1155Proxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc1155Proxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.multiAssetProxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.multiAssetProxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc20BridgeProxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: deployedAddresses.erc20BridgeProxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, }, // ZrxVault timelocks { destination: deployedAddresses.zrxVault, - functionSelector: zrxVault.enterCatastrophicFailure.getSelector(), + functionSelector: zrxVault.getSelector('enterCatastrophicFailure'), secondsTimeLocked: constants.ZERO_AMOUNT, }, // Exchange timelocks { destination: exchange.address, - functionSelector: exchange.detachProtocolFeeCollector.getSelector(), + functionSelector: exchange.getSelector('detachProtocolFeeCollector'), secondsTimeLocked: constants.ZERO_AMOUNT, }, ]; @@ -101,105 +101,105 @@ export async function getTimelockRegistrationsAsync(provider: SupportedProvider) // ZrxVault timelocks { destination: deployedAddresses.zrxVault, - functionSelector: zrxVault.setStakingProxy.getSelector(), + functionSelector: zrxVault.getSelector('setStakingProxy'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.zrxVault, - functionSelector: zrxVault.setZrxProxy.getSelector(), + functionSelector: zrxVault.getSelector('setZrxProxy'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.zrxVault, - functionSelector: ownableInterface.transferOwnership.getSelector(), + functionSelector: ownableInterface.getSelector('transferOwnership'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.zrxVault, - functionSelector: authorizableInterface.addAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('addAuthorizedAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.zrxVault, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.zrxVault, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, // StakingProxy timelocks { destination: deployedAddresses.stakingProxy, - functionSelector: stakingProxy.attachStakingContract.getSelector(), + functionSelector: stakingProxy.getSelector('attachStakingContract'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingProxy.detachStakingContract.getSelector(), + functionSelector: stakingProxy.getSelector('detachStakingContract'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingLogic.setParams.getSelector(), + functionSelector: stakingLogic.getSelector('setParams'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TEN_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingLogic.addExchangeAddress.getSelector(), + functionSelector: stakingLogic.getSelector('addExchangeAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingLogic.removeExchangeAddress.getSelector(), + functionSelector: stakingLogic.getSelector('removeExchangeAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: ownableInterface.transferOwnership.getSelector(), + functionSelector: ownableInterface.getSelector('transferOwnership'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: authorizableInterface.addAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('addAuthorizedAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: deployedAddresses.stakingProxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, // Exchange timelocks { destination: exchange.address, - functionSelector: exchange.setProtocolFeeMultiplier.getSelector(), + functionSelector: exchange.getSelector('setProtocolFeeMultiplier'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TEN_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, { destination: exchange.address, - functionSelector: exchange.setProtocolFeeCollectorAddress.getSelector(), + functionSelector: exchange.getSelector('setProtocolFeeCollectorAddress'), secondsTimeLocked: chainId === constants.MAINNET_CHAIN_ID ? constants.TWENTY_DAYS_IN_SEC : constants.ZERO_AMOUNT, }, diff --git a/packages/monorepo-scripts/src/doc_gen_configs.ts b/packages/monorepo-scripts/src/doc_gen_configs.ts index 02cdc94c95..1238610e11 100644 --- a/packages/monorepo-scripts/src/doc_gen_configs.ts +++ b/packages/monorepo-scripts/src/doc_gen_configs.ts @@ -34,6 +34,7 @@ export const docGenConfigs: DocGenConfigs = { 'Web3WrapperErrors', 'AssetBuyerError', 'ContractError', + 'SubscriptionErrors', 'TypedDataError', 'SwapQuoterError', 'SwapQuoteGetOutputOpts', @@ -45,6 +46,11 @@ export const docGenConfigs: DocGenConfigs = { 'IndexedFilterValues', 'OrderInfo', 'TransactionOpts', + 'ContractEvent', + 'SendTransactionOpts', + 'AwaitTransactionOpts', + 'ContractFunctionObj', + 'ContractTxFunctionObj', 'EventCallback ', ], // Some libraries only export types. In those cases, we cannot check if the exported types are part of the diff --git a/packages/monorepo-scripts/src/utils/doc_generate_utils.ts b/packages/monorepo-scripts/src/utils/doc_generate_utils.ts index 121a2fc8ac..fc040e5739 100644 --- a/packages/monorepo-scripts/src/utils/doc_generate_utils.ts +++ b/packages/monorepo-scripts/src/utils/doc_generate_utils.ts @@ -427,9 +427,9 @@ export class DocGenerateUtils { throw new Error( `GENERATE_DOCS: WARNING - ${ this._packageName - } is exporting one of ${innerExportItems} which is - itself exported from an external package. To fix this, export the external dependency directly, - not indirectly through ${innerExportPath}.`, + } is exporting one of ${innerExportItems} from a package which is itself exporting from another\ + internal package ${innerExportPath}. To fix this, export the dependency directly from ${innerExportPath}\ + instead of the intermediate package.`, ); } else { const absoluteSrcPath = path.join(pathIfExists, 'src', `${innerExportPath}.ts`); diff --git a/packages/order-utils/src/signature_utils.ts b/packages/order-utils/src/signature_utils.ts index 25e92e3457..364f564c39 100644 --- a/packages/order-utils/src/signature_utils.ts +++ b/packages/order-utils/src/signature_utils.ts @@ -125,7 +125,7 @@ export const signatureUtils = { exchangeContract = new ExchangeContract(addresses.exchange, provider); } - const isValid = await exchangeContract.preSigned.callAsync(data, signerAddress); + const isValid = await exchangeContract.preSigned(data, signerAddress).callAsync(); return isValid; }, /** @@ -150,7 +150,7 @@ export const signatureUtils = { const signatureWithoutType = signature.slice(0, -2); const walletContract = new IWalletContract(signerAddress, provider); try { - const magicValue = await walletContract.isValidSignature.callAsync(data, signatureWithoutType); + const magicValue = await walletContract.isValidSignature(data, signatureWithoutType).callAsync(); return magicValue === constants.IS_VALID_WALLET_SIGNATURE_MAGIC_VALUE; } catch (e) { return false; @@ -189,10 +189,9 @@ export const signatureUtils = { } const validatorSignature = signatureUtils.parseValidatorSignature(signature); - const isValidatorApproved = await exchangeContract.allowedValidators.callAsync( - signerAddress, - validatorSignature.validatorAddress, - ); + const isValidatorApproved = await exchangeContract + .allowedValidators(signerAddress, validatorSignature.validatorAddress) + .callAsync(); if (!isValidatorApproved) { throw new Error( `Validator ${validatorSignature.validatorAddress} was not pre-approved by ${signerAddress}.`, @@ -201,11 +200,9 @@ export const signatureUtils = { const validatorContract = new IValidatorContract(validatorSignature.validatorAddress, provider); try { - const magicValue = await validatorContract.isValidSignature.callAsync( - data, - signerAddress, - validatorSignature.signature, - ); + const magicValue = await validatorContract + .isValidSignature(data, signerAddress, validatorSignature.signature) + .callAsync(); return magicValue === constants.IS_VALID_VALIDATOR_SIGNATURE_MAGIC_VALUE; } catch (e) { return false; diff --git a/packages/orderbook/CHANGELOG.json b/packages/orderbook/CHANGELOG.json index a994d473c0..343345e6c0 100644 --- a/packages/orderbook/CHANGELOG.json +++ b/packages/orderbook/CHANGELOG.json @@ -1,4 +1,13 @@ [ + { + "version": "0.1.0-beta.2", + "changes": [ + { + "note": "Update Mesh RPC logic to v6.0.1-beta", + "pr": 2325 + } + ] + }, { "version": "0.1.0-beta.1", "changes": [ diff --git a/packages/orderbook/package.json b/packages/orderbook/package.json index 93ec135b50..0ccdb90d6b 100644 --- a/packages/orderbook/package.json +++ b/packages/orderbook/package.json @@ -38,12 +38,13 @@ "shx": "^0.2.2", "sinon": "^4.0.0", "ts-jest": "^24.0.2", - "typescript": "3.0.1" + "typescript": "3.0.1", + "websocket": "^1.0.26" }, "dependencies": { "@0x/assert": "^2.2.0-beta.1", "@0x/connect": "^5.1.0-beta.1", - "@0x/mesh-rpc-client": "^4.0.1-beta", + "@0x/mesh-rpc-client": "^6.0.1-beta", "@0x/order-utils": "^8.5.0-beta.1", "@0x/utils": "^4.6.0-beta.1" } diff --git a/packages/orderbook/src/order_provider/mesh_order_provider.ts b/packages/orderbook/src/order_provider/mesh_order_provider.ts index 1d6b3e1738..e7890645df 100644 --- a/packages/orderbook/src/order_provider/mesh_order_provider.ts +++ b/packages/orderbook/src/order_provider/mesh_order_provider.ts @@ -2,7 +2,7 @@ import { APIOrder } from '@0x/connect'; import { AcceptedOrderInfo, OrderEvent, - OrderEventKind, + OrderEventEndState, OrderInfo, RejectedOrderInfo, WSClient, @@ -180,20 +180,22 @@ export class MeshOrderProvider extends BaseOrderProvider { addedRemovedByAssetPairKey[assetPairKey] = { added: [], removed: [], assetPairKey }; } const apiOrder = MeshOrderProvider._orderInfoToAPIOrder(event); - switch (event.kind) { - case OrderEventKind.Added: { + switch (event.endState) { + case OrderEventEndState.Added: + case 'UNEXPIRED' as any: { addedRemovedByAssetPairKey[assetPairKey].added.push(apiOrder); break; } - case OrderEventKind.Cancelled: - case OrderEventKind.Expired: - case OrderEventKind.FullyFilled: - case OrderEventKind.Unfunded: { + case OrderEventEndState.Cancelled: + case OrderEventEndState.Expired: + case OrderEventEndState.FullyFilled: + case OrderEventEndState.Unfunded: + case 'STOPPED_WATCHING' as any: { addedRemovedByAssetPairKey[assetPairKey].removed.push(apiOrder); break; } - case OrderEventKind.FillabilityIncreased: - case OrderEventKind.Filled: { + case OrderEventEndState.FillabilityIncreased: + case OrderEventEndState.Filled: { addedRemovedByAssetPairKey[assetPairKey].added.push(apiOrder); break; } diff --git a/packages/orderbook/test/order_provider/mesh_order_provider.test.ts b/packages/orderbook/test/order_provider/mesh_order_provider.test.ts index 0d3e151703..4a492e7519 100644 --- a/packages/orderbook/test/order_provider/mesh_order_provider.test.ts +++ b/packages/orderbook/test/order_provider/mesh_order_provider.test.ts @@ -1,5 +1,4 @@ import { BigNumber, WSClient } from '@0x/mesh-rpc-client'; -import { SERVER_PORT, setupServerAsync, stopServer } from '@0x/mesh-rpc-client/lib/test/utils/mock_ws_server'; import * as sinon from 'sinon'; import { MeshOrderProvider } from '../../src'; @@ -8,6 +7,8 @@ import { OrderStore } from '../../src/order_store'; import { utils } from '../../src/utils'; import { createOrder } from '../utils'; +import { SERVER_PORT, setupServerAsync, stopServer } from './mock_ws_server'; + describe('MeshOrderProvider', () => { let orderStore: OrderStore; let provider: BaseOrderProvider; diff --git a/packages/orderbook/test/order_provider/mock_ws_server.ts b/packages/orderbook/test/order_provider/mock_ws_server.ts new file mode 100644 index 0000000000..54286f46cb --- /dev/null +++ b/packages/orderbook/test/order_provider/mock_ws_server.ts @@ -0,0 +1,50 @@ +import * as http from 'http'; +import * as WebSocket from 'websocket'; + +const DEFAULT_STATUS_CODE = 404; +export const SERVER_PORT = 64321; +// tslint:disable-next-line:custom-no-magic-numbers +const sixtyFourMB = 64 * 1024 * 1024; // 64MiB + +let server: http.Server; +let wsServer: WebSocket.server; + +/** + * Sets up a new test WS server + * @return A WS server + */ +export async function setupServerAsync(): Promise { + return new Promise((resolve, reject) => { + server = http.createServer((_request, response) => { + response.writeHead(DEFAULT_STATUS_CODE); + response.end(); + }); + + wsServer = new WebSocket.server({ + httpServer: server, + autoAcceptConnections: true, + maxReceivedFrameSize: sixtyFourMB, + maxReceivedMessageSize: sixtyFourMB, + fragmentOutgoingMessages: false, + keepalive: false, + disableNagleAlgorithm: false, + }); + + server.listen(SERVER_PORT, () => { + resolve(wsServer); + }); + }); +} + +/** + * Stops the test WS server + */ +export function stopServer(): void { + try { + wsServer.shutDown(); + server.close(); + } catch (e) { + // tslint:disable-next-line:no-console + console.log('stopServer threw', e); + } +} diff --git a/packages/types/CHANGELOG.json b/packages/types/CHANGELOG.json index 9509f0f0e8..162bec3510 100644 --- a/packages/types/CHANGELOG.json +++ b/packages/types/CHANGELOG.json @@ -1,4 +1,13 @@ [ + { + "version": "2.5.0-beta.2", + "changes": [ + { + "note": "Remove `SendTransactionOpts` and `AwaitTransactionSuccessOpts` types and move them to @0x/base-contracts", + "pr": 2325 + } + ] + }, { "version": "2.5.0-beta.1", "changes": [ diff --git a/packages/types/src/index.ts b/packages/types/src/index.ts index 12508b8302..c52de62441 100644 --- a/packages/types/src/index.ts +++ b/packages/types/src/index.ts @@ -854,30 +854,6 @@ export interface IndexedFilterValues { [index: string]: ContractEventArg; } -/* Begin types for @0x/abi-gen-wrappers - * Allow these types to be imported when needed instead of having to import - * the whole package, which is large - */ - -/** - * Used with `sendTransactionAsync` - * * shouldValidate: Flag indicating whether the library should make attempts to validate a transaction before - * broadcasting it. For example, order has a valid signature, maker has sufficient funds, etc. Default=true. - */ -export interface SendTransactionOpts { - shouldValidate?: boolean; -} - -/** - * Used with `awaitTransactionSuccessAsync` - * * pollingIntervalMs: Determine polling intervals in milliseconds - * * timeoutMs: Determines timeout in milliseconds - */ -export interface AwaitTransactionSuccessOpts extends SendTransactionOpts { - pollingIntervalMs?: number; - timeoutMs?: number; -} - export interface SimpleContractArtifact { schemaVersion: string; contractName: string; diff --git a/yarn.lock b/yarn.lock index 6074d71f5e..f73804dba2 100644 --- a/yarn.lock +++ b/yarn.lock @@ -646,7 +646,6 @@ "@0x/abi-gen-wrappers@^5.0.3", "@0x/abi-gen-wrappers@^5.3.2": version "5.3.2" resolved "https://registry.npmjs.org/@0x/abi-gen-wrappers/-/abi-gen-wrappers-5.3.2.tgz#bf7d1942f56916b7d13fae627f6455f309c5c8b5" - integrity sha512-zf5RDhdmPal06exhavdjpHknYxFJ9CJc6Fsc39Ju3hFhRUn57duQozKcFSwnpPHSqUq+gddZnRTfsSRfgpRplQ== dependencies: "@0x/base-contract" "^5.4.0" "@0x/contract-addresses" "^3.2.0" @@ -655,7 +654,6 @@ "@0x/assert@^2.1.0", "@0x/assert@^2.1.1", "@0x/assert@^2.1.2", "@0x/assert@^2.1.6": version "2.1.6" resolved "https://registry.npmjs.org/@0x/assert/-/assert-2.1.6.tgz#61c5854b555bca1f1f0503754f2fd0169bee0ef1" - integrity sha512-Gu8eBnFdEuIAH2GubWYOSVz/BIoRccKof68AziduYDHxh4nSPM6NUH52xtfUGk4nXljiOXU1XHZJhcjTObI+8Q== dependencies: "@0x/json-schemas" "^4.0.2" "@0x/typescript-typings" "^4.3.0" @@ -683,7 +681,6 @@ "@0x/base-contract@^5.4.0": version "5.4.0" resolved "https://registry.npmjs.org/@0x/base-contract/-/base-contract-5.4.0.tgz#466ea98af22d7e629a21a7d16211c825664e2a48" - integrity sha512-YYkv8NwoOFCPqYS4xHAhdhYzM9PrkS03E2L4EaTJmUGOwYkfoRkbzun26Ml1fh4co7NWCfYyBqq9gfeO+wYXrA== dependencies: "@0x/assert" "^2.1.6" "@0x/json-schemas" "^4.0.2" @@ -703,7 +700,6 @@ "@0x/connect@^5.0.13": version "5.0.19" resolved "https://registry.npmjs.org/@0x/connect/-/connect-5.0.19.tgz#569679af661ef84a4c34958388e1be7f1c250a04" - integrity sha512-XdqCxXOZfqr/WwkHseRgG+Wf9/zcfhPsUNhGZ8KUr5agFeXnUjAiS0vfV5gDThPSW/Juu0eaDT6LPapBHp+C3A== dependencies: "@0x/assert" "^2.1.6" "@0x/json-schemas" "^4.0.2" @@ -720,14 +716,12 @@ "@0x/contract-addresses@^3.0.1", "@0x/contract-addresses@^3.0.2", "@0x/contract-addresses@^3.2.0": version "3.2.0" resolved "https://registry.npmjs.org/@0x/contract-addresses/-/contract-addresses-3.2.0.tgz#606307696d9622764220a34e9d4638b899093eec" - integrity sha512-jCVEOgXPa3his4h2qm+O7tn9A2r8UJDgSzDhqhk+za237XxFc2No8TnnMP6qjew3l9ElNM1L+exZHxSd06xB/w== dependencies: lodash "^4.17.11" "@0x/contract-artifacts@^2.0.2", "@0x/contract-artifacts@^2.2.2": version "2.2.2" resolved "https://registry.npmjs.org/@0x/contract-artifacts/-/contract-artifacts-2.2.2.tgz#e6d771afb58d0b59c19c5364af5a42a3dfd17219" - integrity sha512-sbFnSXE6PlmYsbPXpKtEOR3YdVlSn63HhbPgQB3J5jm27wwQtnZ2Lf21I7BdiRBsHwwbf75C/s2pjNqafaRrgQ== "@0x/contract-wrappers@^9.1.6", "@0x/contract-wrappers@^9.1.7": version "9.1.8" @@ -756,7 +750,6 @@ "@0x/contracts-erc20@^2.2.7": version "2.2.14" resolved "https://registry.npmjs.org/@0x/contracts-erc20/-/contracts-erc20-2.2.14.tgz#bac2528a590c0f9668811cfd23948a941ae0ad30" - integrity sha512-zGCg0Yhu/0ZMnjfEZ4ho+VWv/f0sCUQa8xHz36owB3+vnBhzz2o3+vFCctdVVR33SVe2QSgS4A97iJ2M0UsH0g== dependencies: "@0x/base-contract" "^5.4.0" "@0x/contracts-utils" "^3.2.4" @@ -770,7 +763,6 @@ "@0x/contracts-utils@^3.2.4": version "3.2.4" resolved "https://registry.npmjs.org/@0x/contracts-utils/-/contracts-utils-3.2.4.tgz#b5ae80684ac0542eb59925f52113ce2c8b1bdb2b" - integrity sha512-Jk3Ntdt4SUNaHua49ZBty9hMv3gwUJN5US9OLxotbrJSmqdMpZ47FD4MzQ8ORLNcnMRbtyecQabq6pJbezu2jw== dependencies: "@0x/base-contract" "^5.4.0" "@0x/order-utils" "^8.4.0" @@ -812,21 +804,6 @@ typeorm "0.2.7" websocket "^1.0.25" -"@0x/dev-utils@^2.2.6": - version "2.3.3" - resolved "https://registry.npmjs.org/@0x/dev-utils/-/dev-utils-2.3.3.tgz#9b6df00fea357fa6da02b35ca93fc89d100e1992" - integrity sha512-Pi664W/jj1U6WU+kHEPyKpflBnmKRsclB69RaL7wpnvOOFjAPhFV2/0FvIZ25w62rMzKEpfD1/1NcZ7NjAk7OQ== - dependencies: - "@0x/subproviders" "^5.0.4" - "@0x/types" "^2.4.3" - "@0x/typescript-typings" "^4.3.0" - "@0x/utils" "^4.5.2" - "@0x/web3-wrapper" "^6.0.13" - "@types/web3-provider-engine" "^14.0.0" - chai "^4.0.1" - ethereum-types "^2.1.6" - lodash "^4.17.11" - "@0x/json-schemas@^3.0.11", "@0x/json-schemas@^3.1.11": version "3.1.13" resolved "https://registry.yarnpkg.com/@0x/json-schemas/-/json-schemas-3.1.13.tgz#4b9010f1bdeaf2aef1daba1753aa2e5ecf57f654" @@ -839,19 +816,18 @@ "@0x/json-schemas@^4.0.2": version "4.0.2" resolved "https://registry.npmjs.org/@0x/json-schemas/-/json-schemas-4.0.2.tgz#6f7c1dcde04d3acc3e8ca2f24177b9705c10e772" - integrity sha512-JHOwESZeWKAzT5Z42ZNvOvQUQ5vuRIFQWS0FNjYwV8Cv4/dRlLHd7kwxxsvlm9NxgXnOW0ddEDBbVGxhVSYNIg== dependencies: "@0x/typescript-typings" "^4.3.0" "@types/node" "*" jsonschema "^1.2.0" lodash.values "^4.3.0" -"@0x/mesh-rpc-client@^4.0.1-beta": - version "4.0.1-beta" - resolved "https://registry.yarnpkg.com/@0x/mesh-rpc-client/-/mesh-rpc-client-4.0.1-beta.tgz#14db219ea398af5232811e63b7a1e5ca1de19a88" +"@0x/mesh-rpc-client@^6.0.1-beta": + version "6.0.1-beta" + resolved "https://registry.yarnpkg.com/@0x/mesh-rpc-client/-/mesh-rpc-client-6.0.1-beta.tgz#9159cf5f50a43a9c3a9307d7536eeefdc8ec9d31" + integrity sha512-IxZdZk0YpHmSOIKJbh799eeSmZhuSr895dF1E2FTZ5Elit18PNH2godMTAO+DklyglcpoMReXMcaG6qt1fkKbQ== dependencies: "@0x/assert" "^2.1.2" - "@0x/dev-utils" "^2.2.6" "@0x/order-utils" "^8.2.4" "@0x/types" "^2.4.1" "@0x/typescript-typings" "^4.2.4" @@ -863,7 +839,6 @@ "@0x/order-utils@^8.2.1", "@0x/order-utils@^8.2.2", "@0x/order-utils@^8.2.3", "@0x/order-utils@^8.2.4", "@0x/order-utils@^8.4.0": version "8.4.0" resolved "https://registry.npmjs.org/@0x/order-utils/-/order-utils-8.4.0.tgz#f7fe9c73f9fd82ab05ec3c04951049e904aab46a" - integrity sha512-EQh/YpfSKZSbfxetgN6RQmYuc2EpbpWF4f6WUAzm/JjXkCNAK429cMgofVr6Zy4U9ldj89zcODsnK6y6gnNIZQ== dependencies: "@0x/abi-gen-wrappers" "^5.3.2" "@0x/assert" "^2.1.6" @@ -912,34 +887,6 @@ optionalDependencies: "@ledgerhq/hw-transport-node-hid" "^4.3.0" -"@0x/subproviders@^5.0.4": - version "5.0.4" - resolved "https://registry.npmjs.org/@0x/subproviders/-/subproviders-5.0.4.tgz#e4b165634ef6a50c4bd41baacf0dbd2a9390c2f8" - integrity sha512-1LiGcOXkP5eUOl/0JRqkrqYtCvIL4NJj1GbbLIRq4TvkfqrRbF7zJM2SaayxPo3Z48zVsqk0ZE5+RrNAdK/Rrg== - dependencies: - "@0x/assert" "^2.1.6" - "@0x/types" "^2.4.3" - "@0x/typescript-typings" "^4.3.0" - "@0x/utils" "^4.5.2" - "@0x/web3-wrapper" "^6.0.13" - "@ledgerhq/hw-app-eth" "^4.3.0" - "@ledgerhq/hw-transport-u2f" "4.24.0" - "@types/hdkey" "^0.7.0" - "@types/web3-provider-engine" "^14.0.0" - bip39 "^2.5.0" - bn.js "^4.11.8" - ethereum-types "^2.1.6" - ethereumjs-tx "^1.3.5" - ethereumjs-util "^5.1.1" - ganache-core "^2.6.0" - hdkey "^0.7.1" - json-rpc-error "2.0.0" - lodash "^4.17.11" - semaphore-async-await "^1.5.1" - web3-provider-engine "14.0.6" - optionalDependencies: - "@ledgerhq/hw-transport-node-hid" "^4.3.0" - "@0x/ts-doc-gen@^0.0.22": version "0.0.22" resolved "https://registry.yarnpkg.com/@0x/ts-doc-gen/-/ts-doc-gen-0.0.22.tgz#c9c215899695dcd4320a1711291be40050ddbc0e" @@ -956,7 +903,6 @@ "@0x/types@^2.4.0", "@0x/types@^2.4.1", "@0x/types@^2.4.3": version "2.4.3" resolved "https://registry.npmjs.org/@0x/types/-/types-2.4.3.tgz#ea014889789e9013fdf48ce97b79f2c016e10fb3" - integrity sha512-3z4ca9fb9pyTu9lJhTSll5EuEthkA3tLAayyZixCoCnwi4ok6PJ83PnMMsSxlRY2iXr7QGbrQr6nU64YWk2WjA== dependencies: "@types/node" "*" bignumber.js "~8.0.2" @@ -965,7 +911,6 @@ "@0x/typescript-typings@^4.2.2", "@0x/typescript-typings@^4.2.3", "@0x/typescript-typings@^4.2.4", "@0x/typescript-typings@^4.3.0": version "4.3.0" resolved "https://registry.npmjs.org/@0x/typescript-typings/-/typescript-typings-4.3.0.tgz#4813a996ac5101841d1c22f4aa1738ab56168857" - integrity sha512-6IH2JyKyl33+40tJ5rEhaMPTS2mVuRvoNmoXlCd/F0GPYSsDHMGObIXOkx+Qsw5SyCmqNs/3CTLeeCCqiSUdaw== dependencies: "@types/bn.js" "^4.11.0" "@types/react" "*" @@ -976,7 +921,6 @@ "@0x/utils@^4.3.3", "@0x/utils@^4.4.0", "@0x/utils@^4.4.1", "@0x/utils@^4.4.2", "@0x/utils@^4.5.2": version "4.5.2" resolved "https://registry.npmjs.org/@0x/utils/-/utils-4.5.2.tgz#6cc89f2d0dda341e0fb4e76049a35abfb67a4ac5" - integrity sha512-NWfNcvyiOhouk662AWxX0ZVe4ednBZJS9WZT/by3DBCY/WvN7WHMpEy9M5rBCxO+JJndLYeB5eBztDp7W+Ytkw== dependencies: "@0x/types" "^2.4.3" "@0x/typescript-typings" "^4.3.0" @@ -1011,7 +955,6 @@ "@0x/web3-wrapper@^6.0.13", "@0x/web3-wrapper@^6.0.7", "@0x/web3-wrapper@^6.0.8": version "6.0.13" resolved "https://registry.npmjs.org/@0x/web3-wrapper/-/web3-wrapper-6.0.13.tgz#2e666221bd44ceebe02762028214d4aa41ad7247" - integrity sha512-LQjKBCCNdkJuhcJld+/sy+G0+sJu5qp9VDNNwJGLDxWIJpgoshhUpBPi7vUnZ79UY4SYuNcC4yM9yI61cs7ZiA== dependencies: "@0x/assert" "^2.1.6" "@0x/json-schemas" "^4.0.2" @@ -1031,7 +974,6 @@ "@azure/core-asynciterator-polyfill@^1.0.0": version "1.0.0" resolved "https://registry.yarnpkg.com/@azure/core-asynciterator-polyfill/-/core-asynciterator-polyfill-1.0.0.tgz#dcccebb88406e5c76e0e1d52e8cc4c43a68b3ee7" - integrity sha512-kmv8CGrPfN9SwMwrkiBK9VTQYxdFQEGe0BmQk+M8io56P9KNzpAxcWE/1fxJj7uouwN4kXF0BHW8DNlgx+wtCg== "@babel/code-frame@^7.0.0", "@babel/code-frame@^7.0.0-beta.35": version "7.0.0" @@ -1409,7 +1351,6 @@ "@jest/types@^24.9.0": version "24.9.0" resolved "https://registry.yarnpkg.com/@jest/types/-/types-24.9.0.tgz#63cb26cb7500d069e5a389441a7c6ab5e909fc59" - integrity sha512-XKK7ze1apu5JWQ5eZjHITP66AX+QsLlbaJRBGYr8pNzwcAE2JVkwnf0yqjHTsDRcjR0mujy/NmZMXw5kl+kGBw== dependencies: "@types/istanbul-lib-coverage" "^2.0.0" "@types/istanbul-reports" "^1.1.1" @@ -2115,16 +2056,15 @@ dependencies: "@types/node" "*" -"@types/bn.js@^4.11.0": - version "4.11.0" - resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-4.11.0.tgz#401cb20874f0a7b8414e46308a99c449759b7de9" +"@types/bn.js@*", "@types/bn.js@^4.11.4": + version "4.11.5" + resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-4.11.5.tgz#40e36197433f78f807524ec623afcf0169ac81dc" dependencies: "@types/node" "*" -"@types/bn.js@^4.11.4": - version "4.11.5" - resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-4.11.5.tgz#40e36197433f78f807524ec623afcf0169ac81dc" - integrity sha512-AEAZcIZga0JgVMHNtl1CprA/hXX7/wPt79AgR4XqaDt7jyj3QWYw6LPoOiznPtugDmlubUnAahMs2PFxGcQrng== +"@types/bn.js@^4.11.0": + version "4.11.0" + resolved "https://registry.yarnpkg.com/@types/bn.js/-/bn.js-4.11.0.tgz#401cb20874f0a7b8414e46308a99c449759b7de9" dependencies: "@types/node" "*" @@ -2411,7 +2351,6 @@ "@types/yargs-parser@*": version "13.1.0" resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-13.1.0.tgz#c563aa192f39350a1d18da36c5a8da382bbd8228" - integrity sha512-gCubfBUZ6KxzoibJ+SCUc/57Ms1jz5NjHe4+dI2krNmU5zCPAphyLJYyTOg06ueIyfj+SaCUqmzun7ImlxDcKg== "@types/yargs@^11.0.0": version "11.0.0" @@ -2424,7 +2363,6 @@ "@types/yargs@^13.0.0": version "13.0.3" resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-13.0.3.tgz#76482af3981d4412d65371a318f992d33464a380" - integrity sha512-K8/LfZq2duW33XW/tFwEAfnZlqIfVsoyRB3kfXdPXYhl0nfM8mmh7GS0jg7WrX2Dgq/0Ha/pR1PaR+BvmWwjiQ== dependencies: "@types/yargs-parser" "*" @@ -2760,7 +2698,6 @@ ansi-escapes@^3.0.0: ansi-gray@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/ansi-gray/-/ansi-gray-0.1.1.tgz#2962cf54ec9792c48510a3deb524436861ef7251" - integrity sha1-KWLPVOyXksSFEKPetSRDaGHvclE= dependencies: ansi-wrap "0.1.0" @@ -2793,7 +2730,6 @@ ansi-styles@^3.2.0, ansi-styles@^3.2.1: ansi-wrap@0.1.0, ansi-wrap@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/ansi-wrap/-/ansi-wrap-0.1.0.tgz#a82250ddb0015e9a27ca82e82ea603bbfa45efaf" - integrity sha1-qCJQ3bABXponyoLoLqYDu/pF768= ansi@^0.3.0, ansi@~0.3.1: version "0.3.1" @@ -2918,7 +2854,6 @@ array-differ@^2.0.3: array-each@^1.0.0, array-each@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/array-each/-/array-each-1.0.1.tgz#a794af0c05ab1752846ee753a1f211a05ba0c44f" - integrity sha1-p5SvDAWrF1KEbudTofIRoFugxE8= array-equal@^1.0.0: version "1.0.0" @@ -2968,12 +2903,10 @@ array-reduce@~0.0.0: array-slice@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/array-slice/-/array-slice-1.1.0.tgz#e368ea15f89bc7069f7ffb89aec3a6c7d4ac22d4" - integrity sha512-B1qMD3RBP7O8o0H2KbrXDyB0IccejMF15+87Lvlor12ONPRHP6gTjXMNkt/d3ZuOGbAe66hFmaCfECI24Ufp6w== array-sort@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/array-sort/-/array-sort-1.0.0.tgz#e4c05356453f56f53512a7d1d6123f2c54c0a88a" - integrity sha512-ihLeJkonmdiAsD7vpgN3CRcx2J2S0TiYW+IS/5zHBI7mKUq3ySvBdzzBfD236ubDBQFiiyG3SWCPc+msQ9KoYg== dependencies: default-compare "^1.0.0" get-value "^2.0.6" @@ -4056,7 +3989,6 @@ bn.js@4.11.8, bn.js@=4.11.8, bn.js@^4.0.0, bn.js@^4.1.0, bn.js@^4.1.1, bn.js@^4. bn.js@^2.0.3: version "2.2.0" resolved "https://registry.yarnpkg.com/bn.js/-/bn.js-2.2.0.tgz#12162bc2ae71fc40a5626c33438f3a875cd37625" - integrity sha1-EhYrwq5x/EClYmwzQ486h1zTdiU= body-parser@1.18.2, body-parser@^1.16.0: version "1.18.2" @@ -5036,7 +4968,6 @@ color-name@^1.1.1: color-support@^1.1.3: version "1.1.3" resolved "https://registry.yarnpkg.com/color-support/-/color-support-1.1.3.tgz#93834379a1cc9a0c61f82f52f0d04322251bd5a2" - integrity sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg== colors@0.5.x: version "0.5.1" @@ -5876,7 +5807,6 @@ default-require-extensions@^1.0.0: default-resolution@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/default-resolution/-/default-resolution-2.0.0.tgz#bcb82baa72ad79b426a76732f1a81ad6df26d684" - integrity sha1-vLgrqnKtebQmp2cy8aga1t8m1oQ= defaults@^1.0.3: version "1.0.3" @@ -6012,7 +5942,6 @@ destroy@~1.0.4: detect-file@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/detect-file/-/detect-file-1.0.0.tgz#f0d66d03672a825cb1b73bdb3fe62310c8e552b7" - integrity sha1-8NZtA2cqglyxtzvbP+YjEMjlUrc= detect-indent@^4.0.0: version "4.0.0" @@ -6843,7 +6772,6 @@ ethereum-common@^0.0.18: ethereum-types@^2.1.3, ethereum-types@^2.1.4, ethereum-types@^2.1.6: version "2.1.6" resolved "https://registry.npmjs.org/ethereum-types/-/ethereum-types-2.1.6.tgz#57d9d515fad86ab987c0f6962c4203be37da8579" - integrity sha512-xaN5TxLvkdFCGjGfUQ5wV00GHzDHStozP1j+K/YdmUeQXVGiD15cogYPhBVWG3pQJM/aBjtYrpMrjywvKkNC4A== dependencies: "@types/node" "*" bignumber.js "~8.0.2" @@ -7346,7 +7274,6 @@ expand-template@^1.0.2: expand-tilde@^2.0.0, expand-tilde@^2.0.2: version "2.0.2" resolved "https://registry.yarnpkg.com/expand-tilde/-/expand-tilde-2.0.2.tgz#97e801aa052df02454de46b02bf621642cdc8502" - integrity sha1-l+gBqgUt8CRU3kawK/YhZCzchQI= dependencies: homedir-polyfill "^1.0.1" @@ -7530,7 +7457,6 @@ fake-merkle-patricia-tree@^1.0.1: fancy-log@^1.3.2: version "1.3.3" resolved "https://registry.yarnpkg.com/fancy-log/-/fancy-log-1.3.3.tgz#dbc19154f558690150a23953a0adbd035be45fc7" - integrity sha512-k9oEhlyc0FrVh25qYuSELjr8oxsCoc4/LEZfg2iJJrfEk/tZL9bCoJE47gqAvI2m/AUjluCS4+3I0eTx8n3AEw== dependencies: ansi-gray "^0.1.1" color-support "^1.1.3" @@ -7743,7 +7669,6 @@ find-cache-dir@^2.0.0: find-cache-dir@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/find-cache-dir/-/find-cache-dir-3.1.0.tgz#9935894999debef4cf9f677fdf646d002c4cdecb" - integrity sha512-zw+EFiNBNPgI2NTrKkDd1xd7q0cs6wr/iWnr/oUkI0yF9K9GqQ+riIt4aiyFaaqpaWbxPrJXHI+QvmNUQbX+0Q== dependencies: commondir "^1.0.1" make-dir "^3.0.0" @@ -7752,7 +7677,6 @@ find-cache-dir@^3.0.0: find-up@3.0.0, find-up@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/find-up/-/find-up-3.0.0.tgz#49169f1d7993430646da61ecc5ae355c21c97b73" - integrity sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg== dependencies: locate-path "^3.0.0" @@ -7785,7 +7709,6 @@ find@^0.2.4: findup-sync@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-2.0.0.tgz#9326b1488c22d1a6088650a86901b2d9a90a2cbc" - integrity sha1-kyaxSIwi0aYIhlCoaQGy2akKLLw= dependencies: detect-file "^1.0.0" is-glob "^3.1.0" @@ -7795,7 +7718,6 @@ findup-sync@^2.0.0: findup-sync@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/findup-sync/-/findup-sync-3.0.0.tgz#17b108f9ee512dfb7a5c7f3c8b27ea9e1a9c08d1" - integrity sha512-YbffarhcicEhOrm4CtrwdKBdCuz576RLdhJDsIfvNtxUuhdRet1qZcsMjqbePtAseKdAnDyM/IyXbu7PRPRLYg== dependencies: detect-file "^1.0.0" is-glob "^4.0.0" @@ -7805,7 +7727,6 @@ findup-sync@^3.0.0: fined@^1.0.1: version "1.2.0" resolved "https://registry.yarnpkg.com/fined/-/fined-1.2.0.tgz#d00beccf1aa2b475d16d423b0238b713a2c4a37b" - integrity sha512-ZYDqPLGxDkDhDZBjZBb+oD1+j0rA4E0pXY50eplAAOPg2N/gUBSSk5IM1/QhPfyVo19lJ+CvXpqfvk+b2p/8Ng== dependencies: expand-tilde "^2.0.2" is-plain-object "^2.0.3" @@ -7816,7 +7737,6 @@ fined@^1.0.1: flagged-respawn@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/flagged-respawn/-/flagged-respawn-1.0.1.tgz#e7de6f1279ddd9ca9aac8a5971d618606b3aab41" - integrity sha512-lNaHNVymajmk0OJMBn8fVUAU1BtDeKIqKoVhk4xAALB57aALg6b4W0MfJ/cUE0g9YBXy5XhSlPIpYIJ7HaY/3Q== flat-cache@^1.2.1: version "1.3.0" @@ -7878,7 +7798,6 @@ for-own@^0.1.4: for-own@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/for-own/-/for-own-1.0.0.tgz#c63332f415cedc4b04dbfe70cf836494c53cb44b" - integrity sha1-xjMy9BXO3EsE2/5wz4NklMU8tEs= dependencies: for-in "^1.0.1" @@ -8378,7 +8297,6 @@ glob-to-regexp@^0.3.0: glob-watcher@^5.0.3: version "5.0.3" resolved "https://registry.yarnpkg.com/glob-watcher/-/glob-watcher-5.0.3.tgz#88a8abf1c4d131eb93928994bc4a593c2e5dd626" - integrity sha512-8tWsULNEPHKQ2MR4zXuzSmqbdyV5PtwwCaWSGQ1WwHsJ07ilNeN1JB8ntxhckbnpSHaf9dXFUHzIWvm1I13dsg== dependencies: anymatch "^2.0.0" async-done "^1.2.0" @@ -8390,7 +8308,6 @@ glob-watcher@^5.0.3: glob@7.1.2: version "7.1.2" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.2.tgz#c19c9df9a028702d678612384a6552404c636d15" - integrity sha512-MJTUg1kjuLeQCJ+ccE4Vpa6kKVXkPYJ2mOCQyUuKLcLQsdrMCpBPUi8qVE6+YuaJkozeA9NusTAw3hLr8Xe5EQ== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" @@ -8423,7 +8340,6 @@ glob@^5.0.15: glob@^7.0.0, glob@^7.0.3, glob@^7.0.5, glob@^7.0.6, glob@^7.1.1, glob@^7.1.2, glob@~7.1.2: version "7.1.6" resolved "https://registry.yarnpkg.com/glob/-/glob-7.1.6.tgz#141f33b81a7c2492e125594307480c46679278a6" - integrity sha512-LwaxwyZ72Lk7vZINtNNrywX0ZuLyStrdDtabefZKAY5ZGJhVtgdznluResxNmPitE0SAO+O26sWTHeKSI2wMBA== dependencies: fs.realpath "^1.0.0" inflight "^1.0.4" @@ -8456,7 +8372,6 @@ global-modules-path@^2.3.0: global-modules@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/global-modules/-/global-modules-1.0.0.tgz#6d770f0eb523ac78164d72b5e71a8877265cc3ea" - integrity sha512-sKzpEkf11GpOFuw0Zzjzmt4B4UZwjOcG757PPvrfhxcLFbq0wpsgpOqxpxtxFiCG4DtG93M6XRVbF2oGdev7bg== dependencies: global-prefix "^1.0.1" is-windows "^1.0.1" @@ -8465,7 +8380,6 @@ global-modules@^1.0.0: global-prefix@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/global-prefix/-/global-prefix-1.0.2.tgz#dbf743c6c14992593c655568cb66ed32c0122ebe" - integrity sha1-2/dDxsFJklk8ZVVoy2btMsASLr4= dependencies: expand-tilde "^2.0.2" homedir-polyfill "^1.0.1" @@ -8541,7 +8455,6 @@ globby@^9.2.0: glogg@^1.0.0: version "1.0.2" resolved "https://registry.yarnpkg.com/glogg/-/glogg-1.0.2.tgz#2d7dd702beda22eb3bffadf880696da6d846313f" - integrity sha512-5mwUoSuBk44Y4EshyiqcH95ZntbDdTQqA3QYSrxmzj28Ai0vXBGMH1ApSANH14j2sIRtqCEyg6PfsuP7ElOEDA== dependencies: sparkles "^1.0.0" @@ -8630,7 +8543,6 @@ gulp-cli@^2.2.0: gulp@^4.0.2: version "4.0.2" resolved "https://registry.yarnpkg.com/gulp/-/gulp-4.0.2.tgz#543651070fd0f6ab0a0650c6a3e6ff5a7cb09caa" - integrity sha512-dvEs27SCZt2ibF29xYgmnwwCYZxdxhQ/+LFWlbAW8y7jt68L/65402Lz3+CKy0Ov4rOs+NERmDq7YlZaDqUIfA== dependencies: glob-watcher "^5.0.3" gulp-cli "^2.2.0" @@ -8640,7 +8552,6 @@ gulp@^4.0.2: gulplog@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/gulplog/-/gulplog-1.0.0.tgz#e28c4d45d05ecbbed818363ce8f9c5926229ffe5" - integrity sha1-4oxNRdBey77YGDY86PnFkmIp/+U= dependencies: glogg "^1.0.0" @@ -8875,7 +8786,6 @@ home-or-tmp@^2.0.0: homedir-polyfill@^1.0.1: version "1.0.3" resolved "https://registry.yarnpkg.com/homedir-polyfill/-/homedir-polyfill-1.0.3.tgz#743298cef4e5af3e194161fbadcc2151d3a058e8" - integrity sha512-eSmmWE5bZTK2Nou4g0AI3zZ9rswp7GRKoKXS1BLUkvPviOqs4YTN1djQIqrXy9k5gEtdLPy86JjRwsNM9tnDcA== dependencies: parse-passwd "^1.0.0" @@ -11014,7 +10924,6 @@ libnpmaccess@^3.0.0: liftoff@^3.1.0: version "3.1.0" resolved "https://registry.yarnpkg.com/liftoff/-/liftoff-3.1.0.tgz#c9ba6081f908670607ee79062d700df062c52ed3" - integrity sha512-DlIPlJUkCV0Ips2zf2pJP0unEoT1kwYhiiPUGF3s/jtxTCjziNLoiVVh+jqWOWeFi6mmwQ5fNxvAUyPad4Dfog== dependencies: extend "^3.0.0" findup-sync "^3.0.0" @@ -11486,7 +11395,6 @@ make-fetch-happen@^5.0.0: make-iterator@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/make-iterator/-/make-iterator-1.0.1.tgz#29b33f312aa8f547c4a5e490f56afcec99133ad6" - integrity sha512-pxiuXh0iVEq7VM7KMIhs5gxsfxCux2URptUQaXo4iZZJxBAzTPOLE2BumO5dbfVYq/hBJFBR/a1mFDmOx5AGmw== dependencies: kind-of "^6.0.2" @@ -12055,7 +11963,6 @@ multimatch@^3.0.0: mute-stdout@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/mute-stdout/-/mute-stdout-1.0.1.tgz#acb0300eb4de23a7ddeec014e3e96044b3472331" - integrity sha512-kDcwXR4PS7caBpuRYYBUz9iVixUk3anO3f5OYFiIPwK/20vCzKCHyKoulbiDY1S53zD2bxUpxN/IJ+TnXjfvxg== mute-stream@0.0.7, mute-stream@~0.0.4: version "0.0.7" @@ -12701,7 +12608,6 @@ object.assign@4.1.0, object.assign@^4.0.4, object.assign@^4.1.0: object.defaults@^1.0.0, object.defaults@^1.1.0: version "1.1.0" resolved "https://registry.yarnpkg.com/object.defaults/-/object.defaults-1.1.0.tgz#3a7f868334b407dea06da16d88d5cd29e435fecf" - integrity sha1-On+GgzS0B96gbaFtiNXNKeQ1/s8= dependencies: array-each "^1.0.1" array-slice "^1.0.0" @@ -12727,7 +12633,6 @@ object.getownpropertydescriptors@^2.0.3: object.map@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/object.map/-/object.map-1.0.1.tgz#cf83e59dc8fcc0ad5f4250e1f78b3b81bd801d37" - integrity sha1-z4Plncj8wK1fQlDh94s7gb2AHTc= dependencies: for-own "^1.0.0" make-iterator "^1.0.0" @@ -13146,7 +13051,6 @@ parse-code-context@^1.0.0: parse-filepath@^1.0.1: version "1.0.2" resolved "https://registry.yarnpkg.com/parse-filepath/-/parse-filepath-1.0.2.tgz#a632127f53aaf3d15876f5872f3ffac763d6c891" - integrity sha1-pjISf1Oq89FYdvWHLz/6x2PWyJE= dependencies: is-absolute "^1.0.0" map-cache "^0.2.0" @@ -13188,12 +13092,10 @@ parse-json@^4.0.0: parse-node-version@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/parse-node-version/-/parse-node-version-1.0.1.tgz#e2b5dbede00e7fa9bc363607f53327e8b073189b" - integrity sha512-3YHlOa/JgH6Mnpr05jP9eDG254US9ek25LyIxZlDItp2iJtwyaXQb57lBYLdT3MowkUFYEV2XXNAYIPlESvJlA== parse-passwd@^1.0.0: version "1.0.0" resolved "https://registry.yarnpkg.com/parse-passwd/-/parse-passwd-1.0.0.tgz#6d5b934a456993b23d37f40a382d6f1666a8e5c6" - integrity sha1-bVuTSkVpk7I9N/QKOC1vFmao5cY= parse-path@^4.0.0: version "4.0.1" @@ -13287,12 +13189,10 @@ path-parse@^1.0.6: path-root-regex@^0.1.0: version "0.1.2" resolved "https://registry.yarnpkg.com/path-root-regex/-/path-root-regex-0.1.2.tgz#bfccdc8df5b12dc52c8b43ec38d18d72c04ba96d" - integrity sha1-v8zcjfWxLcUsi0PsONGNcsBLqW0= path-root@^0.1.1: version "0.1.1" resolved "https://registry.yarnpkg.com/path-root/-/path-root-0.1.1.tgz#9a4a6814cac1c0cd73360a95f32083c8ea4745b7" - integrity sha1-mkpoFMrBwM1zNgqV8yCDyOpHRbc= dependencies: path-root-regex "^0.1.0" @@ -13536,7 +13436,6 @@ pretty-format@^23.6.0: pretty-format@^24.8.0: version "24.9.0" resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-24.9.0.tgz#12fac31b37019a4eea3c11aa9a959eb7628aa7c9" - integrity sha512-00ZMZUiHaJrNfk33guavqgvfJS30sLYf0f8+Srklv0AMPodGGHcoHgksZ3OThYnIvOd+8yMCn0YiEOogjlgsnA== dependencies: "@jest/types" "^24.9.0" ansi-regex "^4.0.0" @@ -13546,7 +13445,6 @@ pretty-format@^24.8.0: pretty-hrtime@^1.0.0: version "1.0.3" resolved "https://registry.yarnpkg.com/pretty-hrtime/-/pretty-hrtime-1.0.3.tgz#b7e3ea42435a4c9b2759d99e0f201eb195802ee1" - integrity sha1-t+PqQkNaTJsnWdmeDyAesZWALuE= prettyjson@^1.1.2: version "1.2.1" @@ -14535,7 +14433,6 @@ resolve-cwd@^2.0.0: resolve-dir@^1.0.0, resolve-dir@^1.0.1: version "1.0.1" resolved "https://registry.yarnpkg.com/resolve-dir/-/resolve-dir-1.0.1.tgz#79a40644c362be82f26effe739c9bb5382046f43" - integrity sha1-eaQGRMNivoLybv/nOcm7U4IEb0M= dependencies: expand-tilde "^2.0.0" global-modules "^1.0.0" @@ -14569,7 +14466,6 @@ resolve@1.1.7, resolve@1.1.x: resolve@1.x, resolve@^1.1.7: version "1.12.0" resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.12.0.tgz#3fc644a35c84a48554609ff26ec52b66fa577df6" - integrity sha512-B/dOmuoAik5bKcD6s6nXDCjzUKnaDvdkRyAk6rsmsKLipWj4797iothd7jmmUhWTfinVMU+wc56rYKsit2Qy4w== dependencies: path-parse "^1.0.6" @@ -15460,7 +15356,6 @@ source-map@~0.2.0: sparkles@^1.0.0: version "1.0.1" resolved "https://registry.yarnpkg.com/sparkles/-/sparkles-1.0.1.tgz#008db65edce6c50eec0c5e228e1945061dd0437c" - integrity sha512-dSO0DDYUahUt/0/pD/Is3VIm5TGJjludZ0HVymmhYF6eNA53PVLhnUk0znSYbH8IYBuJdCE+1luR22jNLMaQdw== spawn-wrap@^1.4.2: version "1.4.2" @@ -16229,7 +16124,6 @@ thunky@^1.0.2: time-stamp@^1.0.0: version "1.1.0" resolved "https://registry.yarnpkg.com/time-stamp/-/time-stamp-1.1.0.tgz#764a5a11af50561921b133f3b44e618687e0f5c3" - integrity sha1-dkpaEa9QVhkhsTPztE5hhofg9cM= timed-out@^4.0.0, timed-out@^4.0.1: version "4.0.1" @@ -17021,7 +16915,6 @@ v8-compile-cache@^2.0.2: v8flags@^3.0.1: version "3.1.3" resolved "https://registry.yarnpkg.com/v8flags/-/v8flags-3.1.3.tgz#fc9dc23521ca20c5433f81cc4eb9b3033bb105d8" - integrity sha512-amh9CCg3ZxkzQ48Mhcb8iX7xpAfYJgePHxWMQCBWECpOSqJUXgY26ncA61UTV0BkPqfhcy6mzwCIoP4ygxpW8w== dependencies: homedir-polyfill "^1.0.1"