diff --git a/contracts/asset-proxy/test/authorizable.ts b/contracts/asset-proxy/test/authorizable.ts index 4a7794734c..31401d281b 100644 --- a/contracts/asset-proxy/test/authorizable.ts +++ b/contracts/asset-proxy/test/authorizable.ts @@ -47,21 +47,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, ); }); @@ -69,23 +69,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, @@ -95,10 +95,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, @@ -106,10 +106,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, @@ -119,7 +119,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, @@ -129,11 +129,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, @@ -141,26 +141,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 82c410a184..015b2bd44f 100644 --- a/contracts/asset-proxy/test/erc1155_proxy.ts +++ b/contracts/asset-proxy/test/erc1155_proxy.ts @@ -74,8 +74,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(); @@ -119,7 +119,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); }); @@ -634,12 +634,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 @@ -694,14 +696,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, }); } @@ -739,7 +743,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( @@ -794,14 +798,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, }); } @@ -847,12 +853,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); @@ -919,14 +927,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, }); } @@ -969,12 +979,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); @@ -1032,12 +1044,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 @@ -1079,12 +1093,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 @@ -1130,12 +1146,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 @@ -1181,12 +1199,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 @@ -1232,12 +1252,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 @@ -1284,12 +1306,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 @@ -1331,12 +1355,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 @@ -1382,12 +1408,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 @@ -1429,12 +1457,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 @@ -1480,12 +1510,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, @@ -1511,12 +1543,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, @@ -1640,7 +1674,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 358b0038b2..ef25b78a50 100644 --- a/contracts/asset-proxy/test/erc20bridge_proxy.ts +++ b/contracts/asset-proxy/test/erc20bridge_proxy.ts @@ -44,8 +44,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 { @@ -102,7 +102,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()', () => { @@ -132,13 +132,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; } @@ -180,12 +176,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(); }); @@ -281,18 +274,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 2cf0173239..4af06f95a8 100644 --- a/contracts/asset-proxy/test/eth2dai_bridge.ts +++ b/contracts/asset-proxy/test/eth2dai_bridge.ts @@ -8,7 +8,7 @@ import { hexRandom, Numberish, randomAddress, - TransactionHelper, + transactionHelper, } from '@0x/contracts-test-utils'; import { AssetProxyId } from '@0x/types'; import { BigNumber, RawRevertError } from '@0x/utils'; @@ -25,7 +25,6 @@ import { } from '../src'; blockchainTests.resets('Eth2DaiBridge unit tests', env => { - const txHelper = new TransactionHelper(env.web3Wrapper, artifacts); let testContract: TestEth2DaiBridgeContract; before(async () => { @@ -40,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); }); }); @@ -80,31 +79,32 @@ 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( + [_opts.fromTokenAddress] = await transactionHelper.getResultAndReceiptAsync( testContract.createToken, new BigNumber(_opts.fromTokenBalance), ); } if (_opts.toTokenAddress === undefined) { - [_opts.toTokenAddress] = await txHelper.getResultAndReceiptAsync( + [_opts.toTokenAddress] = await transactionHelper.getResultAndReceiptAsync( testContract.createToken, constants.ZERO_AMOUNT, ); } // 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( + const [result, { logs }] = await transactionHelper.getResultAndReceiptAsync( testContract.bridgeTransferFrom, // "to" token address _opts.toTokenAddress, diff --git a/contracts/asset-proxy/test/proxies.ts b/contracts/asset-proxy/test/proxies.ts index 232b085086..9de496ec3e 100644 --- a/contracts/asset-proxy/test/proxies.ts +++ b/contracts/asset-proxy/test/proxies.ts @@ -107,24 +107,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; @@ -154,26 +154,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(); @@ -225,23 +219,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, @@ -262,17 +253,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, @@ -282,8 +270,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)); }); @@ -291,18 +279,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, @@ -323,16 +308,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, @@ -353,17 +335,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(); @@ -382,21 +361,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({ @@ -406,23 +382,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({ @@ -438,18 +411,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({ @@ -459,8 +429,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); }); @@ -480,28 +450,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, @@ -511,28 +477,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, @@ -542,27 +504,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({ @@ -575,27 +533,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, @@ -604,27 +558,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, @@ -633,35 +583,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, @@ -670,27 +616,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, @@ -699,7 +641,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); }); }); @@ -717,7 +659,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); @@ -726,16 +668,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({ @@ -757,16 +696,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( @@ -788,17 +726,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({ @@ -821,17 +756,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({ @@ -860,20 +792,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({ @@ -883,34 +811,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({ @@ -921,34 +844,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({ @@ -959,8 +877,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); }); @@ -980,23 +898,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({ @@ -1036,23 +953,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({ @@ -1100,23 +1016,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({ @@ -1157,29 +1072,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({ @@ -1204,35 +1120,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, @@ -1262,7 +1176,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 = [ @@ -1278,23 +1192,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({ @@ -1312,33 +1222,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({ @@ -1356,24 +1261,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({ @@ -1403,28 +1305,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, @@ -1434,20 +1332,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( @@ -1459,10 +1354,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); @@ -1486,22 +1381,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, @@ -1514,23 +1405,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, @@ -1543,20 +1430,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, @@ -1569,16 +1452,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, @@ -1591,18 +1471,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, @@ -1615,21 +1492,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, @@ -1642,21 +1515,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'; @@ -1675,21 +1544,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); @@ -1709,23 +1574,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({ @@ -1746,12 +1607,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 743cc476a3..f366b61c02 100644 --- a/contracts/asset-proxy/test/static_call_proxy.ts +++ b/contracts/asset-proxy/test/static_call_proxy.ts @@ -79,26 +79,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); @@ -116,25 +111,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); @@ -145,94 +136,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', @@ -245,12 +230,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 2f7f6a0290..ae07d17abe 100644 --- a/contracts/asset-proxy/test/uniswap_bridge.ts +++ b/contracts/asset-proxy/test/uniswap_bridge.ts @@ -9,7 +9,7 @@ import { hexRandom, Numberish, randomAddress, - TransactionHelper, + transactionHelper, } from '@0x/contracts-test-utils'; import { AssetProxyId } from '@0x/types'; import { BigNumber } from '@0x/utils'; @@ -30,7 +30,6 @@ import { } from '../src'; blockchainTests.resets('UniswapBridge unit tests', env => { - const txHelper = new TransactionHelper(env.web3Wrapper, artifacts); let testContract: TestUniswapBridgeContract; let wethTokenAddress: string; @@ -41,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,33 +89,31 @@ blockchainTests.resets('UniswapBridge unit tests', env => { async function withdrawToAsync(opts?: Partial): Promise { const _opts = createWithdrawToOpts(opts); // Create the "from" token and exchange. - [[_opts.fromTokenAddress]] = await txHelper.getResultAndReceiptAsync( + [[_opts.fromTokenAddress]] = await transactionHelper.getResultAndReceiptAsync( testContract.createTokenAndExchange, _opts.fromTokenAddress, _opts.exchangeRevertReason, { value: new BigNumber(_opts.exchangeFillAmount) }, ); // Create the "to" token and exchange. - [[_opts.toTokenAddress]] = await txHelper.getResultAndReceiptAsync( + [[_opts.toTokenAddress]] = await transactionHelper.getResultAndReceiptAsync( 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, - ); + 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( + const [result, receipt] = await transactionHelper.getResultAndReceiptAsync( testContract.bridgeTransferFrom, // The "to" token address. _opts.toTokenAddress, @@ -138,7 +135,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 () => { @@ -147,7 +144,7 @@ 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( + const [[tokenAddress]] = await transactionHelper.getResultAndReceiptAsync( testContract.createTokenAndExchange, constants.NULL_ADDRESS, '', @@ -203,13 +200,15 @@ 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()), - ); + const tx = testContract + .bridgeTransferFrom( + randomAddress(), + randomAddress(), + randomAddress(), + getRandomInteger(1, 1e18), + hexLeftPad(randomAddress()), + ) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); @@ -275,13 +274,15 @@ 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), - ); + const tx = testContract + .bridgeTransferFrom( + randomAddress(), + randomAddress(), + randomAddress(), + getRandomInteger(1, 1e18), + hexLeftPad(wethTokenAddress), + ) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); @@ -333,13 +334,15 @@ 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()), - ); + const tx = testContract + .bridgeTransferFrom( + wethTokenAddress, + randomAddress(), + randomAddress(), + getRandomInteger(1, 1e18), + hexLeftPad(randomAddress()), + ) + .awaitTransactionSuccessAsync(); return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN'); }); diff --git a/contracts/asset-proxy/test/utils/erc1155_proxy_wrapper.ts b/contracts/asset-proxy/test/utils/erc1155_proxy_wrapper.ts index 5bc707af41..6dbe18bb46 100644 --- a/contracts/asset-proxy/test/utils/erc1155_proxy_wrapper.ts +++ b/contracts/asset-proxy/test/utils/erc1155_proxy_wrapper.ts @@ -74,7 +74,7 @@ export class ERC1155ProxyWrapper { txDefaults, artifacts, ); - this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync(); + this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync(); return this._proxyContract; } /** @@ -111,19 +111,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; } /** @@ -171,19 +165,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, @@ -364,7 +352,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/test/utils/erc20_wrapper.ts b/contracts/asset-proxy/test/utils/erc20_wrapper.ts index 52e8d43142..57a9a2afe3 100644 --- a/contracts/asset-proxy/test/utils/erc20_wrapper.ts +++ b/contracts/asset-proxy/test/utils/erc20_wrapper.ts @@ -56,7 +56,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 { @@ -68,43 +68,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(); @@ -113,7 +109,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, @@ -147,7 +143,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/test/utils/erc721_wrapper.ts b/contracts/asset-proxy/test/utils/erc721_wrapper.ts index e2ae988930..ec50c15847 100644 --- a/contracts/asset-proxy/test/utils/erc721_wrapper.ts +++ b/contracts/asset-proxy/test/utils/erc721_wrapper.ts @@ -44,7 +44,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 { @@ -78,7 +78,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; } @@ -93,14 +93,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, @@ -109,28 +109,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; } @@ -138,13 +138,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; @@ -161,7 +161,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/coordinator/test/coordinator_registry.ts b/contracts/coordinator/test/coordinator_registry.ts index 743132fa7e..8a2c8906f0 100644 --- a/contracts/coordinator/test/coordinator_registry.ts +++ b/contracts/coordinator/test/coordinator_registry.ts @@ -23,43 +23,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 ef6eb0b2a7..1ae2630d13 100644 --- a/contracts/coordinator/test/libs.ts +++ b/contracts/coordinator/test/libs.ts @@ -42,7 +42,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 4ee471b797..de86012ea2 100644 --- a/contracts/coordinator/test/mixins.ts +++ b/contracts/coordinator/test/mixins.ts @@ -70,14 +70,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 () => { @@ -88,7 +88,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, @@ -101,7 +101,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, @@ -117,7 +117,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, @@ -133,7 +133,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, @@ -148,7 +148,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, @@ -162,7 +162,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, @@ -176,7 +176,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, @@ -190,7 +190,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, @@ -204,14 +204,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); }); @@ -222,7 +222,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); }); }); @@ -233,13 +233,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 = { @@ -250,54 +248,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]; @@ -309,13 +295,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( @@ -328,13 +312,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)); }); } @@ -350,13 +332,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 => ({ @@ -366,13 +346,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 => ({ @@ -381,26 +359,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 }]; @@ -408,25 +380,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 }]; @@ -434,26 +401,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( @@ -470,13 +431,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( @@ -494,13 +453,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( @@ -517,13 +475,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( @@ -536,13 +492,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)); }); } @@ -552,36 +506,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/test/erc1155_token.ts b/contracts/erc1155/test/erc1155_token.ts index ef3b2def3e..88f2048a78 100644 --- a/contracts/erc1155/test/erc1155_token.ts +++ b/contracts/erc1155/test/erc1155_token.ts @@ -179,14 +179,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 () => { @@ -196,19 +191,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, ); }); @@ -355,14 +345,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 () => { @@ -372,19 +357,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, ); }); @@ -432,14 +412,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, ); }); @@ -485,14 +460,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/erc1155/test/utils/erc1155_wrapper.ts b/contracts/erc1155/test/utils/erc1155_wrapper.ts index 984935db17..f9b49131c2 100644 --- a/contracts/erc1155/test/utils/erc1155_wrapper.ts +++ b/contracts/erc1155/test/utils/erc1155_wrapper.ts @@ -25,7 +25,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( @@ -39,7 +39,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, }), ); @@ -56,14 +56,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; } @@ -74,7 +69,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, }), ); @@ -95,25 +90,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[] = []; @@ -132,14 +124,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( @@ -161,18 +153,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/erc20/test/lib_erc20_token.ts b/contracts/erc20/test/lib_erc20_token.ts index b843867a8c..3df3d2b363 100644 --- a/contracts/erc20/test/lib_erc20_token.ts +++ b/contracts/erc20/test/lib_erc20_token.ts @@ -37,13 +37,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); }); @@ -51,37 +47,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); }); @@ -89,13 +73,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); }); @@ -103,13 +83,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); }); @@ -117,13 +93,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); }); @@ -131,26 +103,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'); }); }); @@ -159,13 +123,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); }); @@ -173,37 +133,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); }); @@ -211,13 +159,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); }); @@ -225,13 +169,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); }); @@ -239,13 +179,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); }); @@ -253,26 +189,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'); }); }); @@ -282,14 +210,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); }); @@ -298,42 +221,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); }); @@ -342,14 +250,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); }); @@ -358,14 +261,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); }); @@ -374,14 +272,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); }); @@ -390,14 +283,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); }); @@ -405,14 +293,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 9d9de2ab01..e0dbaa2433 100644 --- a/contracts/erc20/test/unlimited_allowance_token.ts +++ b/contracts/erc20/test/unlimited_allowance_token.ts @@ -44,7 +44,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, ); }); @@ -56,24 +56,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; @@ -82,7 +82,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(); @@ -91,14 +91,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, @@ -106,15 +106,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, @@ -123,72 +123,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 602abd29f9..f0862bbf66 100644 --- a/contracts/erc20/test/weth9.ts +++ b/contracts/erc20/test/weth9.ts @@ -54,16 +54,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, @@ -71,7 +71,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)); @@ -80,25 +80,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( @@ -108,7 +108,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)), @@ -120,7 +120,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); @@ -138,7 +138,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 a148fc0d85..b0ee2d7d47 100644 --- a/contracts/erc20/test/zrx_token.ts +++ b/contracts/erc20/test/zrx_token.ts @@ -42,25 +42,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); }); @@ -68,8 +68,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); }); }); @@ -77,14 +77,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; @@ -93,7 +93,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(); @@ -102,30 +102,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(); @@ -133,75 +133,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 b3c0ba4141..560d9a0b90 100644 --- a/contracts/erc721/test/erc721_token.ts +++ b/contracts/erc721/test/erc721_token.ts @@ -60,7 +60,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, ); }); @@ -77,7 +77,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, ); }); @@ -85,7 +85,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, ); }); @@ -93,7 +93,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, ); }); @@ -101,7 +101,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, ); }); @@ -109,9 +109,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); @@ -121,16 +121,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); @@ -139,19 +139,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); @@ -164,9 +164,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); @@ -185,7 +185,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 () => { @@ -198,7 +198,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, ); }); @@ -206,9 +206,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; @@ -227,9 +227,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); @@ -248,7 +248,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 () => { @@ -261,7 +261,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, ); }); @@ -269,9 +269,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 e608726e47..652a2e8766 100644 --- a/contracts/exchange-libs/test/lib_eip712_exchange_domain.ts +++ b/contracts/exchange-libs/test/lib_eip712_exchange_domain.ts @@ -23,7 +23,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 () => { @@ -44,7 +44,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 c62ee15803..b92ade1c60 100644 --- a/contracts/exchange-libs/test/lib_fill_results.ts +++ b/contracts/exchange-libs/test/lib_fill_results.ts @@ -106,12 +106,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( @@ -145,12 +147,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); }); @@ -167,12 +171,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); }); @@ -195,12 +201,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); }); @@ -218,12 +226,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); }); @@ -235,12 +245,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); }); @@ -256,12 +268,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); }); @@ -283,12 +297,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); }); @@ -310,12 +326,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); }); @@ -333,12 +351,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); }); @@ -360,12 +375,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); }); }); @@ -393,7 +410,7 @@ blockchainTests('LibFillResults', env => { it('matches the output of the reference function', async () => { const [a, b] = DEFAULT_FILL_RESULTS; const expected = ReferenceFunctions.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); }); @@ -405,7 +422,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 () => { @@ -416,7 +433,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 () => { @@ -427,7 +444,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 () => { @@ -438,7 +455,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 () => { @@ -449,7 +466,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); }); }); }); @@ -513,16 +530,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); } @@ -1184,16 +1202,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 5e9b89023e..409517bae9 100644 --- a/contracts/exchange-libs/test/lib_math.ts +++ b/contracts/exchange-libs/test/lib_math.ts @@ -33,8 +33,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; }; } @@ -54,7 +53,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = ReferenceFunctions.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); }); @@ -63,7 +62,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); }); @@ -77,7 +76,7 @@ blockchainTests('LibMath', env => { denominator, ); return expect( - libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -91,7 +90,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -113,7 +112,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = ReferenceFunctions.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); }); @@ -122,7 +121,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); }); @@ -137,7 +136,7 @@ blockchainTests('LibMath', env => { new BigNumber(1), ); return expect( - libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); @@ -151,7 +150,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -173,7 +172,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = ReferenceFunctions.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); }); @@ -182,7 +181,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); }); @@ -192,7 +191,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); }); @@ -202,7 +201,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); }); @@ -216,7 +215,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -238,7 +237,7 @@ blockchainTests('LibMath', env => { const denominator = ONE_ETHER.dividedToIntegerBy(2); const target = ONE_ETHER.times(0.01); const expected = ReferenceFunctions.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); }); @@ -247,7 +246,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); }); @@ -257,7 +256,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); }); @@ -267,7 +266,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); }); @@ -281,7 +280,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target), + libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -303,7 +302,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); }); @@ -312,7 +311,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); }); @@ -323,7 +322,7 @@ blockchainTests('LibMath', env => { // tslint:disable-next-line: boolean-naming const expected = ReferenceFunctions.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); }); @@ -333,7 +332,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); }); @@ -347,7 +346,7 @@ blockchainTests('LibMath', env => { target, ); return expect( - libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target), + libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(), ).to.revertWith(expectedError); }); }); @@ -369,7 +368,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); }); @@ -378,7 +377,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); }); @@ -389,7 +388,7 @@ blockchainTests('LibMath', env => { // tslint:disable-next-line: boolean-naming const expected = ReferenceFunctions.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); }); @@ -398,9 +397,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 () => { @@ -412,9 +411,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 ec87e6b4cd..1ad0f015db 100644 --- a/contracts/exchange-libs/test/lib_order.ts +++ b/contracts/exchange-libs/test/lib_order.ts @@ -56,7 +56,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); } @@ -106,8 +106,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); }); }); @@ -118,7 +118,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 00d3446606..e650e17a31 100644 --- a/contracts/exchange-libs/test/lib_zero_ex_transaction.ts +++ b/contracts/exchange-libs/test/lib_zero_ex_transaction.ts @@ -48,7 +48,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); } @@ -92,14 +92,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); }); }); @@ -110,7 +108,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/wrapper_interfaces.ts b/contracts/exchange/src/wrapper_interfaces.ts index 2c8fe219b1..23942b10b5 100644 --- a/contracts/exchange/src/wrapper_interfaces.ts +++ b/contracts/exchange/src/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, PromiseWithTransactionHash } 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/exchange/test/assertion_wrappers/fill_order_wrapper.ts b/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts index 0c6e552f3b..cb2878dbed 100644 --- a/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts +++ b/contracts/exchange/test/assertion_wrappers/fill_order_wrapper.ts @@ -157,9 +157,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 @@ -190,18 +190,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]; } @@ -216,7 +210,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/balance_stores/blockchain_balance_store.ts b/contracts/exchange/test/balance_stores/blockchain_balance_store.ts index 73d4fff643..4cebeea2f9 100644 --- a/contracts/exchange/test/balance_stores/blockchain_balance_store.ts +++ b/contracts/exchange/test/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/test/balance_stores/local_balance_store.ts b/contracts/exchange/test/balance_stores/local_balance_store.ts index 458777a871..8fb612f219 100644 --- a/contracts/exchange/test/balance_stores/local_balance_store.ts +++ b/contracts/exchange/test/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/test/core.ts b/contracts/exchange/test/core.ts index 55da2bd13b..ff281a5ecd 100644 --- a/contracts/exchange/test/core.ts +++ b/contracts/exchange/test/core.ts @@ -157,22 +157,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); @@ -216,10 +216,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, }; @@ -257,24 +257,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, @@ -286,19 +281,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, }); @@ -317,19 +308,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, }); @@ -348,19 +335,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, }); @@ -425,9 +408,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, @@ -437,33 +422,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); @@ -471,19 +456,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), }); @@ -491,7 +473,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), }); @@ -499,7 +481,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), }); @@ -676,14 +658,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; @@ -703,14 +685,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; @@ -730,14 +712,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; @@ -757,14 +739,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; @@ -783,8 +765,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); @@ -802,12 +784,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, @@ -822,18 +804,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, @@ -848,12 +830,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, @@ -870,12 +852,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, @@ -901,18 +883,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, @@ -936,18 +922,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, @@ -970,18 +960,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, @@ -1010,18 +1004,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, @@ -1055,18 +1053,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, @@ -1091,12 +1093,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( @@ -1108,28 +1108,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( @@ -1141,18 +1139,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 067f3e2fac..a7794ad8ba 100644 --- a/contracts/exchange/test/dispatcher.ts +++ b/contracts/exchange/test/dispatcher.ts @@ -82,10 +82,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, }); }); @@ -97,34 +97,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( @@ -134,7 +134,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); @@ -142,7 +142,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); @@ -150,7 +150,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); @@ -159,7 +159,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, }), ); @@ -172,15 +172,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); }); }); @@ -189,23 +189,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( @@ -218,23 +213,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); @@ -242,7 +232,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); @@ -251,70 +241,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( @@ -322,25 +300,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'; @@ -350,59 +323,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/internal.ts b/contracts/exchange/test/internal.ts index 9713714774..8507b35937 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/match_orders.ts b/contracts/exchange/test/match_orders.ts index e05aad4316..4065704366 100644 --- a/contracts/exchange/test/match_orders.ts +++ b/contracts/exchange/test/match_orders.ts @@ -143,28 +143,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, }); @@ -179,10 +179,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, @@ -190,10 +190,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, @@ -346,8 +346,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, @@ -400,8 +400,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, @@ -451,8 +451,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, @@ -500,8 +500,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, @@ -545,8 +545,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, @@ -1170,7 +1170,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({ @@ -1267,7 +1267,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), }); @@ -1294,7 +1294,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), }); @@ -1448,8 +1448,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, @@ -1536,8 +1536,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, @@ -1587,8 +1587,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, @@ -1633,8 +1633,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, @@ -1678,8 +1678,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, @@ -1797,8 +1797,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, @@ -2251,7 +2251,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({ @@ -2348,7 +2348,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), }); @@ -2375,7 +2375,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), }); @@ -2684,29 +2684,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}`); } @@ -2752,49 +2752,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 5cba8686ff..3a46d392d7 100644 --- a/contracts/exchange/test/protocol_fees.ts +++ b/contracts/exchange/test/protocol_fees.ts @@ -31,244 +31,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 010fe122c6..54bc8273b0 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 593c8285f2..7a56dbc9bc 100644 --- a/contracts/exchange/test/reentrancy_tests.ts +++ b/contracts/exchange/test/reentrancy_tests.ts @@ -101,8 +101,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(); }); } @@ -112,8 +112,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 33aec898fb..cecdb5386b 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 00e932dbe6..dceff61f57 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 257bbf798d..1a537d7a26 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, transactionHelper } from '@0x/contracts-test-utils'; import { ExchangeRevertErrors, transactionHashUtils } from '@0x/order-utils'; import { EIP712DomainWithDefaultSchema, ZeroExTransaction } from '@0x/types'; import { BigNumber, StringRevertError } from '@0x/utils'; @@ -29,8 +29,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(); @@ -54,11 +52,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 { @@ -109,10 +105,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); }); @@ -132,10 +127,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); }); @@ -155,10 +149,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); }); @@ -176,13 +169,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); }); @@ -203,7 +194,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ); 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. @@ -241,10 +232,10 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef ); 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>; @@ -269,17 +260,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, @@ -293,11 +285,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 () => { @@ -306,34 +296,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({ @@ -344,10 +332,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 () => { @@ -359,13 +346,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 () => { @@ -383,13 +368,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 () => { @@ -407,13 +390,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 () => { @@ -425,7 +406,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(''); @@ -439,7 +420,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(''); @@ -450,17 +431,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 () => { @@ -472,13 +452,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 () => { @@ -493,13 +471,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 () => { @@ -515,13 +491,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 () => { @@ -540,7 +514,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef { from: accounts[0] }, ); - expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result)).to.equal( + expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result)).to.equal( DEADBEEF_RETURN_DATA, ); @@ -571,7 +545,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef { from: accounts[0] }, ); - expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result)).to.equal( + expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result)).to.equal( DEADBEEF_RETURN_DATA, ); @@ -599,7 +573,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 () => { @@ -612,7 +586,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); @@ -627,30 +601,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 () => { @@ -663,7 +637,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); @@ -671,7 +645,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(''); @@ -679,7 +653,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(''); @@ -687,7 +661,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(''); @@ -697,30 +671,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]); @@ -728,10 +699,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_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_data_encoder.ts b/contracts/exchange/test/utils/exchange_data_encoder.ts index 5b7e383d08..87d7e227c2 100644 --- a/contracts/exchange/test/utils/exchange_data_encoder.ts +++ b/contracts/exchange/test/utils/exchange_data_encoder.ts @@ -9,44 +9,38 @@ export const exchangeDataEncoder = { const exchangeInstance = new IExchangeContract(constants.NULL_ADDRESS, provider); let data; if (exchangeConstants.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 (exchangeConstants.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 (exchangeConstants.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 (exchangeConstants.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/utils/exchange_wrapper.ts b/contracts/exchange/test/utils/exchange_wrapper.ts index dead507440..51672aa602 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 006088efea..3f6c9dbd8b 100644 --- a/contracts/exchange/test/utils/fill_order_combinatorial_utils.ts +++ b/contracts/exchange/test/utils/fill_order_combinatorial_utils.ts @@ -125,37 +125,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 0d6f948068..e1ea62b01e 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'; @@ -40,7 +34,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 = {}; @@ -70,19 +63,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( @@ -91,13 +83,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 { @@ -109,7 +102,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 { @@ -121,23 +114,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/wrapper_unit_tests.ts b/contracts/exchange/test/wrapper_unit_tests.ts index 13ae715025..69ebd113c7 100644 --- a/contracts/exchange/test/wrapper_unit_tests.ts +++ b/contracts/exchange/test/wrapper_unit_tests.ts @@ -1,1329 +1,1327 @@ -import { ReferenceFunctions as LibReferenceFunctions } from '@0x/contracts-exchange-libs'; -import { - blockchainTests, - constants, - describe, - expect, - hexRandom, - MutatorContractFunction, - TransactionHelper, -} 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'; -import { AnyRevertError, BigNumber, SafeMathRevertErrors, StringRevertError } from '@0x/utils'; -import { LogEntry, LogWithDecodedArgs } from 'ethereum-types'; -import * as ethjs from 'ethereumjs-util'; -import * as _ from 'lodash'; - -import { - artifacts, - TestWrapperFunctionsCancelOrderCalledEventArgs as CancelOrderCalledEventArgs, - TestWrapperFunctionsContract, - TestWrapperFunctionsFillOrderCalledEventArgs as FillOrderCalledEventArgs, -} from '../src'; - -blockchainTests('Exchange wrapper functions unit tests.', env => { - const CHAIN_ID = 0x74657374; - const { ONE_ETHER, MAX_UINT256 } = constants; - const { addFillResults, getPartialAmountFloor } = LibReferenceFunctions; - const { safeSub } = UtilReferenceFunctions; - const protocolFeeMultiplier = new BigNumber(150000); - const randomAddress = () => hexRandom(constants.ADDRESS_LENGTH); - const randomAssetData = () => hexRandom(34); - const randomAmount = (maxAmount: BigNumber = ONE_ETHER) => maxAmount.times(_.random(0, 100, true).toFixed(12)); - const randomTimestamp = () => new BigNumber(Math.floor(_.now() / 1000) + _.random(0, 34560)); - const randomSalt = () => new BigNumber(hexRandom(constants.WORD_LENGTH).substr(2), 16); - const ALWAYS_FAILING_SALT = constants.MAX_UINT256; - const ALWAYS_FAILING_SALT_REVERT_ERROR = new StringRevertError('ALWAYS_FAILING_SALT'); - const EMPTY_FILL_RESULTS = { - makerAssetFilledAmount: constants.ZERO_AMOUNT, - takerAssetFilledAmount: constants.ZERO_AMOUNT, - makerFeePaid: constants.ZERO_AMOUNT, - takerFeePaid: constants.ZERO_AMOUNT, - 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, - { - ...env.txDefaults, - from: owner, - }, - {}, - ); - - // Set the protocol fee multiplier. - await testContract.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(protocolFeeMultiplier, { - from: owner, - }); - }); - - function randomOrder(fields?: Partial): Order { - return { - makerAddress: randomAddress(), - takerAddress: randomAddress(), - feeRecipientAddress: randomAddress(), - senderAddress: randomAddress(), - takerAssetAmount: randomAmount(), - makerAssetAmount: randomAmount(), - makerFee: randomAmount(), - takerFee: randomAmount(), - expirationTimeSeconds: randomTimestamp(), - salt: randomSalt(), - makerAssetData: randomAssetData(), - takerAssetData: randomAssetData(), - makerFeeAssetData: randomAssetData(), - takerFeeAssetData: randomAssetData(), - exchangeAddress: constants.NULL_ADDRESS, - chainId: CHAIN_ID, - ...(fields || {}), - }; - } - - // Computes the expected (fake) fill results from `TestWrapperFunctions` `_fillOrder` implementation. - function getExpectedFillResults(order: Order, signature: string): FillResults { - if (order.salt === ALWAYS_FAILING_SALT) { - return EMPTY_FILL_RESULTS; - } - return { - makerAssetFilledAmount: order.makerAssetAmount, - takerAssetFilledAmount: order.takerAssetAmount, - makerFeePaid: order.makerFee, - takerFeePaid: order.takerFee, - protocolFeePaid: protocolFeeMultiplier, - }; - } - - // Creates a deterministic order signature, even though no signature validation - // actually occurs in the test contract. - function createOrderSignature(order: Order): string { - return ethjs.bufferToHex(ethjs.sha3(ethjs.toBuffer(orderHashUtils.getOrderHashHex(order)))); - } - - // Asserts that `_fillOrder()` was called in the same order and with the same - // arguments as given by examining receipt logs. - function assertFillOrderCallsFromLogs(logs: LogEntry[], calls: Array<[Order, BigNumber, string]>): void { - expect(logs.length).to.eq(calls.length); - for (const i of _.times(calls.length)) { - const log = (logs[i] as any) as LogWithDecodedArgs; - const [expectedOrder, expectedTakerAssetFillAmount, expectedSignature] = calls[i]; - expect(log.event).to.eq('FillOrderCalled'); - assertSameOrderFromEvent(log.args.order as any, expectedOrder); - expect(log.args.takerAssetFillAmount).to.bignumber.eq(expectedTakerAssetFillAmount); - expect(log.args.signature).to.eq(expectedSignature); - } - } - - function assertSameOrderFromEvent(actual: any[], expected: Order): void { - expect(actual.length === 14); - expect(actual[0].toLowerCase()).to.be.eq(expected.makerAddress); - expect(actual[1].toLowerCase()).to.be.eq(expected.takerAddress); - expect(actual[2].toLowerCase()).to.be.eq(expected.feeRecipientAddress); - expect(actual[3].toLowerCase()).to.be.eq(expected.senderAddress); - expect(actual[4]).to.be.bignumber.eq(expected.makerAssetAmount); - expect(actual[5]).to.be.bignumber.eq(expected.takerAssetAmount); - expect(actual[6]).to.be.bignumber.eq(expected.makerFee); - expect(actual[7]).to.be.bignumber.eq(expected.takerFee); - expect(actual[8]).to.be.bignumber.eq(expected.expirationTimeSeconds); - expect(actual[9]).to.be.bignumber.eq(expected.salt); - expect(actual[10]).to.be.eq(expected.makerAssetData); - expect(actual[11]).to.be.eq(expected.takerAssetData); - expect(actual[12]).to.be.eq(expected.makerFeeAssetData); - expect(actual[13]).to.be.eq(expected.takerFeeAssetData); - } - - describe('fillOrKillOrder', () => { - it('works if the order is filled by exactly `takerAssetFillAmount`', async () => { - const fillAmount = randomAmount(); - const order = randomOrder({ - // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as - // the `takerAssetFilledAmount`. - takerAssetAmount: fillAmount, - }); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('reverts if the order is filled by less than `takerAssetFillAmount`', async () => { - const fillAmount = randomAmount(); - const order = randomOrder({ - // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as - // the `takerAssetFilledAmount`. - takerAssetAmount: fillAmount.minus(1), - }); - const signature = createOrderSignature(order); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, - fillAmount, - fillAmount.minus(1), - ); - const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if the order is filled by greater than `takerAssetFillAmount`', async () => { - const fillAmount = randomAmount(); - const order = randomOrder({ - // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as - // the `takerAssetFilledAmount`. - takerAssetAmount: fillAmount.plus(1), - }); - const signature = createOrderSignature(order); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, - fillAmount, - fillAmount.plus(1), - ); - const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if `_fillOrder()` reverts', async () => { - const fillAmount = randomAmount(); - const order = randomOrder({ - salt: ALWAYS_FAILING_SALT, - }); - const signature = createOrderSignature(order); - const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR; - const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature); - return expect(tx).to.revertWith(expectedError); - }); - }); - - describe('fillOrderNoThrow', () => { - it('calls `fillOrder()` and returns its result', async () => { - const fillAmount = randomAmount(); - const order = randomOrder(); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('does not revert if `fillOrder()` reverts', async () => { - const fillAmount = randomAmount(); - const order = randomOrder({ - salt: ALWAYS_FAILING_SALT, - }); - const signature = createOrderSignature(order); - const expectedResult = EMPTY_FILL_RESULTS; - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.fillOrderNoThrow, - order, - fillAmount, - signature, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, []); - }); - }); - - describe('batchFillOrders', () => { - it('works with no fills', async () => { - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrders, - [], - [], - [], - ); - expect(actualResult).to.deep.eq([]); - assertFillOrderCallsFromLogs(receipt.logs, []); - }); - - it('works with one fill', async () => { - const COUNT = 1; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works with many fills', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works with duplicate orders', async () => { - const NUM_UNIQUE_ORDERS = 2; - const COUNT = 4; - const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); - const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount.dividedToIntegerBy(COUNT)); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('reverts if there are more orders than fill amounts', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - 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); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if there are more orders than signatures', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - 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); - return expect(tx).to.revertWith(expectedError); - }); - }); - - describe('batchFillOrKillOrders', () => { - it('works with no fills', async () => { - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - [], - [], - [], - ); - expect(actualResult).to.deep.eq([]); - assertFillOrderCallsFromLogs(receipt.logs, []); - }); - - it('works with one fill', async () => { - const COUNT = 1; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works with many fills', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works with duplicate orders', async () => { - const NUM_UNIQUE_ORDERS = 2; - const COUNT = 4; - const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); - const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('reverts if any fill sells less than its takerAssetFillAmount', async () => { - const COUNT = 8; - const FAILING_ORDER_INDEX = 6; - const orders = _.times(COUNT, () => randomOrder()); - const failingOrder = orders[FAILING_ORDER_INDEX]; - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - const failingAmount = fillAmounts[FAILING_ORDER_INDEX]; - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as - // the `takerAssetFilledAmount`. - failingOrder.takerAssetAmount = failingOrder.takerAssetAmount.minus(1); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, - failingAmount, - failingAmount.minus(1), - ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if any fill sells more than its takerAssetFillAmount', async () => { - const COUNT = 8; - const FAILING_ORDER_INDEX = 6; - const orders = _.times(COUNT, () => randomOrder()); - const failingOrder = orders[FAILING_ORDER_INDEX]; - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - const failingAmount = fillAmounts[FAILING_ORDER_INDEX]; - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as - // the `takerAssetFilledAmount`. - failingOrder.takerAssetAmount = failingOrder.takerAssetAmount.plus(1); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, - failingAmount, - failingAmount.plus(1), - ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.batchFillOrKillOrders, - orders, - fillAmounts, - signatures, - ); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if there are more orders than fill amounts', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - 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, - ); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if there are more orders than signatures', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - 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, - ); - return expect(tx).to.revertWith(expectedError); - }); - }); - - describe('batchFillOrdersNoThrow', () => { - it('works with no fills', async () => { - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.batchFillOrdersNoThrow, - [], - [], - [], - ); - expect(actualResult).to.deep.eq([]); - assertFillOrderCallsFromLogs(receipt.logs, []); - }); - - it('works with one fill', async () => { - const COUNT = 1; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works with many fills', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works with duplicate orders', async () => { - const NUM_UNIQUE_ORDERS = 2; - const COUNT = 4; - const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); - const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount.dividedToIntegerBy(COUNT)); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('works if a fill fails', async () => { - const COUNT = 8; - const FAILING_ORDER_INDEX = 6; - const orders = _.times(COUNT, () => randomOrder()); - const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const failingOrder = orders[FAILING_ORDER_INDEX]; - failingOrder.salt = ALWAYS_FAILING_SALT; - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); - }); - - it('reverts if there are more orders than fill amounts', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - 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, - ); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts if there are more orders than signatures', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - 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, - ); - return expect(tx).to.revertWith(expectedError); - }); - }); - - type ExpectedFillOrderCallArgs = [Order, BigNumber, string]; - type MarketSellBuyArgs = [Order[], BigNumber, string[], ...any[]]; - type MarketSellBuyContractFunction = MutatorContractFunction; - type MarketSellBuySimulator = (...args: MarketSellBuyArgs) => [FillResults, ExpectedFillOrderCallArgs[]]; - - describe('marketSell*', () => { - function defineCommonMarketSellOrdersTests( - getContractFn: () => MarketSellBuyContractFunction, - simulator: MarketSellBuySimulator, - ): void { - it('works with one order', async () => { - const COUNT = 1; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); - expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('works with many orders', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); - expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('works with duplicate orders', async () => { - const NUM_UNIQUE_ORDERS = 2; - const COUNT = 4; - const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); - const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); - expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - takerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('stops when filled == `takerAssetFillAmount`', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - // Skip the last order in our `takerAssetFillAmount` calculation. - const takerAssetFillAmount = _.reduce( - orders.slice(0, COUNT - 1), - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('stops when filled > `takerAssetFillAmount`', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - // Because `TestWrapperFunctions` always fills `takerAssetAmount` - // setting the first order's `takerAssetAmount` to larger than - // `takerAssetFillAmount` will cause an overfill. - orders[0].takerAssetAmount = takerAssetFillAmount.plus(1); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('reverts when an overflow occurs when summing fill results', async () => { - const COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - orders[1].takerAssetAmount = MAX_UINT256; - const takerAssetFillAmount = MAX_UINT256; - const expectedError = new SafeMathRevertErrors.Uint256BinOpError( - SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow, - orders[0].takerAssetAmount, - orders[1].takerAssetAmount, - ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, takerAssetFillAmount, signatures); - 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, - [], - ); - - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - } - - function simulateMarketSellOrders( - orders: Order[], - takerAssetFillAmount: BigNumber, - signatures: string[], - ): [FillResults, ExpectedFillOrderCallArgs[]] { - const fillOrderCalls = []; - let fillResults = _.cloneDeep(EMPTY_FILL_RESULTS); - for (const [order, signature] of _.zip(orders, signatures) as [[Order, string]]) { - const remainingTakerAssetFillAmount = safeSub(takerAssetFillAmount, fillResults.takerAssetFilledAmount); - if (order.salt !== ALWAYS_FAILING_SALT) { - fillOrderCalls.push([order, remainingTakerAssetFillAmount, signature]); - } - fillResults = addFillResults(fillResults, getExpectedFillResults(order, signature)); - if (fillResults.takerAssetFilledAmount.gte(takerAssetFillAmount)) { - break; - } - } - return [fillResults, fillOrderCalls as any]; - } - - describe('marketSellOrdersNoThrow', () => { - defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders); - - it('works when any fills revert', async () => { - const COUNT = 4; - const BAD_ORDERS_COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); - for (const order of badOrders) { - order.salt = ALWAYS_FAILING_SALT; - } - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulateMarketSellOrders( - orders, - takerAssetFillAmount, - signatures, - ); - expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersNoThrow, - orders, - takerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('works when all fills revert', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder({ salt: ALWAYS_FAILING_SALT })); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulateMarketSellOrders( - orders, - takerAssetFillAmount, - signatures, - ); - expect(expectedCalls.length).to.eq(0); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersNoThrow, - orders, - takerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - }); - - describe('marketSellOrdersFillOrKill', () => { - defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders); - - it('reverts when filled < `takerAssetFillAmount`', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ).plus(1); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketSellOrders, - takerAssetFillAmount, - takerAssetFillAmount.minus(1), - ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersFillOrKill, - orders, - takerAssetFillAmount, - signatures, - ); - return expect(tx).to.revertWith(expectedError); - }); - - it('works when fills fail but can still sell `takerAssetFillAmount`', async () => { - const COUNT = 4; - const BAD_ORDERS_COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); - for (const order of badOrders) { - order.salt = ALWAYS_FAILING_SALT; - } - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ).minus(_.reduce(badOrders, (total, o) => o.takerAssetAmount.plus(total), constants.ZERO_AMOUNT)); - const [expectedResult, expectedCalls] = simulateMarketSellOrders( - orders, - takerAssetFillAmount, - signatures, - ); - expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersFillOrKill, - orders, - takerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('reverts when a failed fill results in selling less than `takerAssetFillAmount`', async () => { - const COUNT = 4; - const BAD_ORDERS_COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); - for (const order of badOrders) { - order.salt = ALWAYS_FAILING_SALT; - } - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const badOrdersAmount = _.reduce( - badOrders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const takerAssetFillAmount = _.reduce( - orders, - (total, o) => o.takerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ) - .minus(badOrdersAmount) - .plus(1); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketSellOrders, - takerAssetFillAmount, - takerAssetFillAmount.minus(1), - ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketSellOrdersFillOrKill, - orders, - takerAssetFillAmount, - signatures, - ); - return expect(tx).to.revertWith(expectedError); - }); - }); - }); - - describe('marketBuy*', () => { - function defineCommonMarketBuyOrdersTests( - getContractFn: () => MarketSellBuyContractFunction, - simulator: MarketSellBuySimulator, - ): void { - it('works with one order', async () => { - const COUNT = 1; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); - expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('works with many orders', async () => { - const COUNT = 8; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); - expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('works with duplicate orders', async () => { - const NUM_UNIQUE_ORDERS = 2; - const COUNT = 4; - const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); - const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); - expect(expectedCalls.length).to.eq(COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - getContractFn(), - orders, - makerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('stops when filled == `makerAssetFillAmount`', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - // Skip the last order in our `makerAssetFillAmount` calculation. - const makerAssetFillAmount = _.reduce( - orders.slice(0, COUNT - 1), - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('stops when filled > `makerAssetFillAmount`', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - // Because `TestWrapperFunctions` always fills `makerAssetAmount` - // setting the first order's `makerAssetAmount` to larger than - // `makerAssetFillAmount` will cause an overfill. - orders[0].makerAssetAmount = makerAssetFillAmount.plus(1); - 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, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('reverts when an overflow occurs when computing `remainingTakerAssetFillAmount`', async () => { - const orders = [randomOrder({ takerAssetAmount: MAX_UINT256 })]; - const signatures = _.times(orders.length, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = new BigNumber(2); - const expectedError = new SafeMathRevertErrors.Uint256BinOpError( - SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow, - orders[0].takerAssetAmount, - makerAssetFillAmount, - ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); - return expect(tx).to.revertWith(expectedError); - }); - - it("reverts when an order's `makerAssetAmount` is zero", async () => { - const orders = [randomOrder({ makerAssetAmount: constants.ZERO_AMOUNT })]; - const signatures = _.times(orders.length, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = ONE_ETHER; - const expectedError = new SafeMathRevertErrors.Uint256BinOpError( - SafeMathRevertErrors.BinOpErrorCodes.DivisionByZero, - orders[0].takerAssetAmount.times(makerAssetFillAmount), - orders[0].makerAssetAmount, - ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); - return expect(tx).to.revertWith(expectedError); - }); - - it('reverts when an overflow occurs when summing fill results', async () => { - const orders = [ - randomOrder({ - takerAssetAmount: new BigNumber(1), - makerAssetAmount: new BigNumber(1), - }), - randomOrder({ - takerAssetAmount: new BigNumber(1), - makerAssetAmount: MAX_UINT256, - }), - ]; - const signatures = _.times(orders.length, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = new BigNumber(2); - const expectedError = new SafeMathRevertErrors.Uint256BinOpError( - SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow, - orders[0].makerAssetAmount, - orders[1].makerAssetAmount, - ); - const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); - 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, - [], - ); - - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - } - - function simulateMarketBuyOrdersNoThrow( - orders: Order[], - makerAssetFillAmount: BigNumber, - signatures: string[], - ): [FillResults, ExpectedFillOrderCallArgs[]] { - const fillOrderCalls = []; - let fillResults = _.cloneDeep(EMPTY_FILL_RESULTS); - for (const [order, signature] of _.zip(orders, signatures) as [[Order, string]]) { - const remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, fillResults.makerAssetFilledAmount); - const remainingTakerAssetFillAmount = getPartialAmountFloor( - order.takerAssetAmount, - order.makerAssetAmount, - remainingMakerAssetFillAmount, - ); - if (order.salt !== ALWAYS_FAILING_SALT) { - fillOrderCalls.push([order, remainingTakerAssetFillAmount, signature]); - } - fillResults = addFillResults(fillResults, getExpectedFillResults(order, signature)); - if (fillResults.makerAssetFilledAmount.gte(makerAssetFillAmount)) { - break; - } - } - return [fillResults, fillOrderCalls as any]; - } - - describe('marketBuyOrdersNoThrow', () => { - defineCommonMarketBuyOrdersTests(() => testContract.marketBuyOrdersNoThrow, simulateMarketBuyOrdersNoThrow); - - it('works when any fills revert', async () => { - const COUNT = 4; - const BAD_ORDERS_COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); - for (const order of badOrders) { - order.salt = ALWAYS_FAILING_SALT; - } - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulateMarketBuyOrdersNoThrow( - orders, - makerAssetFillAmount, - signatures, - ); - expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersNoThrow, - orders, - makerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('works when all fills revert', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder({ salt: ALWAYS_FAILING_SALT })); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const [expectedResult, expectedCalls] = simulateMarketBuyOrdersNoThrow( - orders, - makerAssetFillAmount, - signatures, - ); - expect(expectedCalls.length).to.eq(0); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersNoThrow, - orders, - makerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - }); - - describe('marketBuyOrdersFillOrKill', () => { - defineCommonMarketBuyOrdersTests( - () => testContract.marketBuyOrdersFillOrKill, - simulateMarketBuyOrdersNoThrow, - ); - - it('reverts when filled < `makerAssetFillAmount`', async () => { - const COUNT = 4; - const orders = _.times(COUNT, () => randomOrder()); - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ).plus(1); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketBuyOrders, - makerAssetFillAmount, - makerAssetFillAmount.minus(1), - ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersFillOrKill, - orders, - makerAssetFillAmount, - signatures, - ); - return expect(tx).to.revertWith(expectedError); - }); - - it('works when fills fail but can still buy `makerAssetFillAmount`', async () => { - const COUNT = 4; - const BAD_ORDERS_COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); - for (const order of badOrders) { - order.salt = ALWAYS_FAILING_SALT; - } - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ).minus(_.reduce(badOrders, (total, o) => o.makerAssetAmount.plus(total), constants.ZERO_AMOUNT)); - const [expectedResult, expectedCalls] = simulateMarketBuyOrdersNoThrow( - orders, - makerAssetFillAmount, - signatures, - ); - expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); - const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersFillOrKill, - orders, - makerAssetFillAmount, - signatures, - ); - expect(actualResult).to.deep.eq(expectedResult); - assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); - }); - - it('reverts when a failed fill results in buying less than `makerAssetFillAmount`', async () => { - const COUNT = 4; - const BAD_ORDERS_COUNT = 2; - const orders = _.times(COUNT, () => randomOrder()); - const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); - for (const order of badOrders) { - order.salt = ALWAYS_FAILING_SALT; - } - const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); - const badOrdersAmount = _.reduce( - badOrders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ); - const makerAssetFillAmount = _.reduce( - orders, - (total, o) => o.makerAssetAmount.plus(total), - constants.ZERO_AMOUNT, - ) - .minus(badOrdersAmount) - .plus(1); - const expectedError = new ExchangeRevertErrors.IncompleteFillError( - ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketBuyOrders, - makerAssetFillAmount, - makerAssetFillAmount.minus(1), - ); - const tx = txHelper.getResultAndReceiptAsync( - testContract.marketBuyOrdersFillOrKill, - orders, - makerAssetFillAmount, - signatures, - ); - return expect(tx).to.revertWith(expectedError); - }); - }); - }); - - describe('batchCancelOrders', () => { - // Asserts that `_cancelOrder()` was called in the same order and with the same - // arguments as given by examining receipt logs. - function assertCancelOrderCallsFromLogs(logs: LogEntry[], calls: Order[]): void { - expect(logs.length).to.eq(calls.length); - for (const i of _.times(calls.length)) { - const log = (logs[i] as any) as LogWithDecodedArgs; - const expectedOrder = calls[i]; - expect(log.event).to.eq('CancelOrderCalled'); - assertSameOrderFromEvent(log.args.order as any, expectedOrder); - } - } - - it('works with no orders', async () => { - const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, []); - assertCancelOrderCallsFromLogs(receipt.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); - }); - - it('works with duplicate orders', async () => { - const UNIQUE_ORDERS = 2; - 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); - }); - - it('reverts if one `_cancelOrder()` reverts', async () => { - const COUNT = 8; - const FAILING_ORDER_INDEX = 4; - const orders = _.times(COUNT, () => randomOrder({ makerAddress: senderAddress })); - 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); - return expect(tx).to.revertWith(expectedError); - }); - }); -}); -// tslint:disable-next-line: max-file-line-count +// import { ReferenceFunctions as LibReferenceFunctions } from '@0x/contracts-exchange-libs'; +// import { +// blockchainTests, +// constants, +// describe, +// expect, +// hexRandom, +// MutatorContractFunction, +// transactionHelper, +// } 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'; +// import { AnyRevertError, BigNumber, SafeMathRevertErrors, StringRevertError } from '@0x/utils'; +// import { LogEntry, LogWithDecodedArgs } from 'ethereum-types'; +// import * as ethjs from 'ethereumjs-util'; +// import * as _ from 'lodash'; + +// import { +// artifacts, +// TestWrapperFunctionsCancelOrderCalledEventArgs as CancelOrderCalledEventArgs, +// TestWrapperFunctionsContract, +// TestWrapperFunctionsFillOrderCalledEventArgs as FillOrderCalledEventArgs, +// } from '../src'; + +// blockchainTests('Exchange wrapper functions unit tests.', env => { +// const CHAIN_ID = 0x74657374; +// const { ONE_ETHER, MAX_UINT256 } = constants; +// const { addFillResults, getPartialAmountFloor } = LibReferenceFunctions; +// const { safeSub } = UtilReferenceFunctions; +// const protocolFeeMultiplier = new BigNumber(150000); +// const randomAddress = () => hexRandom(constants.ADDRESS_LENGTH); +// const randomAssetData = () => hexRandom(34); +// const randomAmount = (maxAmount: BigNumber = ONE_ETHER) => maxAmount.times(_.random(0, 100, true).toFixed(12)); +// const randomTimestamp = () => new BigNumber(Math.floor(_.now() / 1000) + _.random(0, 34560)); +// const randomSalt = () => new BigNumber(hexRandom(constants.WORD_LENGTH).substr(2), 16); +// const ALWAYS_FAILING_SALT = constants.MAX_UINT256; +// const ALWAYS_FAILING_SALT_REVERT_ERROR = new StringRevertError('ALWAYS_FAILING_SALT'); +// const EMPTY_FILL_RESULTS = { +// makerAssetFilledAmount: constants.ZERO_AMOUNT, +// takerAssetFilledAmount: constants.ZERO_AMOUNT, +// makerFeePaid: constants.ZERO_AMOUNT, +// takerFeePaid: constants.ZERO_AMOUNT, +// protocolFeePaid: constants.ZERO_AMOUNT, +// }; +// let testContract: TestWrapperFunctionsContract; +// let owner: string; +// let senderAddress: string; + +// before(async () => { +// [owner, senderAddress] = await env.getAccountAddressesAsync(); +// testContract = await TestWrapperFunctionsContract.deployFrom0xArtifactAsync( +// artifacts.TestWrapperFunctions, +// env.provider, +// { +// ...env.txDefaults, +// from: owner, +// }, +// {}, +// ); + +// // Set the protocol fee multiplier. +// await testContract.setProtocolFeeMultiplier(protocolFeeMultiplier).awaitTransactionSuccessAsync({ +// from: owner, +// }); +// }); + +// function randomOrder(fields?: Partial): Order { +// return { +// makerAddress: randomAddress(), +// takerAddress: randomAddress(), +// feeRecipientAddress: randomAddress(), +// senderAddress: randomAddress(), +// takerAssetAmount: randomAmount(), +// makerAssetAmount: randomAmount(), +// makerFee: randomAmount(), +// takerFee: randomAmount(), +// expirationTimeSeconds: randomTimestamp(), +// salt: randomSalt(), +// makerAssetData: randomAssetData(), +// takerAssetData: randomAssetData(), +// makerFeeAssetData: randomAssetData(), +// takerFeeAssetData: randomAssetData(), +// exchangeAddress: constants.NULL_ADDRESS, +// chainId: CHAIN_ID, +// ...(fields || {}), +// }; +// } + +// // Computes the expected (fake) fill results from `TestWrapperFunctions` `_fillOrder` implementation. +// function getExpectedFillResults(order: Order, signature: string): FillResults { +// if (order.salt === ALWAYS_FAILING_SALT) { +// return EMPTY_FILL_RESULTS; +// } +// return { +// makerAssetFilledAmount: order.makerAssetAmount, +// takerAssetFilledAmount: order.takerAssetAmount, +// makerFeePaid: order.makerFee, +// takerFeePaid: order.takerFee, +// protocolFeePaid: protocolFeeMultiplier, +// }; +// } + +// // Creates a deterministic order signature, even though no signature validation +// // actually occurs in the test contract. +// function createOrderSignature(order: Order): string { +// return ethjs.bufferToHex(ethjs.sha3(ethjs.toBuffer(orderHashUtils.getOrderHashHex(order)))); +// } + +// // Asserts that `_fillOrder()` was called in the same order and with the same +// // arguments as given by examining receipt logs. +// function assertFillOrderCallsFromLogs(logs: LogEntry[], calls: Array<[Order, BigNumber, string]>): void { +// expect(logs.length).to.eq(calls.length); +// for (const i of _.times(calls.length)) { +// const log = (logs[i] as any) as LogWithDecodedArgs; +// const [expectedOrder, expectedTakerAssetFillAmount, expectedSignature] = calls[i]; +// expect(log.event).to.eq('FillOrderCalled'); +// assertSameOrderFromEvent(log.args.order as any, expectedOrder); +// expect(log.args.takerAssetFillAmount).to.bignumber.eq(expectedTakerAssetFillAmount); +// expect(log.args.signature).to.eq(expectedSignature); +// } +// } + +// function assertSameOrderFromEvent(actual: any[], expected: Order): void { +// expect(actual.length === 14); +// expect(actual[0].toLowerCase()).to.be.eq(expected.makerAddress); +// expect(actual[1].toLowerCase()).to.be.eq(expected.takerAddress); +// expect(actual[2].toLowerCase()).to.be.eq(expected.feeRecipientAddress); +// expect(actual[3].toLowerCase()).to.be.eq(expected.senderAddress); +// expect(actual[4]).to.be.bignumber.eq(expected.makerAssetAmount); +// expect(actual[5]).to.be.bignumber.eq(expected.takerAssetAmount); +// expect(actual[6]).to.be.bignumber.eq(expected.makerFee); +// expect(actual[7]).to.be.bignumber.eq(expected.takerFee); +// expect(actual[8]).to.be.bignumber.eq(expected.expirationTimeSeconds); +// expect(actual[9]).to.be.bignumber.eq(expected.salt); +// expect(actual[10]).to.be.eq(expected.makerAssetData); +// expect(actual[11]).to.be.eq(expected.takerAssetData); +// expect(actual[12]).to.be.eq(expected.makerFeeAssetData); +// expect(actual[13]).to.be.eq(expected.takerFeeAssetData); +// } + +// describe('fillOrKillOrder', () => { +// it('works if the order is filled by exactly `takerAssetFillAmount`', async () => { +// const fillAmount = randomAmount(); +// const order = randomOrder({ +// // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as +// // the `takerAssetFilledAmount`. +// takerAssetAmount: fillAmount, +// }); +// const signature = createOrderSignature(order); +// const expectedResult = getExpectedFillResults(order, signature); +// const expectedCalls = [[order, fillAmount, signature]]; +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.fillOrKillOrder, +// order, +// fillAmount, +// signature, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('reverts if the order is filled by less than `takerAssetFillAmount`', async () => { +// const fillAmount = randomAmount(); +// const order = randomOrder({ +// // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as +// // the `takerAssetFilledAmount`. +// takerAssetAmount: fillAmount.minus(1), +// }); +// const signature = createOrderSignature(order); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, +// fillAmount, +// fillAmount.minus(1), +// ); +// const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync(); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if the order is filled by greater than `takerAssetFillAmount`', async () => { +// const fillAmount = randomAmount(); +// const order = randomOrder({ +// // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as +// // the `takerAssetFilledAmount`. +// takerAssetAmount: fillAmount.plus(1), +// }); +// const signature = createOrderSignature(order); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, +// fillAmount, +// fillAmount.plus(1), +// ); +// const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync(); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if `_fillOrder()` reverts', async () => { +// const fillAmount = randomAmount(); +// const order = randomOrder({ +// salt: ALWAYS_FAILING_SALT, +// }); +// const signature = createOrderSignature(order); +// const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR; +// const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync(); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); + +// describe('fillOrderNoThrow', () => { +// it('calls `fillOrder()` and returns its result', async () => { +// const fillAmount = randomAmount(); +// const order = randomOrder(); +// const signature = createOrderSignature(order); +// const expectedResult = getExpectedFillResults(order, signature); +// const expectedCalls = [[order, fillAmount, signature]]; +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.fillOrderNoThrow, +// order, +// fillAmount, +// signature, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('does not revert if `fillOrder()` reverts', async () => { +// const fillAmount = randomAmount(); +// const order = randomOrder({ +// salt: ALWAYS_FAILING_SALT, +// }); +// const signature = createOrderSignature(order); +// const expectedResult = EMPTY_FILL_RESULTS; +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.fillOrderNoThrow, +// order, +// fillAmount, +// signature, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, []); +// }); +// }); + +// describe('batchFillOrders', () => { +// it('works with no fills', async () => { +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrders, +// [], +// [], +// [], +// ); +// expect(actualResult).to.deep.eq([]); +// assertFillOrderCallsFromLogs(receipt.logs, []); +// }); + +// it('works with one fill', async () => { +// const COUNT = 1; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works with many fills', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works with duplicate orders', async () => { +// const NUM_UNIQUE_ORDERS = 2; +// const COUNT = 4; +// const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); +// const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount.dividedToIntegerBy(COUNT)); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('reverts if there are more orders than fill amounts', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// 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 = transactionHelper.getResultAndReceiptAsync(testContract.batchFillOrders, orders, fillAmounts, signatures); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if there are more orders than signatures', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// 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 = transactionHelper.getResultAndReceiptAsync(testContract.batchFillOrders, orders, fillAmounts, signatures); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); + +// describe('batchFillOrKillOrders', () => { +// it('works with no fills', async () => { +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// [], +// [], +// [], +// ); +// expect(actualResult).to.deep.eq([]); +// assertFillOrderCallsFromLogs(receipt.logs, []); +// }); + +// it('works with one fill', async () => { +// const COUNT = 1; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works with many fills', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works with duplicate orders', async () => { +// const NUM_UNIQUE_ORDERS = 2; +// const COUNT = 4; +// const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); +// const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('reverts if any fill sells less than its takerAssetFillAmount', async () => { +// const COUNT = 8; +// const FAILING_ORDER_INDEX = 6; +// const orders = _.times(COUNT, () => randomOrder()); +// const failingOrder = orders[FAILING_ORDER_INDEX]; +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// const failingAmount = fillAmounts[FAILING_ORDER_INDEX]; +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as +// // the `takerAssetFilledAmount`. +// failingOrder.takerAssetAmount = failingOrder.takerAssetAmount.minus(1); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, +// failingAmount, +// failingAmount.minus(1), +// ); +// const tx = transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if any fill sells more than its takerAssetFillAmount', async () => { +// const COUNT = 8; +// const FAILING_ORDER_INDEX = 6; +// const orders = _.times(COUNT, () => randomOrder()); +// const failingOrder = orders[FAILING_ORDER_INDEX]; +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// const failingAmount = fillAmounts[FAILING_ORDER_INDEX]; +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// // `_fillOrder()` is overridden to always return `order.takerAssetAmount` as +// // the `takerAssetFilledAmount`. +// failingOrder.takerAssetAmount = failingOrder.takerAssetAmount.plus(1); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder, +// failingAmount, +// failingAmount.plus(1), +// ); +// const tx = transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if there are more orders than fill amounts', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// 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 = transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if there are more orders than signatures', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// 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 = transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrKillOrders, +// orders, +// fillAmounts, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); + +// describe('batchFillOrdersNoThrow', () => { +// it('works with no fills', async () => { +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// [], +// [], +// [], +// ); +// expect(actualResult).to.deep.eq([]); +// assertFillOrderCallsFromLogs(receipt.logs, []); +// }); + +// it('works with one fill', async () => { +// const COUNT = 1; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works with many fills', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works with duplicate orders', async () => { +// const NUM_UNIQUE_ORDERS = 2; +// const COUNT = 4; +// const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); +// const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount.dividedToIntegerBy(COUNT)); +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('works if a fill fails', async () => { +// const COUNT = 8; +// const FAILING_ORDER_INDEX = 6; +// const orders = _.times(COUNT, () => randomOrder()); +// const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const failingOrder = orders[FAILING_ORDER_INDEX]; +// failingOrder.salt = ALWAYS_FAILING_SALT; +// 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 transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// orders, +// fillAmounts, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any); +// }); + +// it('reverts if there are more orders than fill amounts', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// 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 = transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// orders, +// fillAmounts, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts if there are more orders than signatures', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// 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 = transactionHelper.getResultAndReceiptAsync( +// testContract.batchFillOrdersNoThrow, +// orders, +// fillAmounts, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); + +// type ExpectedFillOrderCallArgs = [Order, BigNumber, string]; +// type MarketSellBuyArgs = [Order[], BigNumber, string[], ...any[]]; +// type MarketSellBuyContractFunction = () => MutatorContractFunction<[FillResults, ExpectedFillOrderCallArgs[]]>; +// type MarketSellBuySimulator = (...args: MarketSellBuyArgs) => [FillResults, ExpectedFillOrderCallArgs[]]; + +// describe('marketSell*', () => { +// function defineCommonMarketSellOrdersTests( +// getContractFn: MarketSellBuyContractFunction, +// simulator: MarketSellBuySimulator, +// ): void { +// it('works with one order', async () => { +// const COUNT = 1; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); +// expect(expectedCalls.length).to.eq(COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('works with many orders', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); +// expect(expectedCalls.length).to.eq(COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('works with duplicate orders', async () => { +// const NUM_UNIQUE_ORDERS = 2; +// const COUNT = 4; +// const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); +// const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); +// expect(expectedCalls.length).to.eq(COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('stops when filled == `takerAssetFillAmount`', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// // Skip the last order in our `takerAssetFillAmount` calculation. +// const takerAssetFillAmount = _.reduce( +// orders.slice(0, COUNT - 1), +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// 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 transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('stops when filled > `takerAssetFillAmount`', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// // Because `TestWrapperFunctions` always fills `takerAssetAmount` +// // setting the first order's `takerAssetAmount` to larger than +// // `takerAssetFillAmount` will cause an overfill. +// orders[0].takerAssetAmount = takerAssetFillAmount.plus(1); +// const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures); +// // It should stop filling after first order. +// expect(expectedCalls.length).to.eq(1); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('reverts when an overflow occurs when summing fill results', async () => { +// const COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// orders[1].takerAssetAmount = MAX_UINT256; +// const takerAssetFillAmount = MAX_UINT256; +// const expectedError = new SafeMathRevertErrors.Uint256BinOpError( +// SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow, +// orders[0].takerAssetAmount, +// orders[1].takerAssetAmount, +// ); +// const tx = transactionHelper.getResultAndReceiptAsync(getContractFn, orders, takerAssetFillAmount, signatures); +// 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 transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// [], +// constants.ZERO_AMOUNT, +// [], +// ); + +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); +// } + +// function simulateMarketSellOrders( +// orders: Order[], +// takerAssetFillAmount: BigNumber, +// signatures: string[], +// ): [FillResults, ExpectedFillOrderCallArgs[]] { +// const fillOrderCalls = []; +// let fillResults = _.cloneDeep(EMPTY_FILL_RESULTS); +// for (const [order, signature] of _.zip(orders, signatures) as [[Order, string]]) { +// const remainingTakerAssetFillAmount = safeSub(takerAssetFillAmount, fillResults.takerAssetFilledAmount); +// if (order.salt !== ALWAYS_FAILING_SALT) { +// fillOrderCalls.push([order, remainingTakerAssetFillAmount, signature]); +// } +// fillResults = addFillResults(fillResults, getExpectedFillResults(order, signature)); +// if (fillResults.takerAssetFilledAmount.gte(takerAssetFillAmount)) { +// break; +// } +// } +// return [fillResults, fillOrderCalls as any]; +// } + +// describe('marketSellOrdersNoThrow', () => { +// defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders); + +// it('works when any fills revert', async () => { +// const COUNT = 4; +// const BAD_ORDERS_COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); +// for (const order of badOrders) { +// order.salt = ALWAYS_FAILING_SALT; +// } +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulateMarketSellOrders( +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.marketSellOrdersNoThrow, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('works when all fills revert', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder({ salt: ALWAYS_FAILING_SALT })); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulateMarketSellOrders( +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(expectedCalls.length).to.eq(0); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.marketSellOrdersNoThrow, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); +// }); + +// describe('marketSellOrdersFillOrKill', () => { +// defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders); + +// it('reverts when filled < `takerAssetFillAmount`', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ).plus(1); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketSellOrders, +// takerAssetFillAmount, +// takerAssetFillAmount.minus(1), +// ); +// const tx = transactionHelper.getResultAndReceiptAsync( +// testContract.marketSellOrdersFillOrKill, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('works when fills fail but can still sell `takerAssetFillAmount`', async () => { +// const COUNT = 4; +// const BAD_ORDERS_COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); +// for (const order of badOrders) { +// order.salt = ALWAYS_FAILING_SALT; +// } +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ).minus(_.reduce(badOrders, (total, o) => o.takerAssetAmount.plus(total), constants.ZERO_AMOUNT)); +// const [expectedResult, expectedCalls] = simulateMarketSellOrders( +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.marketSellOrdersFillOrKill, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('reverts when a failed fill results in selling less than `takerAssetFillAmount`', async () => { +// const COUNT = 4; +// const BAD_ORDERS_COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); +// for (const order of badOrders) { +// order.salt = ALWAYS_FAILING_SALT; +// } +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const badOrdersAmount = _.reduce( +// badOrders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const takerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.takerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ) +// .minus(badOrdersAmount) +// .plus(1); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketSellOrders, +// takerAssetFillAmount, +// takerAssetFillAmount.minus(1), +// ); +// const tx = transactionHelper.getResultAndReceiptAsync( +// testContract.marketSellOrdersFillOrKill, +// orders, +// takerAssetFillAmount, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); +// }); + +// describe('marketBuy*', () => { +// function defineCommonMarketBuyOrdersTests( +// getContractFn: () => MarketSellBuyContractFunction, +// simulator: MarketSellBuySimulator, +// ): void { +// it('works with one order', async () => { +// const COUNT = 1; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); +// expect(expectedCalls.length).to.eq(COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('works with many orders', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); +// expect(expectedCalls.length).to.eq(COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('works with duplicate orders', async () => { +// const NUM_UNIQUE_ORDERS = 2; +// const COUNT = 4; +// const uniqueOrders = _.times(NUM_UNIQUE_ORDERS, () => randomOrder()); +// const orders = _.shuffle(_.flatten(_.times(COUNT / NUM_UNIQUE_ORDERS, () => uniqueOrders))); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); +// expect(expectedCalls.length).to.eq(COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn(), +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('stops when filled == `makerAssetFillAmount`', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// // Skip the last order in our `makerAssetFillAmount` calculation. +// const makerAssetFillAmount = _.reduce( +// orders.slice(0, COUNT - 1), +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// 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 transactionHelper.getResultAndReceiptAsync( +// getContractFn(), +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('stops when filled > `makerAssetFillAmount`', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// // Because `TestWrapperFunctions` always fills `makerAssetAmount` +// // setting the first order's `makerAssetAmount` to larger than +// // `makerAssetFillAmount` will cause an overfill. +// orders[0].makerAssetAmount = makerAssetFillAmount.plus(1); +// const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures); +// // It should stop filling after first order. +// expect(expectedCalls.length).to.eq(1); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// getContractFn(), +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('reverts when an overflow occurs when computing `remainingTakerAssetFillAmount`', async () => { +// const orders = [randomOrder({ takerAssetAmount: MAX_UINT256 })]; +// const signatures = _.times(orders.length, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = new BigNumber(2); +// const expectedError = new SafeMathRevertErrors.Uint256BinOpError( +// SafeMathRevertErrors.BinOpErrorCodes.MultiplicationOverflow, +// orders[0].takerAssetAmount, +// makerAssetFillAmount, +// ); +// const tx = transactionHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it("reverts when an order's `makerAssetAmount` is zero", async () => { +// const orders = [randomOrder({ makerAssetAmount: constants.ZERO_AMOUNT })]; +// const signatures = _.times(orders.length, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = ONE_ETHER; +// const expectedError = new SafeMathRevertErrors.Uint256BinOpError( +// SafeMathRevertErrors.BinOpErrorCodes.DivisionByZero, +// orders[0].takerAssetAmount.times(makerAssetFillAmount), +// orders[0].makerAssetAmount, +// ); +// const tx = transactionHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('reverts when an overflow occurs when summing fill results', async () => { +// const orders = [ +// randomOrder({ +// takerAssetAmount: new BigNumber(1), +// makerAssetAmount: new BigNumber(1), +// }), +// randomOrder({ +// takerAssetAmount: new BigNumber(1), +// makerAssetAmount: MAX_UINT256, +// }), +// ]; +// const signatures = _.times(orders.length, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = new BigNumber(2); +// const expectedError = new SafeMathRevertErrors.Uint256BinOpError( +// SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow, +// orders[0].makerAssetAmount, +// orders[1].makerAssetAmount, +// ); +// const tx = transactionHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures); +// 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 transactionHelper.getResultAndReceiptAsync( +// getContractFn(), +// [], +// constants.ZERO_AMOUNT, +// [], +// ); + +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); +// } + +// function simulateMarketBuyOrdersNoThrow( +// orders: Order[], +// makerAssetFillAmount: BigNumber, +// signatures: string[], +// ): [FillResults, ExpectedFillOrderCallArgs[]] { +// const fillOrderCalls = []; +// let fillResults = _.cloneDeep(EMPTY_FILL_RESULTS); +// for (const [order, signature] of _.zip(orders, signatures) as [[Order, string]]) { +// const remainingMakerAssetFillAmount = safeSub(makerAssetFillAmount, fillResults.makerAssetFilledAmount); +// const remainingTakerAssetFillAmount = getPartialAmountFloor( +// order.takerAssetAmount, +// order.makerAssetAmount, +// remainingMakerAssetFillAmount, +// ); +// if (order.salt !== ALWAYS_FAILING_SALT) { +// fillOrderCalls.push([order, remainingTakerAssetFillAmount, signature]); +// } +// fillResults = addFillResults(fillResults, getExpectedFillResults(order, signature)); +// if (fillResults.makerAssetFilledAmount.gte(makerAssetFillAmount)) { +// break; +// } +// } +// return [fillResults, fillOrderCalls as any]; +// } + +// describe('marketBuyOrdersNoThrow', () => { +// defineCommonMarketBuyOrdersTests(() => testContract.marketBuyOrdersNoThrow, simulateMarketBuyOrdersNoThrow); + +// it('works when any fills revert', async () => { +// const COUNT = 4; +// const BAD_ORDERS_COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); +// for (const order of badOrders) { +// order.salt = ALWAYS_FAILING_SALT; +// } +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulateMarketBuyOrdersNoThrow( +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.marketBuyOrdersNoThrow, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('works when all fills revert', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder({ salt: ALWAYS_FAILING_SALT })); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const [expectedResult, expectedCalls] = simulateMarketBuyOrdersNoThrow( +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(expectedCalls.length).to.eq(0); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.marketBuyOrdersNoThrow, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); +// }); + +// describe('marketBuyOrdersFillOrKill', () => { +// defineCommonMarketBuyOrdersTests( +// () => testContract.marketBuyOrdersFillOrKill, +// simulateMarketBuyOrdersNoThrow, +// ); + +// it('reverts when filled < `makerAssetFillAmount`', async () => { +// const COUNT = 4; +// const orders = _.times(COUNT, () => randomOrder()); +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ).plus(1); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketBuyOrders, +// makerAssetFillAmount, +// makerAssetFillAmount.minus(1), +// ); +// const tx = transactionHelper.getResultAndReceiptAsync( +// testContract.marketBuyOrdersFillOrKill, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); + +// it('works when fills fail but can still buy `makerAssetFillAmount`', async () => { +// const COUNT = 4; +// const BAD_ORDERS_COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); +// for (const order of badOrders) { +// order.salt = ALWAYS_FAILING_SALT; +// } +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ).minus(_.reduce(badOrders, (total, o) => o.makerAssetAmount.plus(total), constants.ZERO_AMOUNT)); +// const [expectedResult, expectedCalls] = simulateMarketBuyOrdersNoThrow( +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT); +// const [actualResult, receipt] = await transactionHelper.getResultAndReceiptAsync( +// testContract.marketBuyOrdersFillOrKill, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// expect(actualResult).to.deep.eq(expectedResult); +// assertFillOrderCallsFromLogs(receipt.logs, expectedCalls); +// }); + +// it('reverts when a failed fill results in buying less than `makerAssetFillAmount`', async () => { +// const COUNT = 4; +// const BAD_ORDERS_COUNT = 2; +// const orders = _.times(COUNT, () => randomOrder()); +// const badOrders = _.sampleSize(orders, BAD_ORDERS_COUNT); +// for (const order of badOrders) { +// order.salt = ALWAYS_FAILING_SALT; +// } +// const signatures = _.times(COUNT, i => createOrderSignature(orders[i])); +// const badOrdersAmount = _.reduce( +// badOrders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ); +// const makerAssetFillAmount = _.reduce( +// orders, +// (total, o) => o.makerAssetAmount.plus(total), +// constants.ZERO_AMOUNT, +// ) +// .minus(badOrdersAmount) +// .plus(1); +// const expectedError = new ExchangeRevertErrors.IncompleteFillError( +// ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteMarketBuyOrders, +// makerAssetFillAmount, +// makerAssetFillAmount.minus(1), +// ); +// const tx = transactionHelper.getResultAndReceiptAsync( +// testContract.marketBuyOrdersFillOrKill, +// orders, +// makerAssetFillAmount, +// signatures, +// ); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); +// }); + +// describe('batchCancelOrders', () => { +// // Asserts that `_cancelOrder()` was called in the same order and with the same +// // arguments as given by examining receipt logs. +// function assertCancelOrderCallsFromLogs(logs: LogEntry[], calls: Order[]): void { +// expect(logs.length).to.eq(calls.length); +// for (const i of _.times(calls.length)) { +// const log = (logs[i] as any) as LogWithDecodedArgs; +// const expectedOrder = calls[i]; +// expect(log.event).to.eq('CancelOrderCalled'); +// assertSameOrderFromEvent(log.args.order as any, expectedOrder); +// } +// } + +// it('works with no orders', async () => { +// const [, receipt] = await transactionHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, []); +// assertCancelOrderCallsFromLogs(receipt.logs, []); +// }); + +// it('works with many orders', async () => { +// const COUNT = 8; +// const orders = _.times(COUNT, () => randomOrder({ makerAddress: senderAddress })); +// const [, receipt] = await transactionHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders); +// assertCancelOrderCallsFromLogs(receipt.logs, orders); +// }); + +// it('works with duplicate orders', async () => { +// const UNIQUE_ORDERS = 2; +// const COUNT = 6; +// const uniqueOrders = _.times(UNIQUE_ORDERS, () => randomOrder({ makerAddress: senderAddress })); +// const orders = _.shuffle(_.flatten(_.times(COUNT / UNIQUE_ORDERS, () => uniqueOrders))); +// const [, receipt] = await transactionHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders); +// assertCancelOrderCallsFromLogs(receipt.logs, orders); +// }); + +// it('reverts if one `_cancelOrder()` reverts', async () => { +// const COUNT = 8; +// const FAILING_ORDER_INDEX = 4; +// const orders = _.times(COUNT, () => randomOrder({ makerAddress: senderAddress })); +// const failingOrder = orders[FAILING_ORDER_INDEX]; +// failingOrder.salt = ALWAYS_FAILING_SALT; +// const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR; +// const tx = transactionHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders); +// return expect(tx).to.revertWith(expectedError); +// }); +// }); +// }); +// // tslint:disable-next-line: max-file-line-count diff --git a/contracts/extensions/test/balance_threshold_filter.ts b/contracts/extensions/test/balance_threshold_filter.ts index 7fe4ee5566..e1549c4707 100644 --- a/contracts/extensions/test/balance_threshold_filter.ts +++ b/contracts/extensions/test/balance_threshold_filter.ts @@ -126,7 +126,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(); @@ -142,7 +142,7 @@ describe(ContractName.BalanceThresholdFilter, () => { exchangeWrapper = new ExchangeWrapper(exchangeInstance); // Register proxies await exchangeWrapper.registerAssetProxyAsync(erc20Proxy.address, owner); - await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, { + await erc20Proxy.addAuthorizedAddress(exchangeInstance.address).sendTransactionAsync({ from: owner, }); // Deploy Balance Threshold Filters @@ -173,8 +173,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), @@ -296,12 +296,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 () => { @@ -1239,8 +1236,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 c7cfab18ab..83df0c61c3 100644 --- a/contracts/extensions/test/dutch_auction.ts +++ b/contracts/extensions/test/dutch_auction.ts @@ -89,7 +89,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, @@ -102,10 +102,10 @@ describe(ContractName.DutchAuction, () => { await exchangeWrapper.registerAssetProxyAsync(erc20Proxy.address, owner); await exchangeWrapper.registerAssetProxyAsync(erc721Proxy.address, 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, }); @@ -130,11 +130,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); @@ -156,11 +154,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, @@ -182,7 +180,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(); @@ -321,7 +319,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); @@ -330,10 +328,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, @@ -356,7 +353,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 bd85592601..079ae9b937 100644 --- a/contracts/extensions/test/order_matcher.ts +++ b/contracts/extensions/test/order_matcher.ts @@ -114,7 +114,7 @@ describe('OrderMatcher', () => { provider, txDefaults, artifacts, - await devUtils.encodeERC20AssetData.callAsync(zrxToken.address), + await devUtils.encodeERC20AssetData(zrxToken.address).callAsync(), new BigNumber(chainId), ); exchangeWrapper = new ExchangeWrapper(exchange); @@ -122,7 +122,7 @@ describe('OrderMatcher', () => { await exchangeWrapper.registerAssetProxyAsync(erc721Proxy.address, 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, @@ -138,35 +138,33 @@ 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, { + await erc20TokenA.setBalance(orderMatcher.address, constants.INITIAL_ERC20_BALANCE).sendTransactionAsync({ from: owner, }), constants.AWAIT_TRANSACTION_MINED_MS, ); await web3Wrapper.awaitTransactionSuccessAsync( - await erc20TokenB.setBalance.sendTransactionAsync(orderMatcher.address, constants.INITIAL_ERC20_BALANCE, { + await erc20TokenB.setBalance(orderMatcher.address, constants.INITIAL_ERC20_BALANCE).sendTransactionAsync({ 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 web3Wrapper + .awaitTransactionSuccessAsync( + await orderMatcher.approveAssetProxy(leftMakerAssetData, constants.INITIAL_ERC20_ALLOWANCE), + constants.AWAIT_TRANSACTION_MINED_MS, + ) + .sendTransactionAsync(); + await web3Wrapper + .awaitTransactionSuccessAsync( + await orderMatcher.approveAssetProxy(leftTakerAssetData, constants.INITIAL_ERC20_ALLOWANCE), + constants.AWAIT_TRANSACTION_MINED_MS, + ) + .sendTransactionAsync(); // Create default order parameters const defaultOrderParamsLeft = { @@ -238,12 +236,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, @@ -273,13 +268,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, @@ -289,7 +281,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( @@ -334,13 +326,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, @@ -350,7 +339,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( @@ -396,15 +385,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, @@ -414,8 +400,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( @@ -454,12 +440,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({ @@ -492,12 +475,9 @@ describe('OrderMatcher', () => { await exchangeWrapper.fillOrderAsync(signedOrderRight, takerAddress, { takerAssetFillAmount: signedOrderRight.takerAssetAmount.dividedToIntegerBy(5), }); - 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({ @@ -540,15 +520,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, @@ -558,8 +535,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( @@ -610,17 +587,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, @@ -630,8 +604,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( @@ -671,12 +645,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, @@ -698,17 +669,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, @@ -721,14 +689,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 () => { @@ -742,22 +710,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); @@ -767,12 +735,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 () => { @@ -784,16 +752,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 () => { @@ -805,21 +774,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 30d1798aeb..f1983e092b 100644 --- a/contracts/extensions/test/utils/balance_threshold_wrapper.ts +++ b/contracts/extensions/test/utils/balance_threshold_wrapper.ts @@ -39,11 +39,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; } @@ -53,11 +51,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; } @@ -67,11 +63,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; } @@ -81,11 +75,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; } @@ -95,11 +87,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; } @@ -109,11 +99,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; } @@ -123,11 +111,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; } @@ -137,11 +123,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; } @@ -151,11 +135,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; } @@ -165,17 +147,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; } @@ -184,33 +164,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( @@ -219,12 +199,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; } @@ -234,21 +211,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 { @@ -264,13 +236,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/test/actors/base.ts b/contracts/integrations/test/actors/base.ts index a763e02f8d..e2d2c2e618 100644 --- a/contracts/integrations/test/actors/base.ts +++ b/contracts/integrations/test/actors/base.ts @@ -46,22 +46,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 }); } /** @@ -76,19 +73,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 22763f76ba..249aad85b6 100644 --- a/contracts/integrations/test/actors/pool_operator.ts +++ b/contracts/integrations/test/actors/pool_operator.ts @@ -43,11 +43,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; @@ -64,11 +62,9 @@ export function PoolOperatorMixin(Base: TBase): TBase ): Promise { const stakingContract = this.actor.deployment.staking.stakingWrapper; this.operatorShares[poolId] = newOperatorShare; - return stakingContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - newOperatorShare, - { from: this.actor.address }, - ); + return stakingContract + .decreaseStakingPoolOperatorShare(poolId, newOperatorShare) + .awaitTransactionSuccessAsync({ from: this.actor.address }); } }; } diff --git a/contracts/integrations/test/actors/staker.ts b/contracts/integrations/test/actors/staker.ts index 0e2c48e8c6..77fa8e9636 100644 --- a/contracts/integrations/test/actors/staker.ts +++ b/contracts/integrations/test/actors/staker.ts @@ -32,16 +32,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 }); } } }; diff --git a/contracts/integrations/test/actors/taker.ts b/contracts/integrations/test/actors/taker.ts index a63311b139..36ad4237e8 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 d953739a3f..7409b64af7 100644 --- a/contracts/integrations/test/coordinator/coordinator_test.ts +++ b/contracts/integrations/test/coordinator/coordinator_test.ts @@ -64,10 +64,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(), }, }); @@ -141,7 +141,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(), ); } } @@ -187,13 +187,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(); @@ -202,13 +198,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(); @@ -217,13 +209,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], @@ -236,13 +227,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(); @@ -251,13 +238,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(); @@ -266,13 +249,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, @@ -287,13 +266,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, @@ -302,13 +277,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); @@ -335,13 +306,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(); @@ -351,13 +318,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(); @@ -367,13 +330,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(); @@ -387,13 +346,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, @@ -401,13 +359,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); }); @@ -432,13 +389,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); }); @@ -449,13 +402,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); }); @@ -465,13 +414,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/forwarder/forwarder_test.ts b/contracts/integrations/test/forwarder/forwarder_test.ts index f521b9e44c..9bc82e4762 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 fcc0b83199..70be41d387 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 7cc4a15424..f5e92e2b3e 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 f10ec1efb7..b9158c16dd 100644 --- a/contracts/integrations/test/framework-unit-tests/function_assertion_test.ts +++ b/contracts/integrations/test/framework-unit-tests/function_assertion_test.ts @@ -45,7 +45,7 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => { }); it('should not fail immediately if the wrapped function fails', async () => { - const assertion = new FunctionAssertion<{}>(exampleContract.emptyRevert); + const assertion = new FunctionAssertion<{}, void>(exampleContract.emptyRevert); await assertion.executeAsync(); }); diff --git a/contracts/integrations/test/internal-integration-tests/deployment_test.ts b/contracts/integrations/test/internal-integration-tests/deployment_test.ts index d6e49e0e09..bbee978626 100644 --- a/contracts/integrations/test/internal-integration-tests/deployment_test.ts +++ b/contracts/integrations/test/internal-integration-tests/deployment_test.ts @@ -116,7 +116,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( @@ -164,12 +164,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( @@ -179,7 +178,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); } @@ -189,10 +188,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( @@ -202,7 +200,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(); } @@ -262,13 +260,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, @@ -282,7 +280,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, }); @@ -294,18 +292,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( @@ -320,15 +317,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( @@ -343,7 +340,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); }); }); @@ -354,7 +351,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( @@ -364,11 +361,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, }); @@ -380,17 +377,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 2ba36dcce6..0889c28606 100644 --- a/contracts/integrations/test/internal-integration-tests/exchange_wrapper_test.ts +++ b/contracts/integrations/test/internal-integration-tests/exchange_wrapper_test.ts @@ -19,7 +19,7 @@ import { Numberish, provider, toBaseUnitAmount, - TransactionHelper, + transactionHelper, verifyEvents, } from '@0x/contracts-test-utils'; import { ExchangeRevertErrors, orderHashUtils } from '@0x/order-utils'; @@ -55,7 +55,6 @@ blockchainTests.resets('Exchange wrappers', env => { let localBalances: LocalBalanceStore; let wethAssetData: string; - let txHelper: TransactionHelper; before(async () => { [feeRecipient] = await env.getAccountAddressesAsync(); @@ -70,10 +69,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,13 +110,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, - }); + wethAssetData = await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(); }); beforeEach(async () => { @@ -324,7 +317,7 @@ blockchainTests.resets('Exchange wrappers', env => { }); const takerAssetFilledAmount = signedOrder.takerAssetAmount.div(2); - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( + const [fillResults, receipt] = await transactionHelper.getResultAndReceiptAsync( deployment.exchange.fillOrKillOrder, signedOrder, takerAssetFilledAmount, @@ -368,12 +361,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); }); @@ -381,23 +375,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); }); }); @@ -440,7 +436,7 @@ blockchainTests.resets('Exchange wrappers', env => { await simulateFillAsync(signedOrder, expectedFillResults, shouldPayWethFees); } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( + const [fillResults, receipt] = await transactionHelper.getResultAndReceiptAsync( deployment.exchange.batchFillOrders, signedOrders, takerAssetFillAmounts, @@ -502,7 +498,7 @@ blockchainTests.resets('Exchange wrappers', env => { await simulateFillAsync(signedOrder, expectedFillResults, shouldPayWethFees); } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( + const [fillResults, receipt] = await transactionHelper.getResultAndReceiptAsync( deployment.exchange.batchFillOrKillOrders, signedOrders, takerAssetFillAmounts, @@ -534,25 +530,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); }); }); @@ -596,7 +594,7 @@ blockchainTests.resets('Exchange wrappers', env => { } } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( + const [fillResults, receipt] = await transactionHelper.getResultAndReceiptAsync( deployment.exchange.batchFillOrdersNoThrow, signedOrdersWithValidity.map(signedOrderWithValidity => signedOrderWithValidity.signedOrder), takerAssetFillAmounts, @@ -711,7 +709,7 @@ blockchainTests.resets('Exchange wrappers', env => { } } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( + const [fillResults, receipt] = await transactionHelper.getResultAndReceiptAsync( deployment.exchange.marketSellOrdersNoThrow, signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder), takerAssetFillAmount, @@ -781,9 +779,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(), @@ -804,9 +802,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(), @@ -909,7 +907,7 @@ blockchainTests.resets('Exchange wrappers', env => { } } - const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync( + const [fillResults, receipt] = await transactionHelper.getResultAndReceiptAsync( deployment.exchange.marketBuyOrdersNoThrow, signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder), makerAssetFillAmount, @@ -979,9 +977,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(), @@ -1003,9 +1001,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(), @@ -1069,7 +1067,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)); @@ -1080,13 +1078,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 16f532f609..21f556ad16 100644 --- a/contracts/integrations/test/internal-integration-tests/fillorder_test.ts +++ b/contracts/integrations/test/internal-integration-tests/fillorder_test.ts @@ -50,10 +50,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, }; @@ -133,7 +133,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(), ); } @@ -224,7 +224,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, [ @@ -253,7 +253,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( @@ -295,7 +295,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(); @@ -336,7 +336,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 () => { @@ -375,7 +375,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/utils/deployment_manager.ts b/contracts/integrations/test/utils/deployment_manager.ts index b67008cbf1..93a8ebd3a8 100644 --- a/contracts/integrations/test/utils/deployment_manager.ts +++ b/contracts/integrations/test/utils/deployment_manager.ts @@ -41,7 +41,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 }); } } } @@ -59,7 +59,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 }); } } } @@ -76,7 +76,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 }); } } @@ -174,16 +174,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, [ @@ -266,13 +266,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 }); } /** @@ -365,20 +365,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/utils/function_assertions.ts b/contracts/integrations/test/utils/function_assertions.ts index 37ebceb2cc..c3bb3c6ccf 100644 --- a/contracts/integrations/test/utils/function_assertions.ts +++ b/contracts/integrations/test/utils/function_assertions.ts @@ -1,16 +1,10 @@ -import { PromiseWithTransactionHash } from '@0x/base-contract'; +import { ContractFunctionObj, ContractTxFunctionObj, PromiseWithTransactionHash } 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 Result { data?: any; @@ -53,14 +47,21 @@ export interface RunResult { * 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[] + ) => ContractTxFunctionObj | ContractFunctionObj; - constructor(wrapperFunction: ContractWrapperFunction, condition: Partial> = {}) { + constructor( + wrapperFunction: ( + ...args: any[] + ) => ContractTxFunctionObj | ContractFunctionObj, + condition: Partial> = {}, + ) { this.condition = { before: _.noop.bind(this), after: _.noop.bind(this), @@ -83,10 +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); + 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() : undefined; } catch (error) { callResult.data = error; diff --git a/contracts/multisig/test/multi_sig_with_time_lock.ts b/contracts/multisig/test/multi_sig_with_time_lock.ts index 6f59a7f60b..3eff2c87ea 100644 --- a/contracts/multisig/test/multi_sig_with_time_lock.ts +++ b/contracts/multisig/test/multi_sig_with_time_lock.ts @@ -125,9 +125,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; @@ -255,25 +255,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; @@ -287,14 +287,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; @@ -302,7 +302,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); }); }); @@ -327,7 +327,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, @@ -340,19 +340,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 11f2ce51eb..077d577272 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 19a0688fd9..8adcdc8435 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 9615070613..ff2345b036 100644 --- a/contracts/multisig/test/zero_ex_governor.ts +++ b/contracts/multisig/test/zero_ex_governor.ts @@ -157,10 +157,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]); }); @@ -179,10 +178,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]); } @@ -192,23 +190,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 @@ -217,53 +218,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); }); @@ -271,11 +272,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, @@ -287,91 +286,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(''); }); }); @@ -401,7 +396,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); @@ -410,7 +405,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); @@ -443,12 +438,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, @@ -461,12 +453,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, @@ -479,12 +468,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, @@ -529,12 +515,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, @@ -547,12 +530,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, @@ -629,7 +609,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 () => { @@ -659,12 +639,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 2d2e099b3c..08a95554e0 100644 --- a/contracts/staking/test/actors/finalizer_actor.ts +++ b/contracts/staking/test/actors/finalizer_actor.ts @@ -131,9 +131,9 @@ 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(poolId).callAsync()); } else { - balance = balance.plus(await computeRewardBalanceOfDelegator.callAsync(poolId, delegator)); + balance = balance.plus(await computeRewardBalanceOfDelegator(poolId, delegator).callAsync()); } delegatorBalancesByPoolId[poolId][delegator] = balance; } @@ -150,10 +150,10 @@ export class FinalizerActor extends BaseActor { const delegators = delegatorsByPoolId[poolId]; delegatorBalancesByPoolId[poolId] = {}; for (const delegator of delegators) { - delegatorBalancesByPoolId[poolId][delegator] = (await getStakeDelegatedToPoolByOwner.callAsync( + delegatorBalancesByPoolId[poolId][delegator] = (await getStakeDelegatedToPoolByOwner( delegator, poolId, - )).currentEpochBalance; + ).callAsync()).currentEpochBalance; } } return delegatorBalancesByPoolId; @@ -208,9 +208,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 +219,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 +228,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 +238,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 469f235730..7f5dee39f8 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 ab5d470f34..03191b65bc 100644 --- a/contracts/staking/test/epoch_test.ts +++ b/contracts/staking/test/epoch_test.ts @@ -32,14 +32,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 d6f9b50f2a..43e4e2475d 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 7dc69c08c8..7e0c5fe944 100644 --- a/contracts/staking/test/pools_test.ts +++ b/contracts/staking/test/pools_test.ts @@ -40,7 +40,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 () => { @@ -77,7 +77,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 0f0c4f5172..2974a53782 100644 --- a/contracts/staking/test/rewards_test.ts +++ b/contracts/staking/test/rewards_test.ts @@ -58,7 +58,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(); @@ -117,21 +117,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, @@ -155,12 +153,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(); }; @@ -168,7 +163,7 @@ blockchainTests.resets('Testing Rewards', env => { // sanity balances - all zero await validateEndBalances({}); }); - it('Reward balance should be zero if not delegated, when epoch is greater than 0', async () => { + it.only('Reward balance should be zero if not delegated, when epoch is greater than 0', async () => { await payProtocolFeeAndFinalize(); // sanity balances - all zero await validateEndBalances({}); @@ -574,7 +569,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 @@ -594,18 +589,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); @@ -688,16 +680,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 065178d80a..806d57a2a1 100644 --- a/contracts/staking/test/stake_test.ts +++ b/contracts/staking/test/stake_test.ts @@ -44,7 +44,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 58e4855e20..a031ff2e57 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. @@ -149,7 +153,7 @@ blockchainTests.resets('Delegator rewards unit tests', env => { ...opts, }; const fn = now ? testContract.delegateStakeNow : testContract.delegateStake; - const receipt = await fn.awaitTransactionSuccessAsync(_opts.delegator, poolId, new BigNumber(_opts.stake)); + const receipt = await fn(_opts.delegator, poolId, new BigNumber(_opts.stake)).awaitTransactionSuccessAsync(); const delegatorTransfers = getTransfersFromLogs(receipt.logs, _opts.delegator); return { ..._opts, @@ -164,9 +168,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 +193,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 +211,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 6f21999d87..8dc9e9532e 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 8143917b34..1b3ca90fc2 100644 --- a/contracts/staking/test/unit_tests/finalizer_test.ts +++ b/contracts/staking/test/unit_tests/finalizer_test.ts @@ -75,13 +75,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; } @@ -94,13 +96,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; @@ -207,13 +209,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; } @@ -256,7 +260,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 { @@ -265,13 +269,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, @@ -282,7 +286,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, @@ -292,7 +296,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, @@ -303,7 +307,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, @@ -314,9 +318,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 @@ -328,8 +332,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, @@ -340,7 +344,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([]); @@ -348,21 +352,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]); @@ -373,12 +377,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); @@ -386,7 +389,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)); @@ -397,7 +400,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]; @@ -410,7 +413,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]; @@ -423,18 +426,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); @@ -443,11 +446,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); @@ -457,11 +460,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); }); @@ -476,7 +479,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); } @@ -497,7 +500,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); }); @@ -509,7 +512,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); }); @@ -517,14 +520,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, @@ -534,7 +537,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, { @@ -545,7 +548,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, @@ -554,7 +557,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, @@ -563,7 +566,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 e0080e560e..787c5405c4 100644 --- a/contracts/staking/test/unit_tests/lib_cobb_douglas_test.ts +++ b/contracts/staking/test/unit_tests/lib_cobb_douglas_test.ts @@ -55,18 +55,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 2e98089a67..c53f1ec7d8 100644 --- a/contracts/staking/test/unit_tests/lib_fixed_math_test.ts +++ b/contracts/staking/test/unit_tests/lib_fixed_math_test.ts @@ -40,7 +40,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); }); }); @@ -48,25 +48,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); }); @@ -76,19 +76,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); }); }); @@ -96,19 +96,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); }); @@ -116,7 +116,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); }); }); @@ -124,31 +124,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); }); @@ -157,19 +157,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)); }); @@ -180,7 +180,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); }); @@ -191,7 +191,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); }); @@ -202,19 +202,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()); }); }); @@ -226,19 +226,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)); }); @@ -249,7 +249,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); }); @@ -260,7 +260,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); }); @@ -271,7 +271,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); }); @@ -282,19 +282,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); }); }); @@ -306,19 +306,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)); }); @@ -329,7 +329,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); }); @@ -340,7 +340,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); }); @@ -352,13 +352,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); }); @@ -369,7 +369,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); }); @@ -379,7 +379,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); }); }); @@ -395,31 +395,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)); }); @@ -430,7 +430,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); }); @@ -441,13 +441,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)); }); @@ -458,7 +458,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); }); @@ -469,7 +469,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); }); @@ -480,7 +480,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); }); @@ -491,7 +491,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); }); @@ -502,7 +502,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); }); @@ -513,13 +513,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)); }); }); @@ -540,31 +540,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)); }); @@ -575,7 +575,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); }); @@ -586,13 +586,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); }); }); @@ -600,31 +600,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); }); @@ -634,7 +634,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); }); @@ -645,7 +645,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); }); }); @@ -653,31 +653,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); }); }); @@ -686,37 +686,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); }); @@ -727,7 +727,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); }); @@ -738,7 +738,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); }); }); @@ -746,13 +746,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); }); @@ -762,7 +762,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); }); @@ -772,7 +772,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); }); @@ -783,7 +783,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); }); @@ -794,7 +794,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); }); }); @@ -823,7 +823,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); }); @@ -833,7 +833,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); }); @@ -843,37 +843,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); }); @@ -881,7 +881,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); }); } @@ -901,7 +901,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); }); @@ -911,31 +911,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); }); @@ -943,7 +943,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 9a3ac8931e..f296a21574 100644 --- a/contracts/staking/test/unit_tests/lib_safe_downcast_test.ts +++ b/contracts/staking/test/unit_tests/lib_safe_downcast_test.ts @@ -21,7 +21,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 { @@ -52,7 +52,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 97dcb1753c..462bd10d4d 100644 --- a/contracts/staking/test/unit_tests/mixin_cumulative_rewards_test.ts +++ b/contracts/staking/test/unit_tests/mixin_cumulative_rewards_test.ts @@ -40,89 +40,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]); }); }); @@ -136,22 +126,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); @@ -212,12 +195,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); }); @@ -225,12 +205,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); }); @@ -238,12 +215,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); }); @@ -251,7 +225,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 b8e49225b8..444109f3d2 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 066e4077a4..ed4b57f6c9 100644 --- a/contracts/staking/test/unit_tests/mixin_stake_storage_test.ts +++ b/contracts/staking/test/unit_tests/mixin_stake_storage_test.ts @@ -24,7 +24,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), @@ -48,7 +48,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; } @@ -58,9 +58,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), @@ -100,20 +100,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), ); @@ -122,32 +120,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, @@ -156,16 +154,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, @@ -174,9 +172,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, @@ -184,9 +182,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, @@ -194,9 +192,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 88e344f3be..2dc4580a35 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,7 @@ import { hexRandom, Numberish, randomAddress, - TransactionHelper, + transactionHelper, verifyEventsFromLogs, } from '@0x/contracts-test-utils'; import { BigNumber } from '@0x/utils'; @@ -20,7 +20,6 @@ import { artifacts, TestMixinStakingPoolRewardsContract, TestMixinStakingPoolRew blockchainTests.resets('MixinStakingPoolRewards unit tests', env => { let testContract: TestMixinStakingPoolRewardsContract; - let txHelper: TransactionHelper; const POOL_ID = hexRandom(); const OPERATOR = randomAddress(); @@ -34,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( @@ -47,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. @@ -67,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; } @@ -82,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; } @@ -118,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 }], @@ -135,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 () => { @@ -168,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), @@ -197,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); @@ -206,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 () => { @@ -238,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(); @@ -264,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( @@ -315,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); @@ -347,17 +355,17 @@ 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( + const [result, receipt] = await transactionHelper.getResultAndReceiptAsync( testContract.syncPoolRewards, POOL_ID, new BigNumber(reward), @@ -382,7 +390,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 () => { @@ -390,7 +398,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 () => { @@ -415,10 +423,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), @@ -435,11 +445,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); }); @@ -447,11 +455,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); }); @@ -459,11 +465,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); }); @@ -471,11 +475,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); }); @@ -483,11 +485,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 e49a46a141..59dfad4571 100644 --- a/contracts/staking/test/unit_tests/params_test.ts +++ b/contracts/staking/test/unit_tests/params_test.ts @@ -21,7 +21,7 @@ blockchainTests('Configurable Parameters unit tests', env => { env.txDefaults, artifacts, ); - await testContract.addAuthorizedAddress.awaitTransactionSuccessAsync(authorizedAddress); + await testContract.addAuthorizedAddress(authorizedAddress).awaitTransactionSuccessAsync(); }); blockchainTests.resets('setParams()', () => { @@ -33,14 +33,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); @@ -51,7 +52,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); @@ -67,7 +68,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 1c027fad3a..a80b9f110e 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 019a4487b1..8c5d6cd930 100644 --- a/contracts/staking/test/unit_tests/stake_balances_test.ts +++ b/contracts/staking/test/unit_tests/stake_balances_test.ts @@ -59,11 +59,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 () => { @@ -72,12 +71,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)); }); @@ -86,8 +85,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, @@ -99,7 +98,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(); }); }); @@ -111,40 +110,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)); }); }); @@ -155,16 +150,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); }); }); @@ -177,25 +172,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)); }); }); @@ -206,16 +199,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 76e5dd5d47..080d0c71ef 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 fef82105fb..88f31a4d9c 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,32 +159,32 @@ 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('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( @@ -201,7 +201,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( @@ -220,32 +220,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 equal to current', async () => { const { poolId, operatorShare } = await createPoolAsync(); - const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync( - poolId, - operatorShare, - { from: operator }, - ); + const tx = testContract + .decreaseStakingPoolOperatorShare(poolId, operatorShare) + .awaitTransactionSuccessAsync({ from: operator }); const expectedError = new StakingRevertErrors.OperatorShareError( StakingRevertErrors.OperatorShareErrorCodes.CanOnlyDecreaseOperatorShare, poolId, @@ -255,11 +249,9 @@ blockchainTests.resets('MixinStakingPool unit tests', env => { }); 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 +261,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,31 +273,25 @@ 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', 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, [ @@ -325,36 +309,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 825ed7f2bb..d5333286de 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 6c2209ce44..3b4a54aba6 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 11fba1b467..922422446e 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 e16f12c323..fedba50527 100644 --- a/contracts/staking/test/utils/cumulative_reward_tracking_simulation.ts +++ b/contracts/staking/test/utils/cumulative_reward_tracking_simulation.ts @@ -73,9 +73,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, @@ -99,9 +99,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); } @@ -117,41 +117,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/package.json b/contracts/test-utils/package.json index c629416b19..d1410397eb 100644 --- a/contracts/test-utils/package.json +++ b/contracts/test-utils/package.json @@ -40,6 +40,7 @@ "typescript": "3.0.1" }, "dependencies": { + "@0x/base-contract": "^5.5.0-beta.0", "@0x/dev-utils": "^2.4.0-beta.0", "@0x/order-utils": "^8.5.0-beta.0", "@0x/sol-compiler": "^3.2.0-beta.0", diff --git a/contracts/test-utils/src/index.ts b/contracts/test-utils/src/index.ts index 063859363d..ec7c8afc30 100644 --- a/contracts/test-utils/src/index.ts +++ b/contracts/test-utils/src/index.ts @@ -26,7 +26,7 @@ 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 { 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 index e861e389f7..b76e625588 100644 --- a/contracts/test-utils/src/transaction_helper.ts +++ b/contracts/test-utils/src/transaction_helper.ts @@ -1,56 +1,21 @@ -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; -} +import { ContractTxFunctionObj } from '@0x/base-contract'; +import { TransactionReceiptWithDecodedLogs } from 'ethereum-types'; +export type MutatorContractFunction = (...args: any[]) => ContractTxFunctionObj; /** * 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]> { +export const transactionHelper = { + async getResultAndReceiptAsync( + contractFunction: MutatorContractFunction, + ...args: any[] // tslint:disable-line:trailing-comma + ): Promise<[O, TransactionReceiptWithDecodedLogs]> { // 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), - ); + const contractFunctionObj = contractFunction(...args); + const result = await contractFunctionObj.callAsync(); + const receipt = await contractFunctionObj.awaitTransactionSuccessAsync(); 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 9fe5ee13d6..f0cbeb08fb 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 05f5ea8da5..aca3010448 100644 --- a/contracts/tests/test/dev-utils/order_validation_utils.ts +++ b/contracts/tests/test/dev-utils/order_validation_utils.ts @@ -97,8 +97,8 @@ describe('OrderValidationUtils/OrderTransferSimulatorUtils', () => { await exchangeWrapper.registerAssetProxyAsync(erc20Proxy.address, owner); await exchangeWrapper.registerAssetProxyAsync(erc721Proxy.address, owner); await exchangeWrapper.registerAssetProxyAsync(multiAssetProxy.address, owner); - await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); - await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner }); + await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); + await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner }); devUtils = await DevUtilsContract.deployFrom0xArtifactAsync( artifacts.DevUtils, @@ -108,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, @@ -138,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); }); }); @@ -188,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 () => { @@ -352,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), ); @@ -417,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); @@ -436,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); @@ -472,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 b2a1a46876..8d11c67f4f 100644 --- a/contracts/utils/test/authorizable.ts +++ b/contracts/utils/test/authorizable.ts @@ -46,68 +46,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); @@ -116,7 +116,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); @@ -125,37 +125,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 a538e610c0..41a270befc 100644 --- a/contracts/utils/test/lib_address.ts +++ b/contracts/utils/test/lib_address.ts @@ -30,12 +30,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 5f74cc3659..25923aa4aa 100644 --- a/contracts/utils/test/lib_address_array.ts +++ b/contracts/utils/test/lib_address_array.ts @@ -30,7 +30,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); }); @@ -39,7 +39,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); }); @@ -52,7 +52,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 () => { @@ -60,11 +60,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); }); @@ -74,11 +72,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); @@ -89,27 +85,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); }); }); @@ -117,14 +113,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); }); @@ -132,14 +128,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 541ea43dff..90cec2d1ec 100644 --- a/contracts/utils/test/lib_bytes.ts +++ b/contracts/utils/test/lib_bytes.ts @@ -59,17 +59,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); @@ -78,51 +78,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(); }); }); @@ -132,7 +126,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 () => { @@ -141,7 +135,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 () => { @@ -152,7 +146,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; @@ -162,7 +156,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); }); }); @@ -170,11 +164,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 () => { @@ -183,11 +175,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)); @@ -202,7 +192,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 () => { @@ -213,7 +203,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, ); }); @@ -222,7 +212,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 () => { @@ -231,7 +221,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 () => { @@ -242,7 +232,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, ); }); @@ -253,7 +243,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); }); }); @@ -261,11 +251,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 () => { @@ -274,11 +262,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)); @@ -293,7 +279,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 () => { @@ -304,7 +290,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, ); }); @@ -316,7 +302,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 () => { @@ -326,7 +312,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 () => { @@ -337,7 +323,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, ); }); @@ -351,7 +337,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); }); }); @@ -359,11 +345,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); }); @@ -373,11 +357,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( @@ -395,7 +377,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 () => { @@ -406,7 +388,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, ); }); @@ -423,18 +405,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 () => { @@ -443,7 +427,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 () => { @@ -454,7 +438,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); }); }); @@ -476,12 +460,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); }), @@ -633,14 +614,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); }); @@ -648,7 +629,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); }); @@ -661,14 +642,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); @@ -677,7 +658,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); }); @@ -692,21 +673,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 () => { @@ -719,13 +700,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); }); @@ -733,37 +714,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, @@ -777,35 +752,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 34c46eedbb..41fcd134e5 100644 --- a/contracts/utils/test/lib_eip712.ts +++ b/contracts/utils/test/lib_eip712.ts @@ -44,12 +44,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)); } @@ -83,7 +80,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 3e796ca119..3342c08d8a 100644 --- a/contracts/utils/test/lib_rich_errors.ts +++ b/contracts/utils/test/lib_rich_errors.ts @@ -20,7 +20,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); @@ -32,7 +32,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 39e1ae5d1a..ab68ea67e8 100644 --- a/contracts/utils/test/lib_safe_math.ts +++ b/contracts/utils/test/lib_safe_math.ts @@ -28,17 +28,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); }); @@ -50,11 +50,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)); }); }); @@ -64,27 +64,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); }); @@ -96,7 +96,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); }); }); @@ -105,7 +105,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); }); @@ -117,16 +117,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)); }); }); @@ -136,7 +136,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); }); @@ -148,55 +148,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 13d9d14971..507a0c5459 100644 --- a/contracts/utils/test/log_decoding.ts +++ b/contracts/utils/test/log_decoding.ts @@ -48,19 +48,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); @@ -68,13 +74,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( @@ -82,7 +90,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 d4859f730f..e21a7ae82b 100644 --- a/contracts/utils/test/ownable.ts +++ b/contracts/utils/test/ownable.ts @@ -23,11 +23,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(); }); }); @@ -35,12 +35,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); @@ -51,7 +51,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 9018e6f4c0..c816bf550d 100644 --- a/contracts/utils/test/reentrancy_guard.ts +++ b/contracts/utils/test/reentrancy_guard.ts @@ -31,11 +31,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 8411716231..d474f139d2 100644 --- a/contracts/utils/test/refundable.ts +++ b/contracts/utils/test/refundable.ts @@ -35,14 +35,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, }); }); @@ -53,7 +53,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, }); }); @@ -61,19 +61,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), }); }); @@ -84,7 +84,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, }); }); @@ -92,47 +92,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/asset-buyer/src/asset_buyer.ts b/packages/asset-buyer/src/asset_buyer.ts index 55f972bcd4..953a254228 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/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 a5f43d8350..65e24e3d9f 100644 --- a/packages/asset-swapper/src/swap_quoter.ts +++ b/packages/asset-swapper/src/swap_quoter.ts @@ -216,8 +216,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, @@ -246,8 +250,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, @@ -374,10 +382,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), @@ -397,9 +404,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 4b6621487e..6de57242e7 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 11cc89af3c..d7682ebbd8 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..9252e014fc 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({ value: etherInWei, from: takerAddress }).sendTransactionAsync(); 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({ value: etherInWei, from: takerAddress }).sendTransactionAsync(); const extensionContractType = await swapQuoteConsumer.getOptimalExtensionContractTypeAsync( largeForwarderSwapQuote, { takerAddress }, diff --git a/packages/contract-wrappers/src/coordinator_wrapper.ts b/packages/contract-wrappers/src/coordinator_wrapper.ts index 40250ba9cb..d95cf0f65e 100644 --- a/packages/contract-wrappers/src/coordinator_wrapper.ts +++ b/packages/contract-wrappers/src/coordinator_wrapper.ts @@ -543,13 +543,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,7 +563,7 @@ 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; } @@ -665,7 +667,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 +746,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 e3576f9f49..743d3b46e2 100644 --- a/packages/contract-wrappers/src/index.ts +++ b/packages/contract-wrappers/src/index.ts @@ -154,8 +154,6 @@ export { SignedZeroExTransaction, SimpleEvmOutput, SimpleEvmBytecodeOutput, - AwaitTransactionSuccessOpts, - SendTransactionOpts, EIP712DomainWithDefaultSchema, EventCallback, DecodedLogEvent, @@ -163,3 +161,4 @@ export { } from '@0x/types'; export { AbiDecoder, DecodedCalldata } from '@0x/utils'; +export { AwaitTransactionSuccessOpts, SendTransactionOpts } from '@0x/base-contract'; diff --git a/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts b/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts index 79ebd8833b..cb6e5f460e 100644 --- a/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts +++ b/packages/contract-wrappers/src/utils/getAbiEncodedTransactionData.ts @@ -16,7 +16,7 @@ export function getAbiEncodedTransactionData( getABIEncodedTransactionData: (...args: any[]) => string; }; if (method.getABIEncodedTransactionData) { - const abiEncodedData = method.getABIEncodedTransactionData(...params); + const abiEncodedData = method(...params).getABIEncodedTransactionData(); 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..b8d1e7808d 100644 --- a/packages/contract-wrappers/test/calldata_decoder_test.ts +++ b/packages/contract-wrappers/test/calldata_decoder_test.ts @@ -56,48 +56,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), 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 87982e0086..7bd22f948f 100644 --- a/packages/migrations/src/migration.ts +++ b/packages/migrations/src/migration.ts @@ -143,26 +143,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 wrappers.ForwarderContract.deployFrom0xArtifactAsync( @@ -217,16 +217,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 @@ -237,9 +237,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 wrappers.CoordinatorRegistryContract.deployFrom0xArtifactAsync( diff --git a/packages/migrations/src/test_contract_configs.ts b/packages/migrations/src/test_contract_configs.ts index 9c56e584b7..fcaa16e6c6 100644 --- a/packages/migrations/src/test_contract_configs.ts +++ b/packages/migrations/src/test_contract_configs.ts @@ -45,30 +45,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, @@ -77,158 +77,164 @@ 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 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, @@ -237,33 +243,33 @@ 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 Staking contract'); - const wethAddress = await stakingContract.getWethContract.callAsync(); + const wethAddress = await stakingContract.getWethContract().callAsync(); warnIfMismatch(wethAddress, addresses.etherToken, 'Unexpected WETH contract set in Staking contract'); - const stakingProxyOwner = await stakingProxy.owner.callAsync(); + const stakingProxyOwner = await stakingProxy.owner().callAsync(); warnIfMismatch(stakingProxyOwner, addresses.zeroExGovernor, 'Unexpected StakingProxy owner'); - const zrxVaultOwner = await zrxVault.owner.callAsync(); + const zrxVaultOwner = await zrxVault.owner().callAsync(); warnIfMismatch(zrxVaultOwner, addresses.zeroExGovernor, 'Unexpected ZrxVault 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 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'); } diff --git a/packages/migrations/src/testnet_migrations.ts b/packages/migrations/src/testnet_migrations.ts index e5bf90c959..341fe02e35 100644 --- a/packages/migrations/src/testnet_migrations.ts +++ b/packages/migrations/src/testnet_migrations.ts @@ -27,15 +27,13 @@ async function submitAndExecuteTransactionAsync( destination: string, data: string, ): Promise { - const txReceipt = await governor.submitTransaction.awaitTransactionSuccessAsync( - destination, - constants.ZERO_AMOUNT, - data, - ); + const txReceipt = 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; logUtils.log(`${txId} submitted`); - await governor.executeTransaction.awaitTransactionSuccessAsync(txId); + await governor.executeTransaction(txId).awaitTransactionSuccessAsync(); logUtils.log(`${txId} executed`); } @@ -100,7 +98,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(); await ForwarderContract.deployFrom0xArtifactAsync( forwarderArtifacts.Forwarder, provider, @@ -117,150 +115,150 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t // 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: erc20BridgeProxy.address, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, }, { destination: erc20BridgeProxy.address, - 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, }, { destination: deployedAddresses.zrxVault, - functionSelector: zrxVault.setStakingProxy.getSelector(), + functionSelector: zrxVault.getSelector('setStakingProxy'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.zrxVault, - functionSelector: zrxVault.setZrxProxy.getSelector(), + functionSelector: zrxVault.getSelector('setZrxProxy'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.zrxVault, - functionSelector: ownableInterface.transferOwnership.getSelector(), + functionSelector: ownableInterface.getSelector('transferOwnership'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.zrxVault, - functionSelector: authorizableInterface.addAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('addAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.zrxVault, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.zrxVault, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, // StakingProxy timelocks { destination: deployedAddresses.stakingProxy, - functionSelector: stakingProxy.attachStakingContract.getSelector(), + functionSelector: stakingProxy.getSelector('attachStakingContract'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingProxy.detachStakingContract.getSelector(), + functionSelector: stakingProxy.getSelector('detachStakingContract'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingLogic.setParams.getSelector(), + functionSelector: stakingLogic.getSelector('setParams'), secondsTimeLocked: constants.ZERO_AMOUNT, // 10 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingLogic.addExchangeAddress.getSelector(), + functionSelector: stakingLogic.getSelector('addExchangeAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: stakingLogic.removeExchangeAddress.getSelector(), + functionSelector: stakingLogic.getSelector('removeExchangeAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: ownableInterface.transferOwnership.getSelector(), + functionSelector: ownableInterface.getSelector('transferOwnership'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: authorizableInterface.addAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('addAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: authorizableInterface.removeAuthorizedAddress.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: deployedAddresses.stakingProxy, - functionSelector: authorizableInterface.removeAuthorizedAddressAtIndex.getSelector(), + functionSelector: authorizableInterface.getSelector('removeAuthorizedAddressAtIndex'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, // Exchange timelocks { destination: exchange.address, - functionSelector: exchange.setProtocolFeeMultiplier.getSelector(), + functionSelector: exchange.getSelector('setProtocolFeeMultiplier'), secondsTimeLocked: constants.ZERO_AMOUNT, // 10 days on mainnet }, { destination: exchange.address, - functionSelector: exchange.setProtocolFeeCollectorAddress.getSelector(), + functionSelector: exchange.getSelector('setProtocolFeeCollectorAddress'), secondsTimeLocked: constants.ZERO_AMOUNT, // 20 days on mainnet }, { destination: exchange.address, - functionSelector: exchange.detachProtocolFeeCollector.getSelector(), + functionSelector: exchange.getSelector('detachProtocolFeeCollector'), secondsTimeLocked: constants.ZERO_AMOUNT, }, ]; @@ -279,19 +277,19 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t ); logUtils.log('Configuring Exchange...'); - await exchange.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await exchange.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('Exchange configured!'); logUtils.log('Configuring ERC20BridgeProxy...'); - await erc20BridgeProxy.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await erc20BridgeProxy.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('ERC20BridgeProxy configured!'); logUtils.log('Configuring ZrxVault...'); - await zrxVault.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await zrxVault.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('ZrxVault configured!'); logUtils.log('Configuring StakingProxy...'); - await stakingProxy.transferOwnership.awaitTransactionSuccessAsync(governor.address); + await stakingProxy.transferOwnership(governor.address).awaitTransactionSuccessAsync(); logUtils.log('StakingProxy configured!'); logUtils.log('Transfering ownership of 2.0 contracts...'); @@ -299,27 +297,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!'); @@ -327,89 +325,89 @@ export async function runMigrationsAsync(supportedProvider: SupportedProvider, t // Exchange staking configs { destination: exchange.address, - data: exchange.setProtocolFeeCollectorAddress.getABIEncodedTransactionData(stakingProxy.address), + data: exchange.setProtocolFeeCollectorAddress(stakingProxy.address).getABIEncodedTransactionData(), }, { destination: exchange.address, - data: exchange.setProtocolFeeMultiplier.getABIEncodedTransactionData(new BigNumber(150000)), + data: exchange.setProtocolFeeMultiplier(new BigNumber(150000)).getABIEncodedTransactionData(), }, // Exchange AssetProxy registrations { destination: exchange.address, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(deployedAddresses.erc20Proxy), + data: exchange.registerAssetProxy(deployedAddresses.erc20Proxy).getABIEncodedTransactionData(), }, { destination: exchange.address, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(deployedAddresses.erc721Proxy), + data: exchange.registerAssetProxy(deployedAddresses.erc721Proxy).getABIEncodedTransactionData(), }, { destination: exchange.address, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(deployedAddresses.erc1155Proxy), + data: exchange.registerAssetProxy(deployedAddresses.erc1155Proxy).getABIEncodedTransactionData(), }, { destination: exchange.address, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(deployedAddresses.multiAssetProxy), + data: exchange.registerAssetProxy(deployedAddresses.multiAssetProxy).getABIEncodedTransactionData(), }, { destination: exchange.address, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(deployedAddresses.staticCallProxy), + data: exchange.registerAssetProxy(deployedAddresses.staticCallProxy).getABIEncodedTransactionData(), }, { destination: exchange.address, - data: exchange.registerAssetProxy.getABIEncodedTransactionData(erc20BridgeProxy.address), + data: exchange.registerAssetProxy(erc20BridgeProxy.address).getABIEncodedTransactionData(), }, // ZrxVault configs { destination: zrxVault.address, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(governor.address), + data: authorizableInterface.addAuthorizedAddress(governor.address).getABIEncodedTransactionData(), }, { destination: zrxVault.address, - data: zrxVault.setStakingProxy.getABIEncodedTransactionData(stakingProxy.address), + data: zrxVault.setStakingProxy(stakingProxy.address).getABIEncodedTransactionData(), }, // StakingProxy configs { destination: stakingProxy.address, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(governor.address), + data: authorizableInterface.addAuthorizedAddress(governor.address).getABIEncodedTransactionData(), }, { destination: stakingProxy.address, - data: stakingLogic.addExchangeAddress.getABIEncodedTransactionData(exchange.address), + data: stakingLogic.addExchangeAddress(exchange.address).getABIEncodedTransactionData(), }, // 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(), }, { destination: erc20BridgeProxy.address, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData(exchange.address), + data: authorizableInterface.addAuthorizedAddress(exchange.address).getABIEncodedTransactionData(), }, { destination: erc20BridgeProxy.address, - data: authorizableInterface.addAuthorizedAddress.getABIEncodedTransactionData( - deployedAddresses.multiAssetProxy, - ), + data: authorizableInterface + .addAuthorizedAddress(deployedAddresses.multiAssetProxy) + .getABIEncodedTransactionData(), }, ]; diff --git a/packages/order-utils/src/asset_balance_and_proxy_allowance_fetcher.ts b/packages/order-utils/src/asset_balance_and_proxy_allowance_fetcher.ts index 1cef5d3c73..0745747bb6 100644 --- a/packages/order-utils/src/asset_balance_and_proxy_allowance_fetcher.ts +++ b/packages/order-utils/src/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/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/order-utils/test/exchange_transfer_simulator_test.ts b/packages/order-utils/test/exchange_transfer_simulator_test.ts index 1d64401482..1c06828375 100644 --- a/packages/order-utils/test/exchange_transfer_simulator_test.ts +++ b/packages/order-utils/test/exchange_transfer_simulator_test.ts @@ -72,7 +72,7 @@ describe('ExchangeTransferSimulator', async () => { totalSupply, ); - exampleAssetData = await devUtils.encodeERC20AssetData.callAsync(dummyERC20Token.address); + exampleAssetData = await devUtils.encodeERC20AssetData(dummyERC20Token.address).callAsync(); }); beforeEach(async () => { await blockchainLifecycle.startAsync(); @@ -110,7 +110,7 @@ describe('ExchangeTransferSimulator', async () => { ).to.be.rejectedWith(ExchangeContractErrs.InsufficientTakerAllowance); }); it("throws if the user doesn't have enough balance", async () => { - txHash = await dummyERC20Token.approve.sendTransactionAsync(erc20ProxyAddress, transferAmount, { + txHash = await dummyERC20Token.approve(erc20ProxyAddress, transferAmount).sendTransactionAsync({ from: sender, }); await web3Wrapper.awaitTransactionSuccessAsync(txHash); @@ -126,12 +126,12 @@ describe('ExchangeTransferSimulator', async () => { ).to.be.rejectedWith(ExchangeContractErrs.InsufficientMakerBalance); }); it('updates balances and proxyAllowance after transfer', async () => { - txHash = await dummyERC20Token.transfer.sendTransactionAsync(sender, transferAmount, { + txHash = await dummyERC20Token.transfer(sender, transferAmount).sendTransactionAsync({ from: coinbase, }); await web3Wrapper.awaitTransactionSuccessAsync(txHash); - txHash = await dummyERC20Token.approve.sendTransactionAsync(erc20ProxyAddress, transferAmount, { + txHash = await dummyERC20Token.approve(erc20ProxyAddress, transferAmount).sendTransactionAsync({ from: sender, }); await web3Wrapper.awaitTransactionSuccessAsync(txHash); @@ -153,17 +153,15 @@ describe('ExchangeTransferSimulator', async () => { expect(senderProxyAllowance).to.be.bignumber.equal(0); }); it("doesn't update proxyAllowance after transfer if unlimited", async () => { - txHash = await dummyERC20Token.transfer.sendTransactionAsync(sender, transferAmount, { + txHash = await dummyERC20Token.transfer(sender, transferAmount).sendTransactionAsync({ from: coinbase, }); await web3Wrapper.awaitTransactionSuccessAsync(txHash); - txHash = await dummyERC20Token.approve.sendTransactionAsync( - erc20ProxyAddress, - constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS, - { + txHash = await dummyERC20Token + .approve(erc20ProxyAddress, constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS) + .sendTransactionAsync({ from: sender, - }, - ); + }); await web3Wrapper.awaitTransactionSuccessAsync(txHash); await exchangeTransferSimulator.transferFromAsync( exampleAssetData, diff --git a/packages/order-utils/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts b/packages/order-utils/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts index d3ea8b4567..59f25e9d74 100644 --- a/packages/order-utils/test/utils/simple_erc20_balance_and_proxy_allowance_fetcher.ts +++ b/packages/order-utils/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/packages/testnet-faucets/src/ts/dispense_asset_tasks.ts b/packages/testnet-faucets/src/ts/dispense_asset_tasks.ts index afe1ceb0cc..d10819c4d5 100644 --- a/packages/testnet-faucets/src/ts/dispense_asset_tasks.ts +++ b/packages/testnet-faucets/src/ts/dispense_asset_tasks.ts @@ -48,7 +48,7 @@ export const dispenseAssetTasks = { } const baseUnitAmount = Web3Wrapper.toBaseUnitAmount(amountToDispense, tokenIfExists.decimals); const erc20Token = new ERC20TokenContract(tokenIfExists.address, provider); - const userBalanceBaseUnits = await erc20Token.balanceOf.callAsync(recipientAddress); + const userBalanceBaseUnits = await erc20Token.balanceOf(recipientAddress).callAsync(); const maxAmountBaseUnits = Web3Wrapper.toBaseUnitAmount( new BigNumber(DISPENSE_MAX_AMOUNT_TOKEN), tokenIfExists.decimals, @@ -59,7 +59,7 @@ export const dispenseAssetTasks = { ); return; } - const txHash = await erc20Token.transfer.sendTransactionAsync(recipientAddress, baseUnitAmount, { + const txHash = await erc20Token.transfer(recipientAddress, baseUnitAmount).sendTransactionAsync({ from: configs.DISPENSER_ADDRESS, }); logUtils.log(`Sent ${amountToDispense} ${tokenSymbol} to ${recipientAddress} tx: ${txHash}`);