update abi-gen with new method interfaces (#2325)

* update abi-gen with new method interfaces

* wip: get all packages to build

* wip: get all packages to build

* Fix two contract wrapper calls

* Export necessary types part of the contract wrapper public interfaces

* Revive and fix wrapper_unit_tests

* Remove duplicate type

* Fix lib_exchange_rich_error_decoder tests

* Fix remaining test failures in contracts-* packages

* Prettier fixes

* remove transactionHelper

* lint and update changelogs

* Fix prettier

* Revert changes to reference docs

* Add back changelog already published and add revert changelog entry

* Add missing CHANGELOG entries

* Add missing comma

* Update mesh-rpc-client dep

* Update Mesh RPC logic in @0x/orderbook to v6.0.1-beta

* Align package versions
This commit is contained in:
Xianny 2019-11-14 11:22:29 -05:00 committed by GitHub
parent 9d4d9ce978
commit f0d7d10fe7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
198 changed files with 30021 additions and 38850 deletions

View File

@ -76,7 +76,7 @@ export class ERC1155ProxyWrapper {
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync();
return this._proxyContract;
}
/**
@ -113,19 +113,13 @@ export class ERC1155ProxyWrapper {
this._validateProxyContractExistsOrThrow();
const assetData =
assetData_ === undefined
? await this._devUtils.encodeERC1155AssetData.callAsync(
contractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
? await this._devUtils
.encodeERC1155AssetData(contractAddress, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.callAsync()
: assetData_;
const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData(
assetData,
from,
to,
valueMultiplier,
);
const data = this._assetProxyInterface
.transferFrom(assetData, from, to, valueMultiplier)
.getABIEncodedTransactionData();
return data;
}
/**
@ -173,19 +167,13 @@ export class ERC1155ProxyWrapper {
this._validateProxyContractExistsOrThrow();
const assetData =
assetData_ === undefined
? await this._devUtils.encodeERC1155AssetData.callAsync(
contractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
)
? await this._devUtils
.encodeERC1155AssetData(contractAddress, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.callAsync()
: assetData_;
const data = this._assetProxyInterface.transferFrom.getABIEncodedTransactionData(
assetData,
from,
to,
valueMultiplier,
);
const data = this._assetProxyInterface
.transferFrom(assetData, from, to, valueMultiplier)
.getABIEncodedTransactionData();
const txHash = await this._web3Wrapper.sendTransactionAsync({
to: (this._proxyContract as ERC1155ProxyContract).address,
data,
@ -366,7 +354,7 @@ export class ERC1155ProxyWrapper {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getContractFromAddress(contractAddress);
const operator = (this._proxyContract as ERC1155ProxyContract).address;
const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator);
const didApproveAll = await tokenContract.isApprovedForAll(userAddress, operator).callAsync();
return didApproveAll;
}
public getFungibleTokenIds(): BigNumber[] {

View File

@ -58,7 +58,7 @@ export class ERC20Wrapper {
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync();
return this._proxyContract;
}
public getProxyId(): string {
@ -70,29 +70,25 @@ 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<BigNumber> {
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<void> {
const tokenContract = await this._getTokenContractFromAssetDataAsync(assetData);
await tokenContract.setBalance.awaitTransactionSuccessAsync(
userAddress,
amount,
await tokenContract
.setBalance(userAddress, amount)
.awaitTransactionSuccessAsync(
{ from: this._contractOwnerAddress },
{ pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS },
);
@ -100,13 +96,13 @@ export class ERC20Wrapper {
public async getProxyAllowanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
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<void> {
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<ERC20BalancesByOwner> {
this._validateDummyTokenContractsExistOrThrow();
@ -115,7 +111,7 @@ export class ERC20Wrapper {
const balanceInfo: Array<{ tokenOwnerAddress: string; tokenAddress: string }> = [];
for (const dummyTokenContract of this._dummyTokenContracts) {
for (const tokenOwnerAddress of this._tokenOwnerAddresses) {
balances.push(await dummyTokenContract.balanceOf.callAsync(tokenOwnerAddress));
balances.push(await dummyTokenContract.balanceOf(tokenOwnerAddress).callAsync());
balanceInfo.push({
tokenOwnerAddress,
tokenAddress: dummyTokenContract.address,
@ -149,7 +145,7 @@ export class ERC20Wrapper {
return tokenAddresses;
}
private async _getTokenContractFromAssetDataAsync(assetData: string): Promise<DummyERC20TokenContract> {
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`);

View File

@ -46,7 +46,7 @@ export class ERC721Wrapper {
txDefaults,
artifacts,
);
this._proxyIdIfExists = await this._proxyContract.getProxyId.callAsync();
this._proxyIdIfExists = await this._proxyContract.getProxyId().callAsync();
return this._proxyContract;
}
public getProxyId(): string {
@ -80,7 +80,7 @@ export class ERC721Wrapper {
}
public async doesTokenExistAsync(tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const owner = await tokenContract.ownerOf.callAsync(tokenId);
const owner = await tokenContract.ownerOf(tokenId).callAsync();
const doesExist = owner !== constants.NULL_ADDRESS;
return doesExist;
}
@ -95,14 +95,14 @@ export class ERC721Wrapper {
): Promise<void> {
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<void> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await this.ownerOfAsync(tokenAddress, tokenId);
await tokenContract.approve.awaitTransactionSuccessAsync(to, tokenId, { from: tokenOwner });
await tokenContract.approve(to, tokenId).awaitTransactionSuccessAsync({ from: tokenOwner });
}
public async transferFromAsync(
tokenAddress: string,
@ -111,28 +111,28 @@ export class ERC721Wrapper {
userAddress: string,
): Promise<void> {
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<void> {
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<void> {
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<string> {
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<boolean> {
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const tokenOwner = await tokenContract.ownerOf.callAsync(tokenId);
const tokenOwner = await tokenContract.ownerOf(tokenId).callAsync();
const isOwner = tokenOwner === userAddress;
return isOwner;
}
@ -140,13 +140,13 @@ export class ERC721Wrapper {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const operator = (this._proxyContract as ERC721ProxyContract).address;
const didApproveAll = await tokenContract.isApprovedForAll.callAsync(userAddress, operator);
const didApproveAll = await tokenContract.isApprovedForAll(userAddress, operator).callAsync();
return didApproveAll;
}
public async isProxyApprovedAsync(tokenAddress: string, tokenId: BigNumber): Promise<boolean> {
this._validateProxyContractExistsOrThrow();
const tokenContract = this._getTokenContractFromAssetData(tokenAddress);
const approvedAddress = await tokenContract.getApproved.callAsync(tokenId);
const approvedAddress = await tokenContract.getApproved(tokenId).callAsync();
const proxyAddress = (this._proxyContract as ERC721ProxyContract).address;
const isProxyAnApprovedOperator = approvedAddress === proxyAddress;
return isProxyAnApprovedOperator;
@ -163,7 +163,7 @@ export class ERC721Wrapper {
dummyTokenContract.address
];
for (const tokenId of initialTokenOwnerIds) {
tokenOwnerAddresses.push(await dummyTokenContract.ownerOf.callAsync(tokenId));
tokenOwnerAddresses.push(await dummyTokenContract.ownerOf(tokenId).callAsync());
tokenInfo.push({
tokenId,
tokenAddress: dummyTokenContract.address,

View File

@ -49,21 +49,21 @@ describe('Authorizable', () => {
describe('addAuthorizedAddress', () => {
it('should revert if not called by owner', async () => {
await expectTransactionFailedAsync(
authorizable.addAuthorizedAddress.sendTransactionAsync(notOwner, { from: notOwner }),
authorizable.addAuthorizedAddress(notOwner).sendTransactionAsync({ from: notOwner }),
RevertReason.OnlyContractOwner,
);
});
it('should allow owner to add an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
const isAuthorized = await authorizable.authorized.callAsync(address);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const isAuthorized = await authorizable.authorized(address).callAsync();
expect(isAuthorized).to.be.true();
});
it('should revert if owner attempts to authorize a duplicate address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
return expectTransactionFailedAsync(
authorizable.addAuthorizedAddress.sendTransactionAsync(address, { from: owner }),
authorizable.addAuthorizedAddress(address).sendTransactionAsync({ from: owner }),
RevertReason.TargetAlreadyAuthorized,
);
});
@ -71,23 +71,23 @@ describe('Authorizable', () => {
describe('removeAuthorizedAddress', () => {
it('should revert if not called by owner', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
await expectTransactionFailedAsync(
authorizable.removeAuthorizedAddress.sendTransactionAsync(address, { from: notOwner }),
authorizable.removeAuthorizedAddress(address).sendTransactionAsync({ from: notOwner }),
RevertReason.OnlyContractOwner,
);
});
it('should allow owner to remove an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
const isAuthorized = await authorizable.authorized.callAsync(address);
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const isAuthorized = await authorizable.authorized(address).callAsync();
expect(isAuthorized).to.be.false();
});
it('should revert if owner attempts to remove an address that is not authorized', async () => {
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddress.sendTransactionAsync(address, {
authorizable.removeAuthorizedAddress(address).sendTransactionAsync({
from: owner,
}),
RevertReason.TargetNotAuthorized,
@ -97,10 +97,10 @@ describe('Authorizable', () => {
describe('removeAuthorizedAddressAtIndex', () => {
it('should revert if not called by owner', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const index = new BigNumber(0);
await expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({
from: notOwner,
}),
RevertReason.OnlyContractOwner,
@ -108,10 +108,10 @@ describe('Authorizable', () => {
});
it('should revert if index is >= authorities.length', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const index = new BigNumber(1);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({
from: owner,
}),
RevertReason.IndexOutOfBounds,
@ -121,7 +121,7 @@ describe('Authorizable', () => {
it('should revert if owner attempts to remove an address that is not authorized', async () => {
const index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address, index, {
authorizable.removeAuthorizedAddressAtIndex(address, index).sendTransactionAsync({
from: owner,
}),
RevertReason.TargetNotAuthorized,
@ -131,11 +131,11 @@ describe('Authorizable', () => {
it('should revert if address at index does not match target', async () => {
const address1 = address;
const address2 = notOwner;
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address1, { from: owner });
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address2, { from: owner });
await authorizable.addAuthorizedAddress(address1).awaitTransactionSuccessAsync({ from: owner });
await authorizable.addAuthorizedAddress(address2).awaitTransactionSuccessAsync({ from: owner });
const address1Index = new BigNumber(0);
return expectTransactionFailedAsync(
authorizable.removeAuthorizedAddressAtIndex.sendTransactionAsync(address2, address1Index, {
authorizable.removeAuthorizedAddressAtIndex(address2, address1Index).sendTransactionAsync({
from: owner,
}),
RevertReason.AuthorizedAddressMismatch,
@ -143,26 +143,26 @@ describe('Authorizable', () => {
});
it('should allow owner to remove an authorized address', async () => {
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const index = new BigNumber(0);
await authorizable.removeAuthorizedAddressAtIndex.awaitTransactionSuccessAsync(address, index, {
await authorizable.removeAuthorizedAddressAtIndex(address, index).awaitTransactionSuccessAsync({
from: owner,
});
const isAuthorized = await authorizable.authorized.callAsync(address);
const isAuthorized = await authorizable.authorized(address).callAsync();
expect(isAuthorized).to.be.false();
});
});
describe('getAuthorizedAddresses', () => {
it('should return all authorized addresses', async () => {
const initial = await authorizable.getAuthorizedAddresses.callAsync();
const initial = await authorizable.getAuthorizedAddresses().callAsync();
expect(initial).to.have.length(0);
await authorizable.addAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
const afterAdd = await authorizable.getAuthorizedAddresses.callAsync();
await authorizable.addAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const afterAdd = await authorizable.getAuthorizedAddresses().callAsync();
expect(afterAdd).to.have.length(1);
expect(afterAdd).to.include(address);
await authorizable.removeAuthorizedAddress.awaitTransactionSuccessAsync(address, { from: owner });
const afterRemove = await authorizable.getAuthorizedAddresses.callAsync();
await authorizable.removeAuthorizedAddress(address).awaitTransactionSuccessAsync({ from: owner });
const afterRemove = await authorizable.getAuthorizedAddresses().callAsync();
expect(afterRemove).to.have.length(0);
});
});

View File

@ -77,8 +77,8 @@ describe('ERC1155Proxy', () => {
const usedAddresses = ([owner, notAuthorized, authorized, spender, receiver] = _.slice(accounts, 0, 5));
erc1155ProxyWrapper = new ERC1155ProxyWrapper(provider, usedAddresses, owner);
erc1155Proxy = await erc1155ProxyWrapper.deployProxyAsync();
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner });
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(erc1155Proxy.address, { from: owner });
await erc1155Proxy.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
await erc1155Proxy.addAuthorizedAddress(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: owner });
// deploy & configure ERC1155 tokens and receiver
[erc1155Wrapper] = await erc1155ProxyWrapper.deployDummyContractsAsync();
erc1155Contract = erc1155Wrapper.getContract();
@ -122,7 +122,7 @@ describe('ERC1155Proxy', () => {
);
});
it('should have an id of 0xa7cb5fb7', async () => {
const proxyId = await erc1155Proxy.getProxyId.callAsync();
const proxyId = await erc1155Proxy.getProxyId().callAsync();
const expectedProxyId = AssetProxyId.ERC1155;
expect(proxyId).to.equal(expectedProxyId);
});
@ -637,12 +637,14 @@ describe('ERC1155Proxy', () => {
return value.times(valueMultiplier);
});
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
const extraData = '0102030405060708091001020304050607080910010203040506070809100102';
const assetDataWithExtraData = `${assetData}${extraData}`;
// check balances before transfer
@ -697,14 +699,16 @@ describe('ERC1155Proxy', () => {
// create token
await erc1155Wrapper
.getContract()
.createWithType.awaitTransactionSuccessAsync(tokenToCreate, tokenUri, {
.createWithType(tokenToCreate, tokenUri)
.awaitTransactionSuccessAsync({
from: owner,
});
// mint balance for spender
await erc1155Wrapper
.getContract()
.mintFungible.awaitTransactionSuccessAsync(tokenToCreate, [spender], [spenderInitialBalance], {
.mintFungible(tokenToCreate, [spender], [spenderInitialBalance])
.awaitTransactionSuccessAsync({
from: owner,
});
}
@ -742,7 +746,7 @@ describe('ERC1155Proxy', () => {
// hand encode optimized assetData because our tooling (based on LibAssetData.sol/encodeERC1155AssetData) does not use optimized encoding
const assetDataContract = new IAssetDataContract(constants.NULL_ADDRESS, provider);
const selector = assetDataContract.ERC1155Assets.getSelector();
const selector = assetDataContract.getSelector('ERC1155Assets');
const assetDataWithoutContractAddress =
'0000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000040102030400000000000000000000000000000000000000000000000000000000';
const assetData = `${selector}000000000000000000000000${erc1155ContractAddress.substr(
@ -797,14 +801,16 @@ describe('ERC1155Proxy', () => {
// create token
await erc1155Wrapper
.getContract()
.createWithType.awaitTransactionSuccessAsync(tokenToCreate, tokenUri, {
.createWithType(tokenToCreate, tokenUri)
.awaitTransactionSuccessAsync({
from: owner,
});
// mint balance for spender
await erc1155Wrapper
.getContract()
.mintFungible.awaitTransactionSuccessAsync(tokenToCreate, [spender], [spenderInitialBalance], {
.mintFungible(tokenToCreate, [spender], [spenderInitialBalance])
.awaitTransactionSuccessAsync({
from: owner,
});
}
@ -850,12 +856,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [new BigNumber(2), new BigNumber(2)];
const valueMultiplier = new BigNumber(2);
// create callback data that is the encoded version of `valuesToTransfer`
const generatedAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const generatedAssetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// remove the function selector and contract address from check, as these change on each test
const offsetToTokenIds = 74;
const assetDataSelectorAndContractAddress = generatedAssetData.substr(0, offsetToTokenIds);
@ -922,14 +930,16 @@ describe('ERC1155Proxy', () => {
// create token
await erc1155Wrapper
.getContract()
.createWithType.awaitTransactionSuccessAsync(tokenToCreate, tokenUri, {
.createWithType(tokenToCreate, tokenUri)
.awaitTransactionSuccessAsync({
from: owner,
});
// mint balance for spender
await erc1155Wrapper
.getContract()
.mintFungible.awaitTransactionSuccessAsync(tokenToCreate, [spender], [spenderInitialBalance], {
.mintFungible(tokenToCreate, [spender], [spenderInitialBalance])
.awaitTransactionSuccessAsync({
from: owner,
});
}
@ -972,12 +982,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [new BigNumber(1), new BigNumber(2)];
const valueMultiplier = new BigNumber(2);
// create callback data that is the encoded version of `valuesToTransfer`
const generatedAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const generatedAssetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// remove the function selector and contract address from check, as these change on each test
const offsetToTokenIds = 74;
const assetDataSelectorAndContractAddress = generatedAssetData.substr(0, offsetToTokenIds);
@ -1035,12 +1047,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1082,12 +1096,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1133,12 +1149,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1184,12 +1202,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1235,12 +1255,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1287,12 +1309,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1334,12 +1358,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1385,12 +1411,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1432,12 +1460,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
// The asset data we just generated will look like this:
// a7cb5fb7
// 0x 0000000000000000000000000b1ba0af832d7c05fd64161e0db78e85978e8082
@ -1483,12 +1513,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
const txData = await erc1155ProxyWrapper.getTransferFromAbiEncodedTxDataAsync(
spender,
receiverContract,
@ -1514,12 +1546,14 @@ describe('ERC1155Proxy', () => {
const valuesToTransfer = [fungibleValueToTransferLarge];
const valueMultiplier = valueMultiplierSmall;
const erc1155ContractAddress = erc1155Wrapper.getContract().address;
const assetData = await devUtils.encodeERC1155AssetData.callAsync(
const assetData = await devUtils
.encodeERC1155AssetData(
erc1155ContractAddress,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
const txData = await erc1155ProxyWrapper.getTransferFromAbiEncodedTxDataAsync(
spender,
receiverContract,
@ -1643,7 +1677,7 @@ describe('ERC1155Proxy', () => {
it('should propagate revert reason from erc1155 contract failure', async () => {
// disable transfers
const shouldRejectTransfer = true;
await erc1155Receiver.setRejectTransferFlag.awaitTransactionSuccessAsync(shouldRejectTransfer, {
await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).awaitTransactionSuccessAsync({
from: owner,
});
// setup test parameters

View File

@ -41,8 +41,8 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
env.txDefaults,
artifacts,
);
testTokenAddress = await bridgeContract.testToken.callAsync();
await assetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner);
testTokenAddress = await bridgeContract.testToken().callAsync();
await assetProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync();
});
interface AssetDataOpts {
@ -99,7 +99,7 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
}
async function setTestTokenBalanceAsync(_owner: string, balance: Numberish): Promise<void> {
await bridgeContract.setTestTokenBalance.awaitTransactionSuccessAsync(_owner, new BigNumber(balance));
await bridgeContract.setTestTokenBalance(_owner, new BigNumber(balance)).awaitTransactionSuccessAsync();
}
describe('transferFrom()', () => {
@ -129,13 +129,9 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
async function transferFromAsync(opts?: Partial<TransferFromOpts>, caller?: string): Promise<DecodedLogs> {
const _opts = createTransferFromOpts(opts);
const { logs } = await assetProxy.transferFrom.awaitTransactionSuccessAsync(
encodeAssetData(_opts.assetData),
_opts.from,
_opts.to,
new BigNumber(_opts.amount),
{ from: caller },
);
const { logs } = await assetProxy
.transferFrom(encodeAssetData(_opts.assetData), _opts.from, _opts.to, new BigNumber(_opts.amount))
.awaitTransactionSuccessAsync({ from: caller });
return (logs as any) as DecodedLogs;
}
@ -177,12 +173,9 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
it('fails if asset data is truncated', async () => {
const opts = createTransferFromOpts();
const truncatedAssetData = hexSlice(encodeAssetData(opts.assetData), 0, -1);
const tx = assetProxy.transferFrom.awaitTransactionSuccessAsync(
truncatedAssetData,
opts.from,
opts.to,
new BigNumber(opts.amount),
);
const tx = assetProxy
.transferFrom(truncatedAssetData, opts.from, opts.to, new BigNumber(opts.amount))
.awaitTransactionSuccessAsync();
return expect(tx).to.be.rejected();
});
@ -278,18 +271,18 @@ blockchainTests.resets('ERC20BridgeProxy unit tests', env => {
it('retrieves the balance of the encoded token', async () => {
const _owner = randomAddress();
const balance = getRandomInteger(1, 100e18);
await bridgeContract.setTestTokenBalance.awaitTransactionSuccessAsync(_owner, balance);
await bridgeContract.setTestTokenBalance(_owner, balance).awaitTransactionSuccessAsync();
const assetData = createAssetData({
tokenAddress: testTokenAddress,
});
const actualBalance = await assetProxy.balanceOf.callAsync(encodeAssetData(assetData), _owner);
const actualBalance = await assetProxy.balanceOf(encodeAssetData(assetData), _owner).callAsync();
expect(actualBalance).to.bignumber.eq(balance);
});
});
describe('getProxyId()', () => {
it('returns the correct proxy ID', async () => {
const proxyId = await assetProxy.getProxyId.callAsync();
const proxyId = await assetProxy.getProxyId().callAsync();
expect(proxyId).to.eq(PROXY_ID);
});
});

View File

@ -8,7 +8,6 @@ import {
hexRandom,
Numberish,
randomAddress,
TransactionHelper,
} from '@0x/contracts-test-utils';
import { AssetProxyId } from '@0x/types';
import { BigNumber, RawRevertError } from '@0x/utils';
@ -26,7 +25,6 @@ import {
} from './wrappers';
blockchainTests.resets('Eth2DaiBridge unit tests', env => {
const txHelper = new TransactionHelper(env.web3Wrapper, artifacts);
let testContract: TestEth2DaiBridgeContract;
before(async () => {
@ -41,7 +39,7 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
describe('isValidSignature()', () => {
it('returns success bytes', async () => {
const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381';
const result = await testContract.isValidSignature.callAsync(hexRandom(), hexRandom(_.random(0, 32)));
const result = await testContract.isValidSignature(hexRandom(), hexRandom(_.random(0, 32))).callAsync();
expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE);
});
});
@ -81,32 +79,30 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
async function withdrawToAsync(opts?: Partial<WithdrawToOpts>): Promise<WithdrawToResult> {
const _opts = createWithdrawToOpts(opts);
// Set the fill behavior.
await testContract.setFillBehavior.awaitTransactionSuccessAsync(
_opts.revertReason,
new BigNumber(_opts.fillAmount),
);
await testContract
.setFillBehavior(_opts.revertReason, new BigNumber(_opts.fillAmount))
.awaitTransactionSuccessAsync();
// Create tokens and balances.
if (_opts.fromTokenAddress === undefined) {
[_opts.fromTokenAddress] = await txHelper.getResultAndReceiptAsync(
testContract.createToken,
new BigNumber(_opts.fromTokenBalance),
);
const createTokenFn = testContract.createToken(new BigNumber(_opts.fromTokenBalance));
_opts.fromTokenAddress = await createTokenFn.callAsync();
await createTokenFn.awaitTransactionSuccessAsync();
}
if (_opts.toTokenAddress === undefined) {
[_opts.toTokenAddress] = await txHelper.getResultAndReceiptAsync(
testContract.createToken,
constants.ZERO_AMOUNT,
);
const createTokenFn = testContract.createToken(constants.ZERO_AMOUNT);
_opts.toTokenAddress = await createTokenFn.callAsync();
await createTokenFn.awaitTransactionSuccessAsync();
}
// Set the transfer behavior of `toTokenAddress`.
await testContract.setTransferBehavior.awaitTransactionSuccessAsync(
await testContract
.setTransferBehavior(
_opts.toTokenAddress,
_opts.toTokentransferRevertReason,
_opts.toTokenTransferReturnData,
);
)
.awaitTransactionSuccessAsync();
// Call bridgeTransferFrom().
const [result, { logs }] = await txHelper.getResultAndReceiptAsync(
testContract.bridgeTransferFrom,
const bridgeTransferFromFn = testContract.bridgeTransferFrom(
// "to" token address
_opts.toTokenAddress,
// Random from address.
@ -117,6 +113,8 @@ blockchainTests.resets('Eth2DaiBridge unit tests', env => {
// ABI-encode the "from" token address as the bridge data.
hexLeftPad(_opts.fromTokenAddress as string),
);
const result = await bridgeTransferFromFn.callAsync();
const { logs } = await bridgeTransferFromFn.awaitTransactionSuccessAsync();
return {
opts: _opts,
result,

File diff suppressed because it is too large Load Diff

View File

@ -81,26 +81,21 @@ describe('StaticCallProxy', () => {
);
});
it('should have an id of 0xc339d10a', async () => {
const proxyId = await staticCallProxy.getProxyId.callAsync();
const proxyId = await staticCallProxy.getProxyId().callAsync();
const expectedProxyId = AssetProxyId.StaticCall;
expect(proxyId).to.equal(expectedProxyId);
});
});
describe('transferFrom', () => {
it('should revert if assetData lies outside the bounds of calldata', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const txData = staticCallProxy.transferFrom.getABIEncodedTransactionData(
assetData,
fromAddress,
toAddress,
amount,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
const txData = staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.getABIEncodedTransactionData();
const offsetToAssetData = '0000000000000000000000000000000000000000000000000000000000000080';
const txDataEndBuffer = ethUtil.toBuffer((txData.length - 2) / 2 - 4);
const paddedTxDataEndBuffer = ethUtil.setLengthLeft(txDataEndBuffer, 32);
@ -118,25 +113,21 @@ describe('StaticCallProxy', () => {
it('should revert if the length of assetData is less than 100 bytes', async () => {
const staticCallData = constants.NULL_BYTES;
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = (await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
)).slice(0, -128);
const assetData = (await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync()).slice(0, -128);
const assetDataByteLen = (assetData.length - 2) / 2;
expect((assetDataByteLen - 4) % 32).to.equal(0);
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
);
});
it('should revert if the offset to `staticCallData` points to outside of assetData', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
const offsetToStaticCallData = '0000000000000000000000000000000000000000000000000000000000000060';
const assetDataEndBuffer = ethUtil.toBuffer((assetData.length - 2) / 2 - 4);
const paddedAssetDataEndBuffer = ethUtil.setLengthLeft(assetDataEndBuffer, 32);
@ -147,94 +138,88 @@ describe('StaticCallProxy', () => {
invalidOffsetToStaticCallData,
)}${newStaticCallData}`;
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(badAssetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(badAssetData, fromAddress, toAddress, amount).sendTransactionAsync(),
);
});
it('should revert if the callTarget attempts to write to state', async () => {
const staticCallData = staticCallTarget.updateState.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.updateState().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await expectTransactionFailedWithoutReasonAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
);
});
it('should revert with data provided by the callTarget if the staticcall reverts', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1));
const staticCallData = staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await expectTransactionFailedAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
RevertReason.TargetNotEven,
);
});
it('should revert if the hash of the output is different than expected expected', async () => {
const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(0));
const staticCallData = staticCallTarget.isOddNumber(new BigNumber(0)).getABIEncodedTransactionData();
const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001');
const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer));
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await expectTransactionFailedAsync(
staticCallProxy.transferFrom.sendTransactionAsync(assetData, fromAddress, toAddress, amount),
staticCallProxy.transferFrom(assetData, fromAddress, toAddress, amount).sendTransactionAsync(),
RevertReason.UnexpectedStaticCallResult,
);
});
it('should be successful if a function call with no inputs and no outputs is successful', async () => {
const staticCallData = staticCallTarget.noInputFunction.getABIEncodedTransactionData();
const staticCallData = staticCallTarget.noInputFunction().getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if the staticCallTarget is not a contract and no return value is expected', async () => {
const staticCallData = '0x0102030405060708';
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
toAddress,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(toAddress, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if a function call with one static input returns the correct value', async () => {
const staticCallData = staticCallTarget.isOddNumber.getABIEncodedTransactionData(new BigNumber(1));
const staticCallData = staticCallTarget.isOddNumber(new BigNumber(1)).getABIEncodedTransactionData();
const trueAsBuffer = ethUtil.toBuffer('0x0000000000000000000000000000000000000000000000000000000000000001');
const expectedResultHash = ethUtil.bufferToHex(ethUtil.sha3(trueAsBuffer));
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if a function with one dynamic input is successful', async () => {
const dynamicInput = '0x0102030405060708';
const staticCallData = staticCallTarget.dynamicInputFunction.getABIEncodedTransactionData(dynamicInput);
const staticCallData = staticCallTarget.dynamicInputFunction(dynamicInput).getABIEncodedTransactionData();
const expectedResultHash = constants.KECCAK256_NULL;
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
it('should be successful if a function call returns a complex type', async () => {
const a = new BigNumber(1);
const b = new BigNumber(2);
const staticCallData = staticCallTarget.returnComplexType.getABIEncodedTransactionData(a, b);
const staticCallData = staticCallTarget.returnComplexType(a, b).getABIEncodedTransactionData();
const abiEncoder = new AbiEncoder.DynamicBytes({
name: '',
type: 'bytes',
@ -247,12 +232,12 @@ describe('StaticCallProxy', () => {
const expectedResultHash = ethUtil.bufferToHex(
ethUtil.sha3(ethUtil.toBuffer(encodedExpectedResultWithOffset)),
);
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
expectedResultHash,
);
await staticCallProxy.transferFrom.awaitTransactionSuccessAsync(assetData, fromAddress, toAddress, amount);
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, expectedResultHash)
.callAsync();
await staticCallProxy
.transferFrom(assetData, fromAddress, toAddress, amount)
.awaitTransactionSuccessAsync();
});
});
});

View File

@ -9,7 +9,6 @@ import {
hexRandom,
Numberish,
randomAddress,
TransactionHelper,
} from '@0x/contracts-test-utils';
import { AssetProxyId } from '@0x/types';
import { BigNumber } from '@0x/utils';
@ -31,7 +30,6 @@ import {
} from './wrappers';
blockchainTests.resets('UniswapBridge unit tests', env => {
const txHelper = new TransactionHelper(env.web3Wrapper, artifacts);
let testContract: TestUniswapBridgeContract;
let wethTokenAddress: string;
@ -42,13 +40,13 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
env.txDefaults,
artifacts,
);
wethTokenAddress = await testContract.wethToken.callAsync();
wethTokenAddress = await testContract.wethToken().callAsync();
});
describe('isValidSignature()', () => {
it('returns success bytes', async () => {
const LEGACY_WALLET_MAGIC_VALUE = '0xb0671381';
const result = await testContract.isValidSignature.callAsync(hexRandom(), hexRandom(_.random(0, 32)));
const result = await testContract.isValidSignature(hexRandom(), hexRandom(_.random(0, 32))).callAsync();
expect(result).to.eq(LEGACY_WALLET_MAGIC_VALUE);
});
});
@ -90,35 +88,35 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
async function withdrawToAsync(opts?: Partial<WithdrawToOpts>): Promise<WithdrawToResult> {
const _opts = createWithdrawToOpts(opts);
const callData = { value: new BigNumber(_opts.exchangeFillAmount) };
// Create the "from" token and exchange.
[[_opts.fromTokenAddress]] = await txHelper.getResultAndReceiptAsync(
testContract.createTokenAndExchange,
const createFromTokenFn = testContract.createTokenAndExchange(
_opts.fromTokenAddress,
_opts.exchangeRevertReason,
{ value: new BigNumber(_opts.exchangeFillAmount) },
);
[_opts.fromTokenAddress] = await createFromTokenFn.callAsync(callData);
await createFromTokenFn.awaitTransactionSuccessAsync(callData);
// Create the "to" token and exchange.
[[_opts.toTokenAddress]] = await txHelper.getResultAndReceiptAsync(
testContract.createTokenAndExchange,
const createToTokenFn = testContract.createTokenAndExchange(
_opts.toTokenAddress,
_opts.exchangeRevertReason,
{ value: new BigNumber(_opts.exchangeFillAmount) },
);
await testContract.setTokenRevertReason.awaitTransactionSuccessAsync(
_opts.toTokenAddress,
_opts.toTokenRevertReason,
);
await testContract.setTokenRevertReason.awaitTransactionSuccessAsync(
_opts.fromTokenAddress,
_opts.fromTokenRevertReason,
);
[_opts.toTokenAddress] = await createToTokenFn.callAsync(callData);
await createToTokenFn.awaitTransactionSuccessAsync(callData);
await testContract
.setTokenRevertReason(_opts.toTokenAddress, _opts.toTokenRevertReason)
.awaitTransactionSuccessAsync();
await testContract
.setTokenRevertReason(_opts.fromTokenAddress, _opts.fromTokenRevertReason)
.awaitTransactionSuccessAsync();
// Set the token balance for the token we're converting from.
await testContract.setTokenBalance.awaitTransactionSuccessAsync(_opts.fromTokenAddress, {
await testContract.setTokenBalance(_opts.fromTokenAddress).awaitTransactionSuccessAsync({
value: new BigNumber(_opts.fromTokenBalance),
});
// Call bridgeTransferFrom().
const [result, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.bridgeTransferFrom,
const bridgeTransferFromFn = testContract.bridgeTransferFrom(
// The "to" token address.
_opts.toTokenAddress,
// The "from" address.
@ -130,6 +128,8 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
// ABI-encoded "from" token address.
hexLeftPad(_opts.fromTokenAddress),
);
const result = await bridgeTransferFromFn.callAsync();
const receipt = await bridgeTransferFromFn.awaitTransactionSuccessAsync();
return {
opts: _opts,
result,
@ -139,7 +139,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
}
async function getExchangeForTokenAsync(tokenAddress: string): Promise<string> {
return testContract.getExchange.callAsync(tokenAddress);
return testContract.getExchange(tokenAddress).callAsync();
}
it('returns magic bytes on success', async () => {
@ -148,11 +148,9 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
});
it('just transfers tokens to `to` if the same tokens are in play', async () => {
const [[tokenAddress]] = await txHelper.getResultAndReceiptAsync(
testContract.createTokenAndExchange,
constants.NULL_ADDRESS,
'',
);
const createTokenFn = await testContract.createTokenAndExchange(constants.NULL_ADDRESS, '');
const [tokenAddress] = await createTokenFn.callAsync();
await createTokenFn.awaitTransactionSuccessAsync();
const { opts, result, logs } = await withdrawToAsync({
fromTokenAddress: tokenAddress,
toTokenAddress: tokenAddress,
@ -204,14 +202,16 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
});
it('fails if "from" token does not exist', async () => {
const tx = testContract.bridgeTransferFrom.awaitTransactionSuccessAsync(
const tx = testContract
.bridgeTransferFrom(
randomAddress(),
randomAddress(),
randomAddress(),
getRandomInteger(1, 1e18),
hexLeftPad(randomAddress()),
);
return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
)
.awaitTransactionSuccessAsync();
return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
});
it('fails if the exchange fails', async () => {
@ -219,7 +219,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
const tx = withdrawToAsync({
exchangeRevertReason: revertReason,
});
return expect(tx).to.revertWith(revertReason);
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
});
@ -276,14 +276,16 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
});
it('fails if "from" token does not exist', async () => {
const tx = testContract.bridgeTransferFrom.awaitTransactionSuccessAsync(
const tx = testContract
.bridgeTransferFrom(
randomAddress(),
randomAddress(),
randomAddress(),
getRandomInteger(1, 1e18),
hexLeftPad(wethTokenAddress),
);
return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
)
.awaitTransactionSuccessAsync();
return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
});
it('fails if `WETH.deposit()` fails', async () => {
@ -292,7 +294,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
toTokenAddress: wethTokenAddress,
toTokenRevertReason: revertReason,
});
return expect(tx).to.revertWith(revertReason);
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
it('fails if the exchange fails', async () => {
@ -301,7 +303,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
toTokenAddress: wethTokenAddress,
exchangeRevertReason: revertReason,
});
return expect(tx).to.revertWith(revertReason);
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
});
@ -334,14 +336,16 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
});
it('fails if "to" token does not exist', async () => {
const tx = testContract.bridgeTransferFrom.awaitTransactionSuccessAsync(
const tx = testContract
.bridgeTransferFrom(
wethTokenAddress,
randomAddress(),
randomAddress(),
getRandomInteger(1, 1e18),
hexLeftPad(randomAddress()),
);
return expect(tx).to.revertWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
)
.awaitTransactionSuccessAsync();
return expect(tx).to.eventually.be.rejectedWith('NO_UNISWAP_EXCHANGE_FOR_TOKEN');
});
it('fails if the `WETH.withdraw()` fails', async () => {
@ -350,7 +354,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
fromTokenAddress: wethTokenAddress,
fromTokenRevertReason: revertReason,
});
return expect(tx).to.revertWith(revertReason);
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
it('fails if the exchange fails', async () => {
@ -359,7 +363,7 @@ blockchainTests.resets('UniswapBridge unit tests', env => {
fromTokenAddress: wethTokenAddress,
exchangeRevertReason: revertReason,
});
return expect(tx).to.revertWith(revertReason);
return expect(tx).to.eventually.be.rejectedWith(revertReason);
});
});
});

View File

@ -25,43 +25,42 @@ blockchainTests.resets('Coordinator Registry tests', env => {
});
describe('core', () => {
it('Should successfully set a Coordinator endpoint', async () => {
await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(coordinatorEndpoint, {
await coordinatorRegistry.setCoordinatorEndpoint(coordinatorEndpoint).awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
const recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync(
coordinatorOperator,
);
const recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint);
});
it('Should successfully unset a Coordinator endpoint', async () => {
// set Coordinator endpoint
await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(coordinatorEndpoint, {
await coordinatorRegistry.setCoordinatorEndpoint(coordinatorEndpoint).awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
let recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync(
coordinatorOperator,
);
let recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint);
// unset Coordinator endpoint
await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(nilCoordinatorEndpoint, {
await coordinatorRegistry.setCoordinatorEndpoint(nilCoordinatorEndpoint).awaitTransactionSuccessAsync({
from: coordinatorOperator,
});
recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync(
coordinatorOperator,
);
recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(nilCoordinatorEndpoint);
});
it('Should emit an event when setting Coordinator endpoint', async () => {
// set Coordinator endpoint
const txReceipt = await coordinatorRegistry.setCoordinatorEndpoint.awaitTransactionSuccessAsync(
coordinatorEndpoint,
{
const txReceipt = await coordinatorRegistry
.setCoordinatorEndpoint(coordinatorEndpoint)
.awaitTransactionSuccessAsync({
from: coordinatorOperator,
},
);
const recordedCoordinatorEndpoint = await coordinatorRegistry.getCoordinatorEndpoint.callAsync(
coordinatorOperator,
);
});
const recordedCoordinatorEndpoint = await coordinatorRegistry
.getCoordinatorEndpoint(coordinatorOperator)
.callAsync();
expect(recordedCoordinatorEndpoint).to.be.equal(coordinatorEndpoint);
// validate event
const expectedEvent: CoordinatorRegistryCoordinatorEndpointSetEventArgs = {

View File

@ -46,7 +46,7 @@ blockchainTests.resets('Libs tests', env => {
transactionSignature: signedTx.signature,
};
const expectedApprovalHash = hashUtils.getApprovalHashHex(signedTx, coordinatorContract.address, txOrigin);
const approvalHash = await coordinatorContract.getCoordinatorApprovalHash.callAsync(approval);
const approvalHash = await coordinatorContract.getCoordinatorApprovalHash(approval).callAsync();
expect(expectedApprovalHash).to.eq(approvalHash);
});
});

View File

@ -75,14 +75,14 @@ blockchainTests.resets('Mixins tests', env => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data }, SignatureType.EthSign);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature);
const signerAddress = await mixins.getSignerAddress(transactionHash, transaction.signature).callAsync();
expect(transaction.signerAddress).to.eq(signerAddress);
});
it('should return the correct address using the EIP712 signature type', async () => {
const data = constants.NULL_BYTES;
const transaction = await transactionFactory.newSignedTransactionAsync({ data }, SignatureType.EIP712);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const signerAddress = await mixins.getSignerAddress.callAsync(transactionHash, transaction.signature);
const signerAddress = await mixins.getSignerAddress(transactionHash, transaction.signature).callAsync();
expect(transaction.signerAddress).to.eq(signerAddress);
});
it('should revert with with the Illegal signature type', async () => {
@ -93,7 +93,7 @@ blockchainTests.resets('Mixins tests', env => {
SignatureType.Illegal,
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith(
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Illegal,
transactionHash,
@ -106,7 +106,7 @@ blockchainTests.resets('Mixins tests', env => {
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
transaction.signature = hexConcat(SignatureType.Invalid);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith(
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Invalid,
transactionHash,
@ -122,7 +122,7 @@ blockchainTests.resets('Mixins tests', env => {
SignatureType.NSignatureTypes,
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith(
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Unsupported,
transactionHash,
@ -138,7 +138,7 @@ blockchainTests.resets('Mixins tests', env => {
SignatureType.Wallet,
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(mixins.getSignerAddress.callAsync(transactionHash, transaction.signature)).to.revertWith(
expect(mixins.getSignerAddress(transactionHash, transaction.signature).callAsync()).to.revertWith(
new CoordinatorRevertErrors.SignatureError(
CoordinatorRevertErrors.SignatureErrorCodes.Unsupported,
transactionHash,
@ -153,7 +153,7 @@ blockchainTests.resets('Mixins tests', env => {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@ -167,7 +167,7 @@ blockchainTests.resets('Mixins tests', env => {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@ -181,7 +181,7 @@ blockchainTests.resets('Mixins tests', env => {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@ -195,7 +195,7 @@ blockchainTests.resets('Mixins tests', env => {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const decodedSignedOrders = decodedOrders.map(order => ({
...order,
signature: constants.NULL_BYTES,
@ -209,14 +209,14 @@ blockchainTests.resets('Mixins tests', env => {
it(`should correctly decode the orders for ${fnName} data`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const emptyArray: any[] = [];
expect(emptyArray).to.deep.eq(decodedOrders);
});
}
it('should decode an empty array for invalid data', async () => {
const data = '0x0123456789';
const decodedOrders = await mixins.decodeOrdersFromFillData.callAsync(data);
const decodedOrders = await mixins.decodeOrdersFromFillData(data).callAsync();
const emptyArray: any[] = [];
expect(emptyArray).to.deep.eq(decodedOrders);
});
@ -227,7 +227,7 @@ blockchainTests.resets('Mixins tests', env => {
new BigNumber(3), // the length of data
new BigNumber(4),
);
return expect(mixins.decodeOrdersFromFillData.callAsync(data)).to.revertWith(expectedError);
return expect(mixins.decodeOrdersFromFillData(data).callAsync()).to.revertWith(expectedError);
});
});
@ -238,13 +238,11 @@ blockchainTests.resets('Mixins tests', env => {
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval.signature],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName}, caller=tx_signer, senderAddress=[null], approval_sig=[approver1]`, async () => {
const order = {
@ -255,54 +253,42 @@ blockchainTests.resets('Mixins tests', env => {
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval.signature],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
{
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [])
.callAsync({
from: approvalSignerAddress1,
},
);
});
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approval.signature],
{ from: approvalSignerAddress1 },
);
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [
approval.signature,
])
.callAsync({ from: approvalSignerAddress1 });
});
it(`Should be successful: function=${fnName}, caller=approver1, senderAddress=[verifier], approval_sig=[]`, async () => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
{
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [])
.callAsync({
from: approvalSignerAddress1,
},
);
});
});
it(`Should revert: function=${fnName}, caller=tx_signer, senderAddress=[verifier], approval_sig=[invalid]`, async () => {
const orders = [defaultOrder];
@ -314,13 +300,11 @@ blockchainTests.resets('Mixins tests', env => {
'0xFFFFFFFF',
hexSlice(approval.signature, 6),
);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[signature],
{ from: transactionSignerAddress },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
signature,
])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
@ -333,13 +317,11 @@ blockchainTests.resets('Mixins tests', env => {
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval.signature],
{ from: approvalSignerAddress2 },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: approvalSignerAddress2 });
expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress));
});
}
@ -355,13 +337,11 @@ blockchainTests.resets('Mixins tests', env => {
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval.signature],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder, defaultOrder].map(order => ({
@ -371,13 +351,11 @@ blockchainTests.resets('Mixins tests', env => {
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval.signature],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[null,null], feeRecipient=[approver1,approver1], approval_sig=[]`, async () => {
const orders = [defaultOrder, defaultOrder].map(order => ({
@ -386,26 +364,20 @@ blockchainTests.resets('Mixins tests', env => {
}));
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,null], feeRecipient=[approver1,approver1], approval_sig=[approver1]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, senderAddress: constants.NULL_ADDRESS }];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval.signature],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver1,approver2]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
@ -413,25 +385,20 @@ blockchainTests.resets('Mixins tests', env => {
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval1 = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
const approval2 = approvalFactory2.newSignedApproval(transaction, transactionSignerAddress);
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval1.signature, approval2.signature],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval1.signature,
approval2.signature,
])
.callAsync({ from: transactionSignerAddress });
});
it(`Should be successful: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver1], approval_sig=[]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[],
{ from: approvalSignerAddress1 },
);
await mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [])
.callAsync({ from: approvalSignerAddress1 });
});
it(`Should revert: function=${fnName} caller=approver1, senderAddress=[verifier,verifier], feeRecipient=[approver1,approver2], approval_sig=[approver2]`, async () => {
const orders = [defaultOrder, { ...defaultOrder, feeRecipientAddress: approvalSignerAddress2 }];
@ -439,26 +406,20 @@ blockchainTests.resets('Mixins tests', env => {
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval2 = approvalFactory2.newSignedApproval(transaction, transactionSignerAddress);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval2.signature],
{ from: approvalSignerAddress1 },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval2.signature,
])
.callAsync({ from: approvalSignerAddress1 });
expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress));
});
it(`Should revert: function=${fnName} caller=tx_signer, senderAddress=[verifier,verifier], feeRecipient=[approver1, approver1], approval_sig=[]`, async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(fnName, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
{ from: transactionSignerAddress },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
@ -475,13 +436,11 @@ blockchainTests.resets('Mixins tests', env => {
'0xFFFFFFFF',
hexSlice(approval.signature, 6),
);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[signature],
{ from: transactionSignerAddress },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
signature,
])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
@ -499,13 +458,12 @@ blockchainTests.resets('Mixins tests', env => {
'0xFFFFFFFF',
hexSlice(approval2.signature, 6),
);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval1.signature, approvalSignature2],
{ from: transactionSignerAddress },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval1.signature,
approvalSignature2,
])
.callAsync({ from: transactionSignerAddress });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
@ -522,13 +480,11 @@ blockchainTests.resets('Mixins tests', env => {
'0xFFFFFFFF',
hexSlice(approval2.signature, 6),
);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
approvalSignerAddress1,
transaction.signature,
[approvalSignature2],
{ from: approvalSignerAddress1 },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, approvalSignerAddress1, transaction.signature, [
approvalSignature2,
])
.callAsync({ from: approvalSignerAddress1 });
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
expect(tx).to.revertWith(
@ -541,13 +497,11 @@ blockchainTests.resets('Mixins tests', env => {
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
const approval1 = approvalFactory1.newSignedApproval(transaction, transactionSignerAddress);
const tx = mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[approval1.signature],
{ from: approvalSignerAddress2 },
);
const tx = mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [
approval1.signature,
])
.callAsync({ from: approvalSignerAddress2 });
expect(tx).to.revertWith(new CoordinatorRevertErrors.InvalidOriginError(transactionSignerAddress));
});
}
@ -557,36 +511,24 @@ blockchainTests.resets('Mixins tests', env => {
const orders = [defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrder, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
it('should allow the tx signer to call `batchCancelOrders` without approval', async () => {
const orders = [defaultOrder, defaultOrder];
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.BatchCancelOrders, orders);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
it('should allow the tx signer to call `cancelOrdersUpTo` without approval', async () => {
const data = exchangeDataEncoder.encodeOrdersToExchangeData(ExchangeFunctionName.CancelOrdersUpTo);
const transaction = await transactionFactory.newSignedTransactionAsync({ data });
await mixins.assertValidCoordinatorApprovals.callAsync(
transaction,
transactionSignerAddress,
transaction.signature,
[],
{ from: transactionSignerAddress },
);
await mixins
.assertValidCoordinatorApprovals(transaction, transactionSignerAddress, transaction.signature, [])
.callAsync({ from: transactionSignerAddress });
});
});
});

View File

@ -27,7 +27,7 @@ export class Erc1155Wrapper {
return this._erc1155Contract;
}
public async getBalancesAsync(owners: string[], tokens: BigNumber[]): Promise<BigNumber[]> {
const balances = await this._erc1155Contract.balanceOfBatch.callAsync(owners, tokens);
const balances = await this._erc1155Contract.balanceOfBatch(owners, tokens).callAsync();
return balances;
}
public async safeTransferFromAsync(
@ -41,7 +41,7 @@ export class Erc1155Wrapper {
const spender = delegatedSpender === undefined ? from : delegatedSpender;
const callbackDataHex = callbackData === undefined ? '0x' : callbackData;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.safeTransferFrom.sendTransactionAsync(from, to, token, value, callbackDataHex, {
await this._erc1155Contract.safeTransferFrom(from, to, token, value, callbackDataHex).sendTransactionAsync({
from: spender,
}),
);
@ -58,14 +58,9 @@ export class Erc1155Wrapper {
const spender = delegatedSpender === undefined ? from : delegatedSpender;
const callbackDataHex = callbackData === undefined ? '0x' : callbackData;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
from,
to,
tokens,
values,
callbackDataHex,
{ from: spender },
),
await this._erc1155Contract
.safeBatchTransferFrom(from, to, tokens, values, callbackDataHex)
.sendTransactionAsync({ from: spender }),
);
return tx;
}
@ -76,7 +71,7 @@ export class Erc1155Wrapper {
const tokenUri = 'dummyFungibleToken';
const tokenIsNonFungible = false;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.create.sendTransactionAsync(tokenUri, tokenIsNonFungible, {
await this._erc1155Contract.create(tokenUri, tokenIsNonFungible).sendTransactionAsync({
from: this._contractOwner,
}),
);
@ -97,25 +92,22 @@ export class Erc1155Wrapper {
tokenAmountsAsArray.push(tokenAmounts);
});
}
await this._erc1155Contract.mintFungible.awaitTransactionSuccessAsync(
tokenId,
beneficiaries,
tokenAmountsAsArray,
{ from: this._contractOwner },
);
await this._erc1155Contract
.mintFungible(tokenId, beneficiaries, tokenAmountsAsArray)
.awaitTransactionSuccessAsync({ from: this._contractOwner });
}
public async mintNonFungibleTokensAsync(beneficiaries: string[]): Promise<[BigNumber, BigNumber[]]> {
const tokenUri = 'dummyNonFungibleToken';
const tokenIsNonFungible = true;
const tx = await this._logDecoder.getTxWithDecodedLogsAsync(
await this._erc1155Contract.create.sendTransactionAsync(tokenUri, tokenIsNonFungible, {
await this._erc1155Contract.create(tokenUri, tokenIsNonFungible).sendTransactionAsync({
from: this._contractOwner,
}),
);
// tslint:disable-next-line no-unnecessary-type-assertion
const createFungibleTokenLog = tx.logs[0] as LogWithDecodedArgs<ERC1155TransferSingleEventArgs>;
const token = createFungibleTokenLog.args.id;
await this._erc1155Contract.mintNonFungible.awaitTransactionSuccessAsync(token, beneficiaries, {
await this._erc1155Contract.mintNonFungible(token, beneficiaries).awaitTransactionSuccessAsync({
from: this._contractOwner,
});
const encodedNftIds: BigNumber[] = [];
@ -134,14 +126,14 @@ export class Erc1155Wrapper {
isApproved: boolean,
): Promise<TransactionReceiptWithDecodedLogs> {
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<boolean> {
const isApprovedForAll = await this._erc1155Contract.isApprovedForAll.callAsync(owner, beneficiary);
const isApprovedForAll = await this._erc1155Contract.isApprovedForAll(owner, beneficiary).callAsync();
return isApprovedForAll;
}
public async assertBalancesAsync(
@ -163,18 +155,18 @@ export class Erc1155Wrapper {
});
}
public async isNonFungibleItemAsync(tokenId: BigNumber): Promise<boolean> {
return this._erc1155Contract.isNonFungibleItem.callAsync(tokenId);
return this._erc1155Contract.isNonFungibleItem(tokenId).callAsync();
}
public async isFungibleItemAsync(tokenId: BigNumber): Promise<boolean> {
return !(await this.isNonFungibleItemAsync(tokenId));
}
public async getOwnerOfAsync(tokenId: BigNumber): Promise<string> {
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<BigNumber> {
return this._erc1155Contract.balanceOf.callAsync(ownerAddress, tokenId);
return this._erc1155Contract.balanceOf(ownerAddress, tokenId).callAsync();
}
}

View File

@ -176,14 +176,9 @@ describe('ERC1155Token', () => {
valueToTransfer,
);
// execute transfer
const tx = erc1155Contract.safeTransferFrom.sendTransactionAsync(
spender,
receiver,
tokenToTransfer,
valueToTransfer,
receiverCallbackData,
{ from: spender },
);
const tx = erc1155Contract
.safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender });
return expect(tx).to.revertWith(expectedError);
});
it('should revert if callback reverts', async () => {
@ -193,19 +188,14 @@ describe('ERC1155Token', () => {
// set receiver to reject balances
const shouldRejectTransfer = true;
await web3Wrapper.awaitTransactionSuccessAsync(
await erc1155Receiver.setRejectTransferFlag.sendTransactionAsync(shouldRejectTransfer),
await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeTransferFrom.sendTransactionAsync(
spender,
receiver,
tokenToTransfer,
valueToTransfer,
receiverCallbackData,
{ from: spender },
),
erc1155Contract
.safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender }),
RevertReason.TransferRejected,
);
});
@ -352,14 +342,9 @@ describe('ERC1155Token', () => {
valuesToTransfer[0],
);
// execute transfer
const tx = erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
spender,
receiver,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
{ from: spender },
);
const tx = erc1155Contract
.safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender });
return expect(tx).to.revertWith(expectedError);
});
it('should revert if callback reverts', async () => {
@ -369,19 +354,14 @@ describe('ERC1155Token', () => {
// set receiver to reject balances
const shouldRejectTransfer = true;
await web3Wrapper.awaitTransactionSuccessAsync(
await erc1155Receiver.setRejectTransferFlag.sendTransactionAsync(shouldRejectTransfer),
await erc1155Receiver.setRejectTransferFlag(shouldRejectTransfer).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
spender,
receiver,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
{ from: spender },
),
erc1155Contract
.safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: spender }),
RevertReason.TransferRejected,
);
});
@ -429,14 +409,9 @@ describe('ERC1155Token', () => {
await erc1155Wrapper.assertBalancesAsync(tokenHolders, [tokenToTransfer], expectedInitialBalances);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeTransferFrom.sendTransactionAsync(
spender,
receiver,
tokenToTransfer,
valueToTransfer,
receiverCallbackData,
{ from: delegatedSpender },
),
erc1155Contract
.safeTransferFrom(spender, receiver, tokenToTransfer, valueToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: delegatedSpender }),
RevertReason.InsufficientAllowance,
);
});
@ -482,14 +457,9 @@ describe('ERC1155Token', () => {
await erc1155Wrapper.assertBalancesAsync(tokenHolders, tokensToTransfer, expectedInitialBalances);
// execute transfer
await expectTransactionFailedAsync(
erc1155Contract.safeBatchTransferFrom.sendTransactionAsync(
spender,
receiver,
tokensToTransfer,
valuesToTransfer,
receiverCallbackData,
{ from: delegatedSpender },
),
erc1155Contract
.safeBatchTransferFrom(spender, receiver, tokensToTransfer, valuesToTransfer, receiverCallbackData)
.sendTransactionAsync({ from: delegatedSpender }),
RevertReason.InsufficientAllowance,
);
});

View File

@ -39,13 +39,9 @@ blockchainTests('LibERC20Token', env => {
it('calls the target with the correct arguments', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const { logs } = await testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
spender,
allowance,
);
const { logs } = await testContract
.testApprove(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, spender, allowance)
.awaitTransactionSuccessAsync();
expect(logs).to.be.length(1);
verifyEventsFromLogs(logs, [{ spender, allowance }], TestLibERC20TokenTargetEvents.ApproveCalled);
});
@ -53,37 +49,25 @@ blockchainTests('LibERC20Token', env => {
it('succeeds if the target returns true', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
await testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
spender,
allowance,
);
await testContract
.testApprove(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, spender, allowance)
.awaitTransactionSuccessAsync();
});
it('succeeds if the target returns nothing', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
await testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
constants.NULL_BYTES,
spender,
allowance,
);
await testContract
.testApprove(false, encodeRevert(REVERT_STRING), constants.NULL_BYTES, spender, allowance)
.awaitTransactionSuccessAsync();
});
it('fails if the target returns false', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const tx = testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_FALSE,
spender,
allowance,
);
const tx = testContract
.testApprove(false, encodeRevert(REVERT_STRING), ENCODED_FALSE, spender, allowance)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_FALSE);
return expect(tx).to.revertWith(expectedError);
});
@ -91,13 +75,9 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target returns nonzero and not true', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const tx = testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TWO,
spender,
allowance,
);
const tx = testContract
.testApprove(false, encodeRevert(REVERT_STRING), ENCODED_TWO, spender, allowance)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_TWO);
return expect(tx).to.revertWith(expectedError);
});
@ -105,13 +85,9 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target returns less than 32 bytes', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const tx = testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_SHORT_TRUE,
spender,
allowance,
);
const tx = testContract
.testApprove(false, encodeRevert(REVERT_STRING), ENCODED_SHORT_TRUE, spender, allowance)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_SHORT_TRUE);
return expect(tx).to.revertWith(expectedError);
});
@ -119,13 +95,9 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target returns greater than 32 bytes', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const tx = testContract.testApprove.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_LONG_TRUE,
spender,
allowance,
);
const tx = testContract
.testApprove(false, encodeRevert(REVERT_STRING), ENCODED_LONG_TRUE, spender, allowance)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_LONG_TRUE);
return expect(tx).to.revertWith(expectedError);
});
@ -133,26 +105,18 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target reverts', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const tx = testContract.testApprove.awaitTransactionSuccessAsync(
true,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
spender,
allowance,
);
const tx = testContract
.testApprove(true, encodeRevert(REVERT_STRING), ENCODED_TRUE, spender, allowance)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(REVERT_STRING);
});
it('fails if the target reverts with no data', async () => {
const spender = randomAddress();
const allowance = getRandomInteger(0, 100e18);
const tx = testContract.testApprove.awaitTransactionSuccessAsync(
true,
constants.NULL_BYTES,
ENCODED_TRUE,
spender,
allowance,
);
const tx = testContract
.testApprove(true, constants.NULL_BYTES, ENCODED_TRUE, spender, allowance)
.awaitTransactionSuccessAsync();
return expect(tx).to.be.rejectedWith('revert');
});
});
@ -161,13 +125,9 @@ blockchainTests('LibERC20Token', env => {
it('calls the target with the correct arguments', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
to,
amount,
);
const { logs } = await testContract
.testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, to, amount)
.awaitTransactionSuccessAsync();
expect(logs).to.be.length(1);
verifyEventsFromLogs(logs, [{ to, amount }], TestLibERC20TokenTargetEvents.TransferCalled);
});
@ -175,37 +135,25 @@ blockchainTests('LibERC20Token', env => {
it('succeeds if the target returns true', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
await testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
to,
amount,
);
await testContract
.testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, to, amount)
.awaitTransactionSuccessAsync();
});
it('succeeds if the target returns nothing', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
await testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
constants.NULL_BYTES,
to,
amount,
);
await testContract
.testTransfer(false, encodeRevert(REVERT_STRING), constants.NULL_BYTES, to, amount)
.awaitTransactionSuccessAsync();
});
it('fails if the target returns false', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_FALSE,
to,
amount,
);
const tx = testContract
.testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_FALSE, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_FALSE);
return expect(tx).to.revertWith(expectedError);
});
@ -213,13 +161,9 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target returns nonzero and not true', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TWO,
to,
amount,
);
const tx = testContract
.testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_TWO, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_TWO);
return expect(tx).to.revertWith(expectedError);
});
@ -227,13 +171,9 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target returns less than 32 bytes', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_SHORT_TRUE,
to,
amount,
);
const tx = testContract
.testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_SHORT_TRUE, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_SHORT_TRUE);
return expect(tx).to.revertWith(expectedError);
});
@ -241,13 +181,9 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target returns greater than 32 bytes', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransfer.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_LONG_TRUE,
to,
amount,
);
const tx = testContract
.testTransfer(false, encodeRevert(REVERT_STRING), ENCODED_LONG_TRUE, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_LONG_TRUE);
return expect(tx).to.revertWith(expectedError);
});
@ -255,26 +191,18 @@ blockchainTests('LibERC20Token', env => {
it('fails if the target reverts', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransfer.awaitTransactionSuccessAsync(
true,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
to,
amount,
);
const tx = testContract
.testTransfer(true, encodeRevert(REVERT_STRING), ENCODED_TRUE, to, amount)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(REVERT_STRING);
});
it('fails if the target reverts with no data', async () => {
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransfer.awaitTransactionSuccessAsync(
true,
constants.NULL_BYTES,
ENCODED_TRUE,
to,
amount,
);
const tx = testContract
.testTransfer(true, constants.NULL_BYTES, ENCODED_TRUE, to, amount)
.awaitTransactionSuccessAsync();
return expect(tx).to.be.rejectedWith('revert');
});
});
@ -284,14 +212,9 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
owner,
to,
amount,
);
const { logs } = await testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, owner, to, amount)
.awaitTransactionSuccessAsync();
expect(logs).to.be.length(1);
verifyEventsFromLogs(logs, [{ from: owner, to, amount }], TestLibERC20TokenTargetEvents.TransferFromCalled);
});
@ -300,42 +223,27 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
await testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
owner,
to,
amount,
);
await testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_TRUE, owner, to, amount)
.awaitTransactionSuccessAsync();
});
it('succeeds if the target returns nothing', async () => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
await testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
constants.NULL_BYTES,
owner,
to,
amount,
);
await testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), constants.NULL_BYTES, owner, to, amount)
.awaitTransactionSuccessAsync();
});
it('fails if the target returns false', async () => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_FALSE,
owner,
to,
amount,
);
const tx = testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_FALSE, owner, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_FALSE);
return expect(tx).to.revertWith(expectedError);
});
@ -344,14 +252,9 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_TWO,
owner,
to,
amount,
);
const tx = testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_TWO, owner, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_TWO);
return expect(tx).to.revertWith(expectedError);
});
@ -360,14 +263,9 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_SHORT_TRUE,
owner,
to,
amount,
);
const tx = testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_SHORT_TRUE, owner, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_SHORT_TRUE);
return expect(tx).to.revertWith(expectedError);
});
@ -376,14 +274,9 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync(
false,
encodeRevert(REVERT_STRING),
ENCODED_LONG_TRUE,
owner,
to,
amount,
);
const tx = testContract
.testTransferFrom(false, encodeRevert(REVERT_STRING), ENCODED_LONG_TRUE, owner, to, amount)
.awaitTransactionSuccessAsync();
const expectedError = new RawRevertError(ENCODED_LONG_TRUE);
return expect(tx).to.revertWith(expectedError);
});
@ -392,14 +285,9 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync(
true,
encodeRevert(REVERT_STRING),
ENCODED_TRUE,
owner,
to,
amount,
);
const tx = testContract
.testTransferFrom(true, encodeRevert(REVERT_STRING), ENCODED_TRUE, owner, to, amount)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(REVERT_STRING);
});
@ -407,14 +295,9 @@ blockchainTests('LibERC20Token', env => {
const owner = randomAddress();
const to = randomAddress();
const amount = getRandomInteger(0, 100e18);
const tx = testContract.testTransferFrom.awaitTransactionSuccessAsync(
true,
constants.NULL_BYTES,
ENCODED_TRUE,
owner,
to,
amount,
);
const tx = testContract
.testTransferFrom(true, constants.NULL_BYTES, ENCODED_TRUE, owner, to, amount)
.awaitTransactionSuccessAsync();
return expect(tx).to.be.rejectedWith('revert');
});
});

View File

@ -46,7 +46,7 @@ describe('UnlimitedAllowanceToken', () => {
constants.DUMMY_TOKEN_TOTAL_SUPPLY,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.mint.sendTransactionAsync(MAX_MINT_VALUE, { from: owner }),
await token.mint(MAX_MINT_VALUE).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
@ -58,24 +58,24 @@ describe('UnlimitedAllowanceToken', () => {
});
describe('transfer', () => {
it('should revert if owner has insufficient balance', async () => {
const ownerBalance = await token.balanceOf.callAsync(owner);
const ownerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = ownerBalance.plus(1);
return expectContractCallFailedAsync(
token.transfer.callAsync(spender, amountToTransfer, { from: owner }),
token.transfer(spender, amountToTransfer).callAsync({ from: owner }),
RevertReason.Erc20InsufficientBalance,
);
});
it('should transfer balance from sender to receiver', async () => {
const receiver = spender;
const initOwnerBalance = await token.balanceOf.callAsync(owner);
const initOwnerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = new BigNumber(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.transfer.sendTransactionAsync(receiver, amountToTransfer, { from: owner }),
await token.transfer(receiver, amountToTransfer).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const finalOwnerBalance = await token.balanceOf.callAsync(owner);
const finalReceiverBalance = await token.balanceOf.callAsync(receiver);
const finalOwnerBalance = await token.balanceOf(owner).callAsync();
const finalReceiverBalance = await token.balanceOf(receiver).callAsync();
const expectedFinalOwnerBalance = initOwnerBalance.minus(amountToTransfer);
const expectedFinalReceiverBalance = amountToTransfer;
@ -84,7 +84,7 @@ describe('UnlimitedAllowanceToken', () => {
});
it('should return true on a 0 value transfer', async () => {
const didReturnTrue = await token.transfer.callAsync(spender, new BigNumber(0), {
const didReturnTrue = await token.transfer(spender, new BigNumber(0)).callAsync({
from: owner,
});
expect(didReturnTrue).to.be.true();
@ -93,14 +93,14 @@ describe('UnlimitedAllowanceToken', () => {
describe('transferFrom', () => {
it('should revert if owner has insufficient balance', async () => {
const ownerBalance = await token.balanceOf.callAsync(owner);
const ownerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = ownerBalance.plus(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.approve.sendTransactionAsync(spender, amountToTransfer, { from: owner }),
await token.approve(spender, amountToTransfer).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
return expectContractCallFailedAsync(
token.transferFrom.callAsync(owner, spender, amountToTransfer, {
token.transferFrom(owner, spender, amountToTransfer).callAsync({
from: spender,
}),
RevertReason.Erc20InsufficientBalance,
@ -108,15 +108,15 @@ describe('UnlimitedAllowanceToken', () => {
});
it('should revert if spender has insufficient allowance', async () => {
const ownerBalance = await token.balanceOf.callAsync(owner);
const ownerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = ownerBalance;
const spenderAllowance = await token.allowance.callAsync(owner, spender);
const spenderAllowance = await token.allowance(owner, spender).callAsync();
const isSpenderAllowanceInsufficient = spenderAllowance.comparedTo(amountToTransfer) < 0;
expect(isSpenderAllowanceInsufficient).to.be.true();
return expectContractCallFailedAsync(
token.transferFrom.callAsync(owner, spender, amountToTransfer, {
token.transferFrom(owner, spender, amountToTransfer).callAsync({
from: spender,
}),
RevertReason.Erc20InsufficientAllowance,
@ -125,72 +125,72 @@ describe('UnlimitedAllowanceToken', () => {
it('should return true on a 0 value transfer', async () => {
const amountToTransfer = new BigNumber(0);
const didReturnTrue = await token.transferFrom.callAsync(owner, spender, amountToTransfer, {
const didReturnTrue = await token.transferFrom(owner, spender, amountToTransfer).callAsync({
from: spender,
});
expect(didReturnTrue).to.be.true();
});
it('should not modify spender allowance if spender allowance is 2^256 - 1', async () => {
const initOwnerBalance = await token.balanceOf.callAsync(owner);
const initOwnerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = initOwnerBalance;
const initSpenderAllowance = constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS;
await web3Wrapper.awaitTransactionSuccessAsync(
await token.approve.sendTransactionAsync(spender, initSpenderAllowance, { from: owner }),
await token.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, {
await token.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({
from: spender,
gas: constants.MAX_TOKEN_TRANSFERFROM_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newSpenderAllowance = await token.allowance.callAsync(owner, spender);
const newSpenderAllowance = await token.allowance(owner, spender).callAsync();
expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance);
});
it('should transfer the correct balances if spender has sufficient allowance', async () => {
const initOwnerBalance = await token.balanceOf.callAsync(owner);
const initOwnerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = initOwnerBalance;
const initSpenderAllowance = initOwnerBalance;
await web3Wrapper.awaitTransactionSuccessAsync(
await token.approve.sendTransactionAsync(spender, initSpenderAllowance, { from: owner }),
await token.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, {
await token.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({
from: spender,
gas: constants.MAX_TOKEN_TRANSFERFROM_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newOwnerBalance = await token.balanceOf.callAsync(owner);
const newSpenderBalance = await token.balanceOf.callAsync(spender);
const newOwnerBalance = await token.balanceOf(owner).callAsync();
const newSpenderBalance = await token.balanceOf(spender).callAsync();
expect(newOwnerBalance).to.be.bignumber.equal(0);
expect(newSpenderBalance).to.be.bignumber.equal(initOwnerBalance);
});
it('should modify allowance if spender has sufficient allowance less than 2^256 - 1', async () => {
const initOwnerBalance = await token.balanceOf.callAsync(owner);
const initOwnerBalance = await token.balanceOf(owner).callAsync();
const amountToTransfer = initOwnerBalance;
const initSpenderAllowance = initOwnerBalance;
await web3Wrapper.awaitTransactionSuccessAsync(
await token.approve.sendTransactionAsync(spender, initSpenderAllowance, { from: owner }),
await token.approve(spender, initSpenderAllowance).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, {
await token.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({
from: spender,
gas: constants.MAX_TOKEN_TRANSFERFROM_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newSpenderAllowance = await token.allowance.callAsync(owner, spender);
const newSpenderAllowance = await token.allowance(owner, spender).callAsync();
expect(newSpenderAllowance).to.be.bignumber.equal(0);
});
});

View File

@ -56,16 +56,16 @@ describe('EtherToken', () => {
const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const ethToDeposit = initEthBalance.plus(1);
return expectInsufficientFundsAsync(etherToken.deposit.sendTransactionAsync({ value: ethToDeposit }));
return expectInsufficientFundsAsync(etherToken.deposit().sendTransactionAsync({ value: ethToDeposit }));
});
it('should convert deposited Ether to wrapped Ether tokens', async () => {
const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const initEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const initEthTokenBalance = await etherToken.balanceOf(account).callAsync();
const ethToDeposit = new BigNumber(Web3Wrapper.toWei(new BigNumber(1)));
const txHash = await etherToken.deposit.sendTransactionAsync({ value: ethToDeposit });
const txHash = await etherToken.deposit().sendTransactionAsync({ value: ethToDeposit });
const receipt = await web3Wrapper.awaitTransactionSuccessAsync(
txHash,
constants.AWAIT_TRANSACTION_MINED_MS,
@ -73,7 +73,7 @@ describe('EtherToken', () => {
const ethSpentOnGas = gasPrice.times(receipt.gasUsed);
const finalEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const finalEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const finalEthTokenBalance = await etherToken.balanceOf(account).callAsync();
expect(finalEthBalance).to.be.bignumber.equal(initEthBalance.minus(ethToDeposit.plus(ethSpentOnGas)));
expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.plus(ethToDeposit));
@ -82,25 +82,25 @@ describe('EtherToken', () => {
describe('withdraw', () => {
it('should revert if caller attempts to withdraw greater than caller balance', async () => {
const initEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const initEthTokenBalance = await etherToken.balanceOf(account).callAsync();
const ethTokensToWithdraw = initEthTokenBalance.plus(1);
return expectTransactionFailedWithoutReasonAsync(
etherToken.withdraw.sendTransactionAsync(ethTokensToWithdraw),
etherToken.withdraw(ethTokensToWithdraw).sendTransactionAsync(),
);
});
it('should convert ether tokens to ether with sufficient balance', async () => {
const ethToDeposit = new BigNumber(Web3Wrapper.toWei(new BigNumber(1)));
await web3Wrapper.awaitTransactionSuccessAsync(
await etherToken.deposit.sendTransactionAsync({ value: ethToDeposit }),
await etherToken.deposit().sendTransactionAsync({ value: ethToDeposit }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const initEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const initEthTokenBalance = await etherToken.balanceOf(account).callAsync();
const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const ethTokensToWithdraw = initEthTokenBalance;
expect(ethTokensToWithdraw).to.not.be.bignumber.equal(0);
const txHash = await etherToken.withdraw.sendTransactionAsync(ethTokensToWithdraw, {
const txHash = await etherToken.withdraw(ethTokensToWithdraw).sendTransactionAsync({
gas: constants.MAX_ETHERTOKEN_WITHDRAW_GAS,
});
const receipt = await web3Wrapper.awaitTransactionSuccessAsync(
@ -110,7 +110,7 @@ describe('EtherToken', () => {
const ethSpentOnGas = gasPrice.times(receipt.gasUsed);
const finalEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const finalEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const finalEthTokenBalance = await etherToken.balanceOf(account).callAsync();
expect(finalEthBalance).to.be.bignumber.equal(
initEthBalance.plus(ethTokensToWithdraw.minus(ethSpentOnGas)),
@ -122,7 +122,7 @@ describe('EtherToken', () => {
describe('fallback', () => {
it('should convert sent ether to ether tokens', async () => {
const initEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const initEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const initEthTokenBalance = await etherToken.balanceOf(account).callAsync();
const ethToDeposit = Web3Wrapper.toBaseUnitAmount(new BigNumber(1), 18);
@ -140,7 +140,7 @@ describe('EtherToken', () => {
const ethSpentOnGas = gasPrice.times(receipt.gasUsed);
const finalEthBalance = await web3Wrapper.getBalanceInWeiAsync(account);
const finalEthTokenBalance = await etherToken.balanceOf.callAsync(account);
const finalEthTokenBalance = await etherToken.balanceOf(account).callAsync();
expect(finalEthBalance).to.be.bignumber.equal(initEthBalance.minus(ethToDeposit.plus(ethSpentOnGas)));
expect(finalEthTokenBalance).to.be.bignumber.equal(initEthTokenBalance.plus(ethToDeposit));

View File

@ -44,25 +44,25 @@ describe('ZRXToken', () => {
});
describe('constants', () => {
it('should have 18 decimals', async () => {
const decimals = new BigNumber(await zrxToken.decimals.callAsync());
const decimals = new BigNumber(await zrxToken.decimals().callAsync());
const expectedDecimals = 18;
expect(decimals).to.be.bignumber.equal(expectedDecimals);
});
it('should have a total supply of 1 billion tokens', async () => {
const totalSupply = new BigNumber(await zrxToken.totalSupply.callAsync());
const totalSupply = new BigNumber(await zrxToken.totalSupply().callAsync());
const expectedTotalSupply = 1000000000;
expect(Web3Wrapper.toUnitAmount(totalSupply, 18)).to.be.bignumber.equal(expectedTotalSupply);
});
it('should be named 0x Protocol Token', async () => {
const name = await zrxToken.name.callAsync();
const name = await zrxToken.name().callAsync();
const expectedName = '0x Protocol Token';
expect(name).to.be.equal(expectedName);
});
it('should have the symbol ZRX', async () => {
const symbol = await zrxToken.symbol.callAsync();
const symbol = await zrxToken.symbol().callAsync();
const expectedSymbol = 'ZRX';
expect(symbol).to.be.equal(expectedSymbol);
});
@ -70,8 +70,8 @@ describe('ZRXToken', () => {
describe('constructor', () => {
it('should initialize owner balance to totalSupply', async () => {
const ownerBalance = await zrxToken.balanceOf.callAsync(owner);
const totalSupply = new BigNumber(await zrxToken.totalSupply.callAsync());
const ownerBalance = await zrxToken.balanceOf(owner).callAsync();
const totalSupply = new BigNumber(await zrxToken.totalSupply().callAsync());
expect(totalSupply).to.be.bignumber.equal(ownerBalance);
});
});
@ -79,14 +79,14 @@ describe('ZRXToken', () => {
describe('transfer', () => {
it('should transfer balance from sender to receiver', async () => {
const receiver = spender;
const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner);
const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync();
const amountToTransfer = new BigNumber(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.transfer.sendTransactionAsync(receiver, amountToTransfer, { from: owner }),
await zrxToken.transfer(receiver, amountToTransfer).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const finalOwnerBalance = await zrxToken.balanceOf.callAsync(owner);
const finalReceiverBalance = await zrxToken.balanceOf.callAsync(receiver);
const finalOwnerBalance = await zrxToken.balanceOf(owner).callAsync();
const finalReceiverBalance = await zrxToken.balanceOf(receiver).callAsync();
const expectedFinalOwnerBalance = initOwnerBalance.minus(amountToTransfer);
const expectedFinalReceiverBalance = amountToTransfer;
@ -95,7 +95,7 @@ describe('ZRXToken', () => {
});
it('should return true on a 0 value transfer', async () => {
const didReturnTrue = await zrxToken.transfer.callAsync(spender, new BigNumber(0), {
const didReturnTrue = await zrxToken.transfer(spender, new BigNumber(0)).callAsync({
from: owner,
});
expect(didReturnTrue).to.be.true();
@ -104,30 +104,30 @@ describe('ZRXToken', () => {
describe('transferFrom', () => {
it('should return false if owner has insufficient balance', async () => {
const ownerBalance = await zrxToken.balanceOf.callAsync(owner);
const ownerBalance = await zrxToken.balanceOf(owner).callAsync();
const amountToTransfer = ownerBalance.plus(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.approve.sendTransactionAsync(spender, amountToTransfer, {
await zrxToken.approve(spender, amountToTransfer).sendTransactionAsync({
from: owner,
gas: constants.MAX_TOKEN_APPROVE_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const didReturnTrue = await zrxToken.transferFrom.callAsync(owner, spender, amountToTransfer, {
const didReturnTrue = await zrxToken.transferFrom(owner, spender, amountToTransfer).callAsync({
from: spender,
});
expect(didReturnTrue).to.be.false();
});
it('should return false if spender has insufficient allowance', async () => {
const ownerBalance = await zrxToken.balanceOf.callAsync(owner);
const ownerBalance = await zrxToken.balanceOf(owner).callAsync();
const amountToTransfer = ownerBalance;
const spenderAllowance = await zrxToken.allowance.callAsync(owner, spender);
const spenderAllowance = await zrxToken.allowance(owner, spender).callAsync();
const isSpenderAllowanceInsufficient = spenderAllowance.comparedTo(amountToTransfer) < 0;
expect(isSpenderAllowanceInsufficient).to.be.true();
const didReturnTrue = await zrxToken.transferFrom.callAsync(owner, spender, amountToTransfer, {
const didReturnTrue = await zrxToken.transferFrom(owner, spender, amountToTransfer).callAsync({
from: spender,
});
expect(didReturnTrue).to.be.false();
@ -135,75 +135,75 @@ describe('ZRXToken', () => {
it('should return true on a 0 value transfer', async () => {
const amountToTransfer = new BigNumber(0);
const didReturnTrue = await zrxToken.transferFrom.callAsync(owner, spender, amountToTransfer, {
const didReturnTrue = await zrxToken.transferFrom(owner, spender, amountToTransfer).callAsync({
from: spender,
});
expect(didReturnTrue).to.be.true();
});
it('should not modify spender allowance if spender allowance is 2^256 - 1', async () => {
const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner);
const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync();
const amountToTransfer = initOwnerBalance;
const initSpenderAllowance = MAX_UINT;
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.approve.sendTransactionAsync(spender, initSpenderAllowance, {
await zrxToken.approve(spender, initSpenderAllowance).sendTransactionAsync({
from: owner,
gas: constants.MAX_TOKEN_APPROVE_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, {
await zrxToken.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({
from: spender,
gas: constants.MAX_TOKEN_TRANSFERFROM_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newSpenderAllowance = await zrxToken.allowance.callAsync(owner, spender);
const newSpenderAllowance = await zrxToken.allowance(owner, spender).callAsync();
expect(initSpenderAllowance).to.be.bignumber.equal(newSpenderAllowance);
});
it('should transfer the correct balances if spender has sufficient allowance', async () => {
const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner);
const initSpenderBalance = await zrxToken.balanceOf.callAsync(spender);
const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync();
const initSpenderBalance = await zrxToken.balanceOf(spender).callAsync();
const amountToTransfer = initOwnerBalance;
const initSpenderAllowance = initOwnerBalance;
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.approve.sendTransactionAsync(spender, initSpenderAllowance),
await zrxToken.approve(spender, initSpenderAllowance).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, {
await zrxToken.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({
from: spender,
gas: constants.MAX_TOKEN_TRANSFERFROM_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newOwnerBalance = await zrxToken.balanceOf.callAsync(owner);
const newSpenderBalance = await zrxToken.balanceOf.callAsync(spender);
const newOwnerBalance = await zrxToken.balanceOf(owner).callAsync();
const newSpenderBalance = await zrxToken.balanceOf(spender).callAsync();
expect(newOwnerBalance).to.be.bignumber.equal(0);
expect(newSpenderBalance).to.be.bignumber.equal(initSpenderBalance.plus(initOwnerBalance));
});
it('should modify allowance if spender has sufficient allowance less than 2^256 - 1', async () => {
const initOwnerBalance = await zrxToken.balanceOf.callAsync(owner);
const initOwnerBalance = await zrxToken.balanceOf(owner).callAsync();
const amountToTransfer = initOwnerBalance;
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.approve.sendTransactionAsync(spender, amountToTransfer),
await zrxToken.approve(spender, amountToTransfer).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await zrxToken.transferFrom.sendTransactionAsync(owner, spender, amountToTransfer, {
await zrxToken.transferFrom(owner, spender, amountToTransfer).sendTransactionAsync({
from: spender,
gas: constants.MAX_TOKEN_TRANSFERFROM_GAS,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newSpenderAllowance = await zrxToken.allowance.callAsync(owner, spender);
const newSpenderAllowance = await zrxToken.allowance(owner, spender).callAsync();
expect(newSpenderAllowance).to.be.bignumber.equal(0);
});
});

View File

@ -61,7 +61,7 @@ describe('ERC721Token', () => {
);
logDecoder = new LogDecoder(web3Wrapper, artifacts);
await web3Wrapper.awaitTransactionSuccessAsync(
await token.mint.sendTransactionAsync(owner, tokenId, { from: owner }),
await token.mint(owner, tokenId).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
});
@ -78,7 +78,7 @@ describe('ERC721Token', () => {
const to = erc721Receiver.address;
const unownedTokenId = new BigNumber(2);
await expectTransactionFailedAsync(
token.transferFrom.sendTransactionAsync(from, to, unownedTokenId),
token.transferFrom(from, to, unownedTokenId).sendTransactionAsync(),
RevertReason.Erc721ZeroOwner,
);
});
@ -86,7 +86,7 @@ describe('ERC721Token', () => {
const from = owner;
const to = constants.NULL_ADDRESS;
await expectTransactionFailedAsync(
token.transferFrom.sendTransactionAsync(from, to, tokenId),
token.transferFrom(from, to, tokenId).sendTransactionAsync(),
RevertReason.Erc721ZeroToAddress,
);
});
@ -94,7 +94,7 @@ describe('ERC721Token', () => {
const from = spender;
const to = erc721Receiver.address;
await expectTransactionFailedAsync(
token.transferFrom.sendTransactionAsync(from, to, tokenId),
token.transferFrom(from, to, tokenId).sendTransactionAsync(),
RevertReason.Erc721OwnerMismatch,
);
});
@ -102,7 +102,7 @@ describe('ERC721Token', () => {
const from = owner;
const to = erc721Receiver.address;
await expectTransactionFailedAsync(
token.transferFrom.sendTransactionAsync(from, to, tokenId, { from: spender }),
token.transferFrom(from, to, tokenId).sendTransactionAsync({ from: spender }),
RevertReason.Erc721InvalidSpender,
);
});
@ -110,9 +110,9 @@ describe('ERC721Token', () => {
const from = owner;
const to = erc721Receiver.address;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.transferFrom.sendTransactionAsync(from, to, tokenId),
await token.transferFrom(from, to, tokenId).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const log = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
expect(log.args._from).to.be.equal(from);
@ -122,16 +122,16 @@ describe('ERC721Token', () => {
it('should transfer the token if spender is approved for all', async () => {
const isApproved = true;
await web3Wrapper.awaitTransactionSuccessAsync(
await token.setApprovalForAll.sendTransactionAsync(spender, isApproved),
await token.setApprovalForAll(spender, isApproved).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const from = owner;
const to = erc721Receiver.address;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.transferFrom.sendTransactionAsync(from, to, tokenId),
await token.transferFrom(from, to, tokenId).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const log = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
expect(log.args._from).to.be.equal(from);
@ -140,19 +140,19 @@ describe('ERC721Token', () => {
});
it('should transfer the token if spender is individually approved', async () => {
await web3Wrapper.awaitTransactionSuccessAsync(
await token.approve.sendTransactionAsync(spender, tokenId),
await token.approve(spender, tokenId).sendTransactionAsync(),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const from = owner;
const to = erc721Receiver.address;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.transferFrom.sendTransactionAsync(from, to, tokenId),
await token.transferFrom(from, to, tokenId).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const approvedAddress = await token.getApproved.callAsync(tokenId);
const approvedAddress = await token.getApproved(tokenId).callAsync();
expect(approvedAddress).to.be.equal(constants.NULL_ADDRESS);
const log = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
expect(log.args._from).to.be.equal(from);
@ -165,9 +165,9 @@ describe('ERC721Token', () => {
const from = owner;
const to = spender;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId),
await token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const log = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
expect(log.args._from).to.be.equal(from);
@ -186,7 +186,7 @@ describe('ERC721Token', () => {
const from = owner;
const to = contract.address;
await expectTransactionFailedWithoutReasonAsync(
token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId),
token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(),
);
});
it('should revert if onERC721Received does not return the correct value', async () => {
@ -199,7 +199,7 @@ describe('ERC721Token', () => {
const from = owner;
const to = invalidErc721Receiver.address;
await expectTransactionFailedAsync(
token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId),
token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(),
RevertReason.Erc721InvalidSelector,
);
});
@ -207,9 +207,9 @@ describe('ERC721Token', () => {
const from = owner;
const to = erc721Receiver.address;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.safeTransferFrom1.sendTransactionAsync(from, to, tokenId),
await token.safeTransferFrom1(from, to, tokenId).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const transferLog = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
const receiverLog = txReceipt.logs[1] as LogWithDecodedArgs<DummyERC721ReceiverTokenReceivedEventArgs>;
@ -228,9 +228,9 @@ describe('ERC721Token', () => {
const from = owner;
const to = spender;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data),
await token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const log = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
expect(log.args._from).to.be.equal(from);
@ -249,7 +249,7 @@ describe('ERC721Token', () => {
const from = owner;
const to = contract.address;
await expectTransactionFailedWithoutReasonAsync(
token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data),
token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(),
);
});
it('should revert if onERC721Received does not return the correct value', async () => {
@ -262,7 +262,7 @@ describe('ERC721Token', () => {
const from = owner;
const to = invalidErc721Receiver.address;
await expectTransactionFailedAsync(
token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data),
token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(),
RevertReason.Erc721InvalidSelector,
);
});
@ -270,9 +270,9 @@ describe('ERC721Token', () => {
const from = owner;
const to = erc721Receiver.address;
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await token.safeTransferFrom2.sendTransactionAsync(from, to, tokenId, data),
await token.safeTransferFrom2(from, to, tokenId, data).sendTransactionAsync(),
);
const newOwner = await token.ownerOf.callAsync(tokenId);
const newOwner = await token.ownerOf(tokenId).callAsync();
expect(newOwner).to.be.equal(to);
const transferLog = txReceipt.logs[0] as LogWithDecodedArgs<DummyERC721TokenTransferEventArgs>;
const receiverLog = txReceipt.logs[1] as LogWithDecodedArgs<DummyERC721ReceiverTokenReceivedEventArgs>;

View File

@ -25,7 +25,7 @@ blockchainTests('LibEIP712ExchangeDomain', env => {
version: constants.EIP712_DOMAIN_VERSION,
};
const expectedDomainHash = ethUtil.bufferToHex(signTypedDataUtils.generateDomainHash(domain));
const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH.callAsync();
const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH().callAsync();
expect(actualDomainHash).to.be.equal(expectedDomainHash);
});
it('should calculate the correct domain hash when verifyingContractAddressIfExists is set to a non-null address', async () => {
@ -46,7 +46,7 @@ blockchainTests('LibEIP712ExchangeDomain', env => {
version: constants.EIP712_DOMAIN_VERSION,
};
const expectedDomainHash = ethUtil.bufferToHex(signTypedDataUtils.generateDomainHash(domain));
const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH.callAsync();
const actualDomainHash = await libEIP712ExchangeDomainContract.EIP712_EXCHANGE_DOMAIN_HASH().callAsync();
expect(actualDomainHash).to.be.equal(expectedDomainHash);
});
});

View File

@ -109,12 +109,14 @@ blockchainTests('LibFillResults', env => {
otherAmount: BigNumber,
): Promise<FillResults> {
const order = makeOrder(otherAmount, orderTakerAssetAmount, otherAmount, otherAmount);
return libsContract.calculateFillResults.callAsync(
return libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
takerAssetFilledAmount, // Using this so that the gas price is distinct from protocolFeeMultiplier
otherAmount,
);
)
.callAsync();
}
testCombinatoriallyWithReferenceFunc(
@ -148,12 +150,14 @@ blockchainTests('LibFillResults', env => {
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
);
const actual = await libsContract.calculateFillResults.callAsync(
const actual = await libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
);
)
.callAsync();
expect(actual).to.deep.eq(expected);
});
@ -170,12 +174,14 @@ blockchainTests('LibFillResults', env => {
order.makerAssetAmount,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -198,12 +204,14 @@ blockchainTests('LibFillResults', env => {
order.makerFee,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -221,12 +229,14 @@ blockchainTests('LibFillResults', env => {
order.takerFee,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -238,12 +248,14 @@ blockchainTests('LibFillResults', env => {
const takerAssetFilledAmount = ONE_ETHER;
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -259,12 +271,14 @@ blockchainTests('LibFillResults', env => {
order.makerAssetAmount,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -286,12 +300,14 @@ blockchainTests('LibFillResults', env => {
order.makerFee,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -313,12 +329,14 @@ blockchainTests('LibFillResults', env => {
order.takerFee,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
@ -336,12 +354,9 @@ blockchainTests('LibFillResults', env => {
MAX_UINT256,
);
return expect(
libsContract.calculateFillResults.callAsync(
order,
takerAssetFilledAmount,
MAX_UINT256,
DEFAULT_GAS_PRICE,
),
libsContract
.calculateFillResults(order, takerAssetFilledAmount, MAX_UINT256, DEFAULT_GAS_PRICE)
.callAsync(),
).to.revertWith(expectedError);
});
@ -363,12 +378,14 @@ blockchainTests('LibFillResults', env => {
order.makerFee,
);
return expect(
libsContract.calculateFillResults.callAsync(
libsContract
.calculateFillResults(
order,
takerAssetFilledAmount,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
DEFAULT_GAS_PRICE,
),
)
.callAsync(),
).to.revertWith(expectedError);
});
});
@ -396,7 +413,7 @@ blockchainTests('LibFillResults', env => {
it('matches the output of the reference function', async () => {
const [a, b] = DEFAULT_FILL_RESULTS;
const expected = addFillResults(a, b);
const actual = await libsContract.addFillResults.callAsync(a, b);
const actual = await libsContract.addFillResults(a, b).callAsync();
expect(actual).to.deep.equal(expected);
});
@ -408,7 +425,7 @@ blockchainTests('LibFillResults', env => {
a.makerAssetFilledAmount,
b.makerAssetFilledAmount,
);
return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError);
return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError);
});
it('reverts if computing `takerAssetFilledAmount` overflows', async () => {
@ -419,7 +436,7 @@ blockchainTests('LibFillResults', env => {
a.takerAssetFilledAmount,
b.takerAssetFilledAmount,
);
return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError);
return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError);
});
it('reverts if computing `makerFeePaid` overflows', async () => {
@ -430,7 +447,7 @@ blockchainTests('LibFillResults', env => {
a.makerFeePaid,
b.makerFeePaid,
);
return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError);
return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError);
});
it('reverts if computing `takerFeePaid` overflows', async () => {
@ -441,7 +458,7 @@ blockchainTests('LibFillResults', env => {
a.takerFeePaid,
b.takerFeePaid,
);
return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError);
return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError);
});
it('reverts if computing `protocolFeePaid` overflows', async () => {
@ -452,7 +469,7 @@ blockchainTests('LibFillResults', env => {
a.protocolFeePaid,
b.protocolFeePaid,
);
return expect(libsContract.addFillResults.callAsync(a, b)).to.revertWith(expectedError);
return expect(libsContract.addFillResults(a, b).callAsync()).to.revertWith(expectedError);
});
});
});
@ -516,7 +533,8 @@ blockchainTests('LibFillResults', env => {
gasPrice: BigNumber,
from?: string,
): Promise<void> {
const actualMatchedFillResults = await libsContract.calculateMatchedFillResults.callAsync(
const actualMatchedFillResults = await libsContract
.calculateMatchedFillResults(
leftOrder,
rightOrder,
leftOrderTakerAssetFilledAmount,
@ -524,8 +542,8 @@ blockchainTests('LibFillResults', env => {
protocolFeeMultiplier,
gasPrice,
false,
{ from },
);
)
.callAsync({ from });
expect(actualMatchedFillResults).to.be.deep.eq(expectedMatchedFillResults);
}
@ -1187,7 +1205,8 @@ blockchainTests('LibFillResults', env => {
gasPrice: BigNumber,
from?: string,
): Promise<void> {
const actualMatchedFillResults = await libsContract.calculateMatchedFillResults.callAsync(
const actualMatchedFillResults = await libsContract
.calculateMatchedFillResults(
leftOrder,
rightOrder,
leftOrderTakerAssetFilledAmount,
@ -1195,8 +1214,8 @@ blockchainTests('LibFillResults', env => {
protocolFeeMultiplier,
gasPrice,
true,
{ from },
);
)
.callAsync({ from });
expect(actualMatchedFillResults).to.be.deep.eq(expectedMatchedFillResults);
}

View File

@ -43,8 +43,7 @@ blockchainTests('LibMath', env => {
function createContractTestFunction<T>(name: string): (...args: any[]) => Promise<T> {
return async (...args: any[]): Promise<T> => {
const method = (libsContract as any)[name] as { callAsync: (...args: any[]) => Promise<T> };
return method.callAsync(...args);
return (libsContract as any)[name](...args).callAsync;
};
}
@ -64,7 +63,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = ONE_ETHER.times(0.01);
const expected = getPartialAmountFloor(numerator, denominator, target);
const actual = await libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -73,7 +72,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.times(1.8);
const target = ONE_ETHER;
const expected = ONE_ETHER.dividedToIntegerBy(3);
const actual = await libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -87,7 +86,7 @@ blockchainTests('LibMath', env => {
denominator,
);
return expect(
libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target),
libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -101,7 +100,7 @@ blockchainTests('LibMath', env => {
target,
);
return expect(
libsContract.getPartialAmountFloor.callAsync(numerator, denominator, target),
libsContract.getPartialAmountFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
});
@ -123,7 +122,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = ONE_ETHER.times(0.01);
const expected = getPartialAmountCeil(numerator, denominator, target);
const actual = await libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -132,7 +131,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.times(1.8);
const target = ONE_ETHER;
const expected = ONE_ETHER.dividedToIntegerBy(3).plus(1);
const actual = await libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -147,7 +146,7 @@ blockchainTests('LibMath', env => {
new BigNumber(1),
);
return expect(
libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target),
libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -161,7 +160,7 @@ blockchainTests('LibMath', env => {
target,
);
return expect(
libsContract.getPartialAmountCeil.callAsync(numerator, denominator, target),
libsContract.getPartialAmountCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
});
@ -183,7 +182,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = ONE_ETHER.times(0.01);
const expected = safeGetPartialAmountFloor(numerator, denominator, target);
const actual = await libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -192,7 +191,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.times(1.8);
const target = ONE_ETHER;
const expected = ONE_ETHER.dividedToIntegerBy(3);
const actual = await libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -202,7 +201,7 @@ blockchainTests('LibMath', env => {
const target = new BigNumber(333);
const expectedError = new LibMathRevertErrors.RoundingError(numerator, denominator, target);
return expect(
libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target),
libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -212,7 +211,7 @@ blockchainTests('LibMath', env => {
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(
libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target),
libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -226,7 +225,7 @@ blockchainTests('LibMath', env => {
target,
);
return expect(
libsContract.safeGetPartialAmountFloor.callAsync(numerator, denominator, target),
libsContract.safeGetPartialAmountFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
});
@ -248,7 +247,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.dividedToIntegerBy(2);
const target = ONE_ETHER.times(0.01);
const expected = safeGetPartialAmountCeil(numerator, denominator, target);
const actual = await libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -257,7 +256,7 @@ blockchainTests('LibMath', env => {
const denominator = ONE_ETHER.times(1.8);
const target = ONE_ETHER;
const expected = ONE_ETHER.dividedToIntegerBy(3).plus(1);
const actual = await libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync();
expect(actual).to.bignumber.eq(expected);
});
@ -267,7 +266,7 @@ blockchainTests('LibMath', env => {
const target = new BigNumber(333);
const expectedError = new LibMathRevertErrors.RoundingError(numerator, denominator, target);
return expect(
libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target),
libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -277,7 +276,7 @@ blockchainTests('LibMath', env => {
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(
libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target),
libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -291,7 +290,7 @@ blockchainTests('LibMath', env => {
target,
);
return expect(
libsContract.safeGetPartialAmountCeil.callAsync(numerator, denominator, target),
libsContract.safeGetPartialAmountCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
});
@ -313,7 +312,7 @@ blockchainTests('LibMath', env => {
const denominator = new BigNumber(102);
const target = new BigNumber(52);
// tslint:disable-next-line: boolean-naming
const actual = await libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync();
expect(actual).to.eq(true);
});
@ -322,7 +321,7 @@ blockchainTests('LibMath', env => {
const denominator = new BigNumber(101);
const target = new BigNumber(92);
// tslint:disable-next-line: boolean-naming
const actual = await libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync();
expect(actual).to.eq(false);
});
@ -333,7 +332,7 @@ blockchainTests('LibMath', env => {
// tslint:disable-next-line: boolean-naming
const expected = isRoundingErrorFloor(numerator, denominator, target);
// tslint:disable-next-line: boolean-naming
const actual = await libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target);
const actual = await libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync();
expect(actual).to.eq(expected);
});
@ -343,7 +342,7 @@ blockchainTests('LibMath', env => {
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(
libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target),
libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
@ -357,7 +356,7 @@ blockchainTests('LibMath', env => {
target,
);
return expect(
libsContract.isRoundingErrorFloor.callAsync(numerator, denominator, target),
libsContract.isRoundingErrorFloor(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
});
@ -379,7 +378,7 @@ blockchainTests('LibMath', env => {
const denominator = new BigNumber(101);
const target = new BigNumber(92);
// tslint:disable-next-line: boolean-naming
const actual = await libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync();
expect(actual).to.eq(true);
});
@ -388,7 +387,7 @@ blockchainTests('LibMath', env => {
const denominator = new BigNumber(102);
const target = new BigNumber(52);
// tslint:disable-next-line: boolean-naming
const actual = await libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync();
expect(actual).to.eq(false);
});
@ -399,7 +398,7 @@ blockchainTests('LibMath', env => {
// tslint:disable-next-line: boolean-naming
const expected = isRoundingErrorCeil(numerator, denominator, target);
// tslint:disable-next-line: boolean-naming
const actual = await libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target);
const actual = await libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync();
expect(actual).to.eq(expected);
});
@ -408,9 +407,9 @@ blockchainTests('LibMath', env => {
const denominator = ZERO_AMOUNT;
const target = ONE_ETHER.times(0.01);
const expectedError = new LibMathRevertErrors.DivisionByZeroError();
return expect(libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target)).to.revertWith(
expectedError,
);
return expect(
libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
it('reverts if `numerator * target` overflows', async () => {
@ -422,9 +421,9 @@ blockchainTests('LibMath', env => {
numerator,
target,
);
return expect(libsContract.isRoundingErrorCeil.callAsync(numerator, denominator, target)).to.revertWith(
expectedError,
);
return expect(
libsContract.isRoundingErrorCeil(numerator, denominator, target).callAsync(),
).to.revertWith(expectedError);
});
});
});

View File

@ -58,7 +58,7 @@ blockchainTests('LibOrder', env => {
version: constants.EIP712_DOMAIN_VERSION,
}),
);
const actualHash = await libOrderContract.getTypedDataHash.callAsync(order, domainHash);
const actualHash = await libOrderContract.getTypedDataHash(order, domainHash).callAsync();
expect(actualHash).to.be.eq(expectedHash);
}
@ -108,8 +108,8 @@ blockchainTests('LibOrder', env => {
chainId: 1337,
}),
);
const orderHashHex1 = await libOrderContract.getTypedDataHash.callAsync(EMPTY_ORDER, domainHash1);
const orderHashHex2 = await libOrderContract.getTypedDataHash.callAsync(EMPTY_ORDER, domainHash2);
const orderHashHex1 = await libOrderContract.getTypedDataHash(EMPTY_ORDER, domainHash1).callAsync();
const orderHashHex2 = await libOrderContract.getTypedDataHash(EMPTY_ORDER, domainHash2).callAsync();
expect(orderHashHex1).to.be.not.equal(orderHashHex2);
});
});
@ -120,7 +120,7 @@ blockchainTests('LibOrder', env => {
async function testGetStructHashAsync(order: Order): Promise<void> {
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);
}

View File

@ -50,7 +50,7 @@ blockchainTests('LibZeroExTransaction', env => {
version: constants.EIP712_DOMAIN_VERSION,
}),
);
const actualHash = await libZeroExTransactionContract.getTypedDataHash.callAsync(transaction, domainHash);
const actualHash = await libZeroExTransactionContract.getTypedDataHash(transaction, domainHash).callAsync();
expect(actualHash).to.be.eq(expectedHash);
}
@ -94,14 +94,12 @@ blockchainTests('LibZeroExTransaction', env => {
chainId: 1337,
}),
);
const transactionHashHex1 = await libZeroExTransactionContract.getTypedDataHash.callAsync(
EMPTY_TRANSACTION,
domainHash1,
);
const transactionHashHex2 = await libZeroExTransactionContract.getTypedDataHash.callAsync(
EMPTY_TRANSACTION,
domainHash2,
);
const transactionHashHex1 = await libZeroExTransactionContract
.getTypedDataHash(EMPTY_TRANSACTION, domainHash1)
.callAsync();
const transactionHashHex2 = await libZeroExTransactionContract
.getTypedDataHash(EMPTY_TRANSACTION, domainHash2)
.callAsync();
expect(transactionHashHex1).to.be.not.equal(transactionHashHex2);
});
});
@ -112,7 +110,7 @@ blockchainTests('LibZeroExTransaction', env => {
async function testGetStructHashAsync(transaction: ZeroExTransaction): Promise<void> {
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);
}

View File

@ -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) {

View File

@ -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]);

View File

@ -9,44 +9,38 @@ export const exchangeDataEncoder = {
const exchangeInstance = new IExchangeContract(constants.NULL_ADDRESS, provider);
let data;
if (constants.SINGLE_FILL_FN_NAMES.indexOf(fnName) !== -1) {
data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData(
orders[0],
orders[0].takerAssetAmount,
orders[0].signature,
);
data = (exchangeInstance as any)
[fnName](orders[0], orders[0].takerAssetAmount, orders[0].signature)
.getABIEncodedTransactionData();
} else if (constants.BATCH_FILL_FN_NAMES.indexOf(fnName) !== -1) {
data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData(
orders,
orders.map(order => order.takerAssetAmount),
orders.map(order => order.signature),
);
data = (exchangeInstance as any)
[fnName](orders, orders.map(order => order.takerAssetAmount), orders.map(order => order.signature))
.getABIEncodedTransactionData();
} else if (constants.MARKET_FILL_FN_NAMES.indexOf(fnName) !== -1) {
const fillAsset = /Buy/.test(fnName) ? 'makerAssetAmount' : 'takerAssetAmount';
data = (exchangeInstance as any)[fnName].getABIEncodedTransactionData(
data = (exchangeInstance as any)
[fnName](
orders,
orders.map(order => order[fillAsset]).reduce((prev, curr) => prev.plus(curr)),
orders.map(order => order.signature),
);
)
.getABIEncodedTransactionData();
} else if (constants.MATCH_ORDER_FN_NAMES.indexOf(fnName) !== -1) {
data = exchangeInstance.matchOrders.getABIEncodedTransactionData(
orders[0],
orders[1],
orders[0].signature,
orders[1].signature,
);
data = exchangeInstance
.matchOrders(orders[0], orders[1], orders[0].signature, orders[1].signature)
.getABIEncodedTransactionData();
} else if (fnName === ExchangeFunctionName.CancelOrder) {
data = exchangeInstance.cancelOrder.getABIEncodedTransactionData(orders[0]);
data = exchangeInstance.cancelOrder(orders[0]).getABIEncodedTransactionData();
} else if (fnName === ExchangeFunctionName.BatchCancelOrders) {
data = exchangeInstance.batchCancelOrders.getABIEncodedTransactionData(orders);
data = exchangeInstance.batchCancelOrders(orders).getABIEncodedTransactionData();
} else if (fnName === ExchangeFunctionName.CancelOrdersUpTo) {
data = exchangeInstance.cancelOrdersUpTo.getABIEncodedTransactionData(constants.ZERO_AMOUNT);
data = exchangeInstance.cancelOrdersUpTo(constants.ZERO_AMOUNT).getABIEncodedTransactionData();
} else if (fnName === ExchangeFunctionName.PreSign) {
data = exchangeInstance.preSign.getABIEncodedTransactionData(orderHashUtils.getOrderHashHex(orders[0]));
data = exchangeInstance.preSign(orderHashUtils.getOrderHashHex(orders[0])).getABIEncodedTransactionData();
} else if (fnName === ExchangeFunctionName.SetSignatureValidatorApproval) {
data = exchangeInstance.setSignatureValidatorApproval.getABIEncodedTransactionData(
constants.NULL_ADDRESS,
true,
);
data = exchangeInstance
.setSignatureValidatorApproval(constants.NULL_ADDRESS, true)
.getABIEncodedTransactionData();
} else {
throw new Error(`Error: ${fnName} not a supported function`);
}

View File

@ -154,9 +154,9 @@ export class FillOrderWrapper {
): Promise<void> {
// Get init state
await this._blockchainBalanceStore.updateBalancesAsync();
const initTakerAssetFilledAmount = await this._exchange.filled.callAsync(
orderHashUtils.getOrderHashHex(signedOrder),
);
const initTakerAssetFilledAmount = await this._exchange
.filled(orderHashUtils.getOrderHashHex(signedOrder))
.callAsync();
// Assert init state of exchange
await this._assertOrderStateAsync(signedOrder, initTakerAssetFilledAmount);
// Simulate and execute fill then assert outputs
@ -187,18 +187,12 @@ export class FillOrderWrapper {
opts: { takerAssetFillAmount?: BigNumber } = {},
): Promise<[FillResults, FillEventArgs, TransactionReceiptWithDecodedLogs]> {
const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount);
const fillResults = await this._exchange.fillOrder.callAsync(
params.order,
params.takerAssetFillAmount,
params.signature,
{ from },
);
const txReceipt = await this._exchange.fillOrder.awaitTransactionSuccessAsync(
params.order,
params.takerAssetFillAmount,
params.signature,
{ from },
);
const fillResults = await this._exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.callAsync({ from });
const txReceipt = await this._exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.awaitTransactionSuccessAsync({ from });
const fillEvent = FillOrderWrapper._extractFillEventsfromReceipt(txReceipt)[0];
return [fillResults, fillEvent, txReceipt];
}
@ -213,7 +207,7 @@ export class FillOrderWrapper {
order: SignedOrder,
expectedFilledAmount: BigNumber = new BigNumber(0),
): Promise<void> {
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);

View File

@ -152,22 +152,22 @@ blockchainTests.resets('Exchange core', () => {
exchange.address,
);
// Configure ERC20Proxy
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner });
await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner });
// Configure ERC721Proxy
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner });
await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner });
// Configure ERC1155Proxy
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: owner });
await erc1155Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: owner });
// Configure MultiAssetProxy
await multiAssetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { from: owner });
await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { from: owner });
await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(staticCallProxy.address, { from: owner });
await multiAssetProxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: owner });
await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: owner });
await multiAssetProxy.registerAssetProxy(staticCallProxy.address).awaitTransactionSuccessAsync({ from: owner });
// Configure Exchange
exchangeWrapper = new ExchangeWrapper(exchange);
@ -211,10 +211,10 @@ blockchainTests.resets('Exchange core', () => {
...constants.STATIC_ORDER_PARAMS,
makerAddress,
feeRecipientAddress,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeAssetAddress),
takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(),
makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeAssetAddress).callAsync(),
takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeAssetAddress).callAsync(),
exchangeAddress: exchange.address,
chainId,
};
@ -252,24 +252,19 @@ blockchainTests.resets('Exchange core', () => {
describe('callback signature types', () => {
beforeEach(async () => {
// Approve the ERC20 proxy with the test validator wallet.
await validatorWallet.approveERC20.awaitTransactionSuccessAsync(
erc20TokenA.address,
erc20Proxy.address,
constants.INITIAL_ERC20_ALLOWANCE,
);
await validatorWallet
.approveERC20(erc20TokenA.address, erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE)
.awaitTransactionSuccessAsync();
// Mint some ERC20 tokens to the test validator wallet.
await erc20TokenA.setBalance.awaitTransactionSuccessAsync(
validatorWallet.address,
constants.INITIAL_ERC20_BALANCE,
);
await erc20TokenA
.setBalance(validatorWallet.address, constants.INITIAL_ERC20_BALANCE)
.awaitTransactionSuccessAsync();
// Approve the validator.
await exchange.setSignatureValidatorApproval.awaitTransactionSuccessAsync(
validatorWallet.address,
true,
{
await exchange
.setSignatureValidatorApproval(validatorWallet.address, true)
.awaitTransactionSuccessAsync({
from: makerAddress,
},
);
});
signedOrder = await orderFactory.newSignedOrderAsync({
makerFee: constants.ZERO_AMOUNT,
takerFee: constants.ZERO_AMOUNT,
@ -281,19 +276,15 @@ blockchainTests.resets('Exchange core', () => {
signedOrder.signature = signatureHex;
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Allow the signature check for the first fill.
await validatorWallet.prepare.awaitTransactionSuccessAsync(
orderHashHex,
ValidatorWalletAction.Accept,
constants.NULL_BYTES,
);
await validatorWallet
.prepare(orderHashHex, ValidatorWalletAction.Accept, constants.NULL_BYTES)
.awaitTransactionSuccessAsync();
const fillAmount = signedOrder.takerAssetAmount.div(10);
await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount });
// Reject the signature check for the second fill.
await validatorWallet.prepare.awaitTransactionSuccessAsync(
orderHashHex,
ValidatorWalletAction.Reject,
constants.NULL_BYTES,
);
await validatorWallet
.prepare(orderHashHex, ValidatorWalletAction.Reject, constants.NULL_BYTES)
.awaitTransactionSuccessAsync();
const tx = exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, {
takerAssetFillAmount: fillAmount,
});
@ -312,19 +303,15 @@ blockchainTests.resets('Exchange core', () => {
signedOrder.signature = signatureHex;
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Allow the signature check for the first fill.
await validatorWallet.prepare.awaitTransactionSuccessAsync(
orderHashHex,
ValidatorWalletAction.Accept,
constants.NULL_BYTES,
);
await validatorWallet
.prepare(orderHashHex, ValidatorWalletAction.Accept, constants.NULL_BYTES)
.awaitTransactionSuccessAsync();
const fillAmount = signedOrder.takerAssetAmount.div(10);
await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount });
// Reject the signature check for the second fill.
await validatorWallet.prepare.awaitTransactionSuccessAsync(
orderHashHex,
ValidatorWalletAction.Reject,
constants.NULL_BYTES,
);
await validatorWallet
.prepare(orderHashHex, ValidatorWalletAction.Reject, constants.NULL_BYTES)
.awaitTransactionSuccessAsync();
const tx = exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, {
takerAssetFillAmount: fillAmount,
});
@ -343,19 +330,15 @@ blockchainTests.resets('Exchange core', () => {
signedOrder.signature = signatureHex;
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Allow the signature check for the first fill.
await validatorWallet.prepare.awaitTransactionSuccessAsync(
orderHashHex,
ValidatorWalletAction.Accept,
constants.NULL_BYTES,
);
await validatorWallet
.prepare(orderHashHex, ValidatorWalletAction.Accept, constants.NULL_BYTES)
.awaitTransactionSuccessAsync();
const fillAmount = signedOrder.takerAssetAmount.div(10);
await exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, { takerAssetFillAmount: fillAmount });
// Reject the signature check for the second fill.
await validatorWallet.prepare.awaitTransactionSuccessAsync(
orderHashHex,
ValidatorWalletAction.Reject,
constants.NULL_BYTES,
);
await validatorWallet
.prepare(orderHashHex, ValidatorWalletAction.Reject, constants.NULL_BYTES)
.awaitTransactionSuccessAsync();
const tx = exchangeWrapper.fillOrderAsync(signedOrder, takerAddress, {
takerAssetFillAmount: fillAmount,
});
@ -420,9 +403,11 @@ blockchainTests.resets('Exchange core', () => {
describe('Fill transfer ordering', () => {
it('should allow the maker to exchange assets received by the taker', async () => {
// Set maker/taker assetData to the same asset
const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const takerAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
const takerAssetAmount = new BigNumber(1);
const makerAssetData = await devUtils.encodeMultiAssetData.callAsync([takerAssetAmount], [takerAssetData]);
const makerAssetData = await devUtils
.encodeMultiAssetData([takerAssetAmount], [takerAssetData])
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
takerAssetData,
@ -432,33 +417,33 @@ blockchainTests.resets('Exchange core', () => {
takerFee: constants.ZERO_AMOUNT,
});
// Set maker balance to 0 so that the asset must be received by the taker in order for the fill to succeed
await erc20TokenA.setBalance.awaitTransactionSuccessAsync(makerAddress, constants.ZERO_AMOUNT, {
await erc20TokenA.setBalance(makerAddress, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({
from: owner,
});
await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress);
});
it('should allow the taker to pay fees with an asset that received by the maker', async () => {
const makerAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const makerAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
takerFeeAssetData: makerAssetData,
makerFee: constants.ZERO_AMOUNT,
takerFee: new BigNumber(1),
});
// Set taker balance to 0 so that the asset must be received by the maker in order for the fill to succeed
await erc20TokenA.setBalance.awaitTransactionSuccessAsync(takerAddress, constants.ZERO_AMOUNT, {
await erc20TokenA.setBalance(takerAddress, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({
from: owner,
});
await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress);
});
it('should allow the maker to pay fees with an asset that received by the taker', async () => {
const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address);
const takerAssetData = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerFeeAssetData: takerAssetData,
makerFee: new BigNumber(1),
takerFee: constants.ZERO_AMOUNT,
});
// Set maker balance to 0 so that the asset must be received by the taker in order for the fill to succeed
await erc20TokenB.setBalance.awaitTransactionSuccessAsync(makerAddress, constants.ZERO_AMOUNT, {
await erc20TokenB.setBalance(makerAddress, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({
from: owner,
});
await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress);
@ -466,19 +451,16 @@ blockchainTests.resets('Exchange core', () => {
});
describe('Testing exchange of ERC20 tokens with no return values', () => {
before(async () => {
await noReturnErc20Token.setBalance.awaitTransactionSuccessAsync(
makerAddress,
constants.INITIAL_ERC20_BALANCE,
);
await noReturnErc20Token.approve.awaitTransactionSuccessAsync(
erc20Proxy.address,
constants.INITIAL_ERC20_ALLOWANCE,
{ from: makerAddress },
);
await noReturnErc20Token
.setBalance(makerAddress, constants.INITIAL_ERC20_BALANCE)
.awaitTransactionSuccessAsync();
await noReturnErc20Token
.approve(erc20Proxy.address, constants.INITIAL_ERC20_ALLOWANCE)
.awaitTransactionSuccessAsync({ from: makerAddress });
});
it('should transfer the correct amounts when makerAssetAmount === takerAssetAmount', async () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address),
makerAssetData: await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18),
});
@ -486,7 +468,7 @@ blockchainTests.resets('Exchange core', () => {
});
it('should transfer the correct amounts when makerAssetAmount > takerAssetAmount', async () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address),
makerAssetData: await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18),
});
@ -494,7 +476,7 @@ blockchainTests.resets('Exchange core', () => {
});
it('should transfer the correct amounts when makerAssetAmount < takerAssetAmount', async () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(noReturnErc20Token.address),
makerAssetData: await devUtils.encodeERC20AssetData(noReturnErc20Token.address).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), 18),
});
@ -671,14 +653,14 @@ blockchainTests.resets('Exchange core', () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetAmount: new BigNumber(1),
takerAssetAmount: new BigNumber(1),
makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId),
takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId),
makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(),
takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(),
});
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Verify pre-conditions
const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId);
const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync();
expect(initialOwnerMakerAsset).to.be.bignumber.not.equal(makerAddress);
const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId);
const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync();
expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress);
// Call Exchange
const takerAssetFillAmount = signedOrder.takerAssetAmount;
@ -698,14 +680,14 @@ blockchainTests.resets('Exchange core', () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetAmount: new BigNumber(1),
takerAssetAmount: new BigNumber(1),
makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId),
takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId),
makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(),
takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(),
});
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Verify pre-conditions
const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId);
const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync();
expect(initialOwnerMakerAsset).to.be.bignumber.equal(makerAddress);
const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId);
const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync();
expect(initialOwnerTakerAsset).to.be.bignumber.not.equal(takerAddress);
// Call Exchange
const takerAssetFillAmount = signedOrder.takerAssetAmount;
@ -725,14 +707,14 @@ blockchainTests.resets('Exchange core', () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetAmount: new BigNumber(2),
takerAssetAmount: new BigNumber(1),
makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId),
takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId),
makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(),
takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(),
});
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Verify pre-conditions
const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId);
const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync();
expect(initialOwnerMakerAsset).to.be.bignumber.equal(makerAddress);
const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId);
const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync();
expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress);
// Call Exchange
const takerAssetFillAmount = signedOrder.takerAssetAmount;
@ -752,14 +734,14 @@ blockchainTests.resets('Exchange core', () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetAmount: new BigNumber(1),
takerAssetAmount: new BigNumber(500),
makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId),
takerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId),
makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(),
takerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(),
});
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
// Verify pre-conditions
const initialOwnerMakerAsset = await erc721Token.ownerOf.callAsync(makerAssetId);
const initialOwnerMakerAsset = await erc721Token.ownerOf(makerAssetId).callAsync();
expect(initialOwnerMakerAsset).to.be.bignumber.equal(makerAddress);
const initialOwnerTakerAsset = await erc721Token.ownerOf.callAsync(takerAssetId);
const initialOwnerTakerAsset = await erc721Token.ownerOf(takerAssetId).callAsync();
expect(initialOwnerTakerAsset).to.be.bignumber.equal(takerAddress);
// Call Exchange
const takerAssetFillAmount = signedOrder.takerAssetAmount;
@ -778,8 +760,8 @@ blockchainTests.resets('Exchange core', () => {
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetAmount: new BigNumber(1),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), 18),
makerAssetData: await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, makerAssetId),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress),
makerAssetData: await devUtils.encodeERC721AssetData(erc721Token.address, makerAssetId).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(),
});
// Call Exchange
const takerAssetFillAmount = signedOrder.takerAssetAmount.div(2);
@ -797,12 +779,12 @@ blockchainTests.resets('Exchange core', () => {
it('should allow multiple assets to be exchanged for a single asset', async () => {
const makerAmounts = [new BigNumber(10), new BigNumber(20)];
const makerNestedAssetData = [
await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address),
await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address),
await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(),
await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(),
];
const makerAssetData = await devUtils.encodeMultiAssetData.callAsync(makerAmounts, makerNestedAssetData);
const makerAssetData = await devUtils.encodeMultiAssetData(makerAmounts, makerNestedAssetData).callAsync();
const makerAssetAmount = new BigNumber(1);
const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(feeToken.address);
const takerAssetData = await devUtils.encodeERC20AssetData(feeToken.address).callAsync();
const takerAssetAmount = new BigNumber(10);
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
@ -817,18 +799,18 @@ blockchainTests.resets('Exchange core', () => {
it('should allow multiple assets to be exchanged for multiple assets', async () => {
const makerAmounts = [new BigNumber(10), new BigNumber(20)];
const makerNestedAssetData = [
await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address),
await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address),
await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(),
await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(),
];
const makerAssetData = await devUtils.encodeMultiAssetData.callAsync(makerAmounts, makerNestedAssetData);
const makerAssetData = await devUtils.encodeMultiAssetData(makerAmounts, makerNestedAssetData).callAsync();
const makerAssetAmount = new BigNumber(1);
const takerAmounts = [new BigNumber(10), new BigNumber(1)];
const takerAssetId = erc721TakerAssetIds[0];
const takerNestedAssetData = [
await devUtils.encodeERC20AssetData.callAsync(feeToken.address),
await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, takerAssetId),
await devUtils.encodeERC20AssetData(feeToken.address).callAsync(),
await devUtils.encodeERC721AssetData(erc721Token.address, takerAssetId).callAsync(),
];
const takerAssetData = await devUtils.encodeMultiAssetData.callAsync(takerAmounts, takerNestedAssetData);
const takerAssetData = await devUtils.encodeMultiAssetData(takerAmounts, takerNestedAssetData).callAsync();
const takerAssetAmount = new BigNumber(1);
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
@ -843,12 +825,12 @@ blockchainTests.resets('Exchange core', () => {
it('should allow an order selling multiple assets to be partially filled', async () => {
const makerAmounts = [new BigNumber(10), new BigNumber(20)];
const makerNestedAssetData = [
await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address),
await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address),
await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(),
await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(),
];
const makerAssetData = await devUtils.encodeMultiAssetData.callAsync(makerAmounts, makerNestedAssetData);
const makerAssetData = await devUtils.encodeMultiAssetData(makerAmounts, makerNestedAssetData).callAsync();
const makerAssetAmount = new BigNumber(30);
const takerAssetData = await devUtils.encodeERC20AssetData.callAsync(feeToken.address);
const takerAssetData = await devUtils.encodeERC20AssetData(feeToken.address).callAsync();
const takerAssetAmount = new BigNumber(10);
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
@ -865,12 +847,12 @@ blockchainTests.resets('Exchange core', () => {
it('should allow an order buying multiple assets to be partially filled', async () => {
const takerAmounts = [new BigNumber(10), new BigNumber(20)];
const takerNestedAssetData = [
await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address),
await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address),
await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync(),
await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync(),
];
const takerAssetData = await devUtils.encodeMultiAssetData.callAsync(takerAmounts, takerNestedAssetData);
const takerAssetData = await devUtils.encodeMultiAssetData(takerAmounts, takerNestedAssetData).callAsync();
const takerAssetAmount = new BigNumber(30);
const makerAssetData = await devUtils.encodeERC20AssetData.callAsync(feeToken.address);
const makerAssetData = await devUtils.encodeERC20AssetData(feeToken.address).callAsync();
const makerAssetAmount = new BigNumber(10);
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
@ -896,18 +878,22 @@ blockchainTests.resets('Exchange core', () => {
const makerAssetAmount = new BigNumber(1);
const takerAssetAmount = new BigNumber(1);
const receiverCallbackData = '0x';
const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const makerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
makerAssetsToTransfer,
makerValuesToTransfer,
receiverCallbackData,
);
const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
)
.callAsync();
const takerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
takerAssetsToTransfer,
takerValuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
takerAssetData,
@ -931,18 +917,22 @@ blockchainTests.resets('Exchange core', () => {
const makerAssetAmount = new BigNumber(1);
const takerAssetAmount = new BigNumber(1);
const receiverCallbackData = '0x';
const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const makerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
makerAssetsToTransfer,
makerValuesToTransfer,
receiverCallbackData,
);
const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
)
.callAsync();
const takerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
takerAssetsToTransfer,
takerValuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
takerAssetData,
@ -965,18 +955,22 @@ blockchainTests.resets('Exchange core', () => {
const makerAssetAmount = new BigNumber(1);
const takerAssetAmount = new BigNumber(1);
const receiverCallbackData = '0x';
const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const makerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
makerAssetsToTransfer,
makerValuesToTransfer,
receiverCallbackData,
);
const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
)
.callAsync();
const takerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
takerAssetsToTransfer,
takerValuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
takerAssetData,
@ -1005,18 +999,22 @@ blockchainTests.resets('Exchange core', () => {
const makerAssetAmount = new BigNumber(1);
const takerAssetAmount = new BigNumber(1);
const receiverCallbackData = '0x';
const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const makerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
makerAssetsToTransfer,
makerValuesToTransfer,
receiverCallbackData,
);
const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
)
.callAsync();
const takerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
takerAssetsToTransfer,
takerValuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
takerAssetData,
@ -1050,18 +1048,22 @@ blockchainTests.resets('Exchange core', () => {
const makerAssetAmount = new BigNumber(10);
const takerAssetAmount = new BigNumber(20);
const receiverCallbackData = '0x';
const makerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
const makerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
makerAssetsToTransfer,
makerValuesToTransfer,
receiverCallbackData,
);
const takerAssetData = await devUtils.encodeERC1155AssetData.callAsync(
)
.callAsync();
const takerAssetData = await devUtils
.encodeERC1155AssetData(
erc1155Contract.address,
takerAssetsToTransfer,
takerValuesToTransfer,
receiverCallbackData,
);
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({
makerAssetData,
takerAssetData,
@ -1086,12 +1088,10 @@ blockchainTests.resets('Exchange core', () => {
);
});
it('should revert if the staticcall is unsuccessful', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1));
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
constants.KECCAK256_NULL,
);
const staticCallData = staticCallTarget.assertEvenNumber(new BigNumber(1)).getABIEncodedTransactionData();
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData });
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const expectedError = new ExchangeRevertErrors.AssetProxyTransferError(
@ -1103,28 +1103,26 @@ blockchainTests.resets('Exchange core', () => {
return expect(tx).to.revertWith(expectedError);
});
it('should fill the order if the staticcall is successful', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(
constants.ZERO_AMOUNT,
);
const assetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
constants.KECCAK256_NULL,
);
const staticCallData = staticCallTarget
.assertEvenNumber(constants.ZERO_AMOUNT)
.getABIEncodedTransactionData();
const assetData = await devUtils
.encodeStaticCallAssetData(staticCallTarget.address, staticCallData, constants.KECCAK256_NULL)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData });
await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress);
});
it('should revert if the staticcall is unsuccessful using the MultiAssetProxy', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(new BigNumber(1));
const staticCallAssetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
constants.KECCAK256_NULL,
);
const assetData = await devUtils.encodeMultiAssetData.callAsync(
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.callAsync(defaultMakerAssetAddress), staticCallAssetData],
);
[await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), staticCallAssetData],
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData });
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const expectedError = new ExchangeRevertErrors.AssetProxyTransferError(
@ -1136,18 +1134,18 @@ blockchainTests.resets('Exchange core', () => {
return expect(tx).to.revertWith(expectedError);
});
it('should fill the order is the staticcall is successful using the MultiAssetProxy', async () => {
const staticCallData = staticCallTarget.assertEvenNumber.getABIEncodedTransactionData(
constants.ZERO_AMOUNT,
);
const staticCallAssetData = await devUtils.encodeStaticCallAssetData.callAsync(
staticCallTarget.address,
staticCallData,
constants.KECCAK256_NULL,
);
const assetData = await devUtils.encodeMultiAssetData.callAsync(
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.callAsync(defaultMakerAssetAddress), staticCallAssetData],
);
[await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(), staticCallAssetData],
)
.callAsync();
signedOrder = await orderFactory.newSignedOrderAsync({ makerAssetData: assetData });
await fillOrderWrapper.fillOrderAndAssertEffectsAsync(signedOrder, takerAddress);
});

View File

@ -79,10 +79,10 @@ describe('AssetProxyDispatcher', () => {
txDefaults,
dependencyArtifacts,
);
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(assetProxyDispatcher.address, {
await erc20Proxy.addAuthorizedAddress(assetProxyDispatcher.address).awaitTransactionSuccessAsync({
from: owner,
});
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(assetProxyDispatcher.address, {
await erc721Proxy.addAuthorizedAddress(assetProxyDispatcher.address).awaitTransactionSuccessAsync({
from: owner,
});
});
@ -94,34 +94,34 @@ describe('AssetProxyDispatcher', () => {
});
describe('registerAssetProxy', () => {
it('should record proxy upon registration', async () => {
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20);
const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync();
expect(proxyAddress).to.be.equal(erc20Proxy.address);
});
it('should be able to record multiple proxies', async () => {
// Record first proxy
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
let proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20);
let proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync();
expect(proxyAddress).to.be.equal(erc20Proxy.address);
// Record another proxy
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC721);
proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC721).callAsync();
expect(proxyAddress).to.be.equal(erc721Proxy.address);
});
it('should revert if a proxy with the same id is already registered', async () => {
// Initial registration
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20);
const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync();
expect(proxyAddress).to.be.equal(erc20Proxy.address);
// Deploy a new version of the ERC20 Transfer Proxy contract
const newErc20TransferProxy = await ERC20ProxyContract.deployFrom0xArtifactAsync(
@ -131,7 +131,7 @@ describe('AssetProxyDispatcher', () => {
dependencyArtifacts,
);
const expectedError = new ExchangeRevertErrors.AssetProxyExistsError(AssetProxyId.ERC20, proxyAddress);
const tx = assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(newErc20TransferProxy.address, {
const tx = assetProxyDispatcher.registerAssetProxy(newErc20TransferProxy.address).sendTransactionAsync({
from: owner,
});
return expect(tx).to.revertWith(expectedError);
@ -139,7 +139,7 @@ describe('AssetProxyDispatcher', () => {
it('should revert if requesting address is not owner', async () => {
const expectedError = new OwnableRevertErrors.OnlyOwnerError(notOwner, owner);
const tx = assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, {
const tx = assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).sendTransactionAsync({
from: notOwner,
});
return expect(tx).to.revertWith(expectedError);
@ -147,7 +147,7 @@ describe('AssetProxyDispatcher', () => {
it('should revert if the proxy is not a contract address', async () => {
const errMessage = 'VM Exception while processing transaction: revert';
const tx = assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(notOwner, {
const tx = assetProxyDispatcher.registerAssetProxy(notOwner).sendTransactionAsync({
from: owner,
});
return expect(tx).to.be.rejectedWith(errMessage);
@ -156,7 +156,7 @@ describe('AssetProxyDispatcher', () => {
it('should log an event with correct arguments when an asset proxy is registered', async () => {
const logDecoder = new LogDecoder(web3Wrapper, artifacts);
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await assetProxyDispatcher.registerAssetProxy.sendTransactionAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).sendTransactionAsync({
from: owner,
}),
);
@ -169,15 +169,15 @@ describe('AssetProxyDispatcher', () => {
describe('getAssetProxy', () => {
it('should return correct address of registered proxy', async () => {
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20);
const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync();
expect(proxyAddress).to.be.equal(erc20Proxy.address);
});
it('should return NULL address if requesting non-existent proxy', async () => {
const proxyAddress = await assetProxyDispatcher.getAssetProxy.callAsync(AssetProxyId.ERC20);
const proxyAddress = await assetProxyDispatcher.getAssetProxy(AssetProxyId.ERC20).callAsync();
expect(proxyAddress).to.be.equal(constants.NULL_ADDRESS);
});
});
@ -186,23 +186,18 @@ describe('AssetProxyDispatcher', () => {
const orderHash = orderUtils.generatePseudoRandomOrderHash();
it('should dispatch transfer to registered proxy', async () => {
// Register ERC20 proxy
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
// Construct metadata for ERC20 proxy
const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
// Perform a transfer from makerAddress to takerAddress
const erc20Balances = await erc20Wrapper.getBalancesAsync();
const amount = new BigNumber(10);
await assetProxyDispatcher.dispatchTransferFrom.awaitTransactionSuccessAsync(
orderHash,
encodedAssetData,
makerAddress,
takerAddress,
amount,
{ from: owner },
);
await assetProxyDispatcher
.dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount)
.awaitTransactionSuccessAsync({ from: owner });
// Verify transfer was successful
const newBalances = await erc20Wrapper.getBalancesAsync();
expect(newBalances[makerAddress][erc20TokenA.address]).to.be.bignumber.equal(
@ -215,23 +210,18 @@ describe('AssetProxyDispatcher', () => {
it('should not dispatch a transfer if amount == 0', async () => {
// Register ERC20 proxy
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
// Construct metadata for ERC20 proxy
const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
// Perform a transfer from makerAddress to takerAddress
const erc20Balances = await erc20Wrapper.getBalancesAsync();
const amount = constants.ZERO_AMOUNT;
const txReceipt = await assetProxyDispatcher.dispatchTransferFrom.awaitTransactionSuccessAsync(
orderHash,
encodedAssetData,
makerAddress,
takerAddress,
amount,
{ from: owner },
);
const txReceipt = await assetProxyDispatcher
.dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount)
.awaitTransactionSuccessAsync({ from: owner });
expect(txReceipt.logs.length).to.be.equal(0);
const newBalances = await erc20Wrapper.getBalancesAsync();
expect(newBalances).to.deep.equal(erc20Balances);
@ -239,7 +229,7 @@ describe('AssetProxyDispatcher', () => {
it('should revert if dispatching to unregistered proxy', async () => {
// Construct metadata for ERC20 proxy
const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
// Perform a transfer from makerAddress to takerAddress
const amount = new BigNumber(10);
@ -248,70 +238,58 @@ describe('AssetProxyDispatcher', () => {
orderHash,
encodedAssetData,
);
const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync(
orderHash,
encodedAssetData,
makerAddress,
takerAddress,
amount,
{ from: owner },
);
const tx = assetProxyDispatcher
.dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount)
.sendTransactionAsync({ from: owner });
return expect(tx).to.revertWith(expectedError);
});
it('should revert with the correct error when assetData length < 4 bytes', async () => {
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
const encodedAssetData = (await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address)).slice(0, 8);
const encodedAssetData = (await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync()).slice(0, 8);
const amount = new BigNumber(1);
const expectedError = new ExchangeRevertErrors.AssetProxyDispatchError(
ExchangeRevertErrors.AssetProxyDispatchErrorCode.InvalidAssetDataLength,
orderHash,
encodedAssetData,
);
const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync(
orderHash,
encodedAssetData,
makerAddress,
takerAddress,
amount,
{ from: owner },
);
const tx = assetProxyDispatcher
.dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount)
.sendTransactionAsync({ from: owner });
return expect(tx).to.revertWith(expectedError);
});
it('should revert if assetData is not padded to 32 bytes (excluding the id)', async () => {
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
// Shave off the last byte
const encodedAssetData = (await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address)).slice(0, 72);
const encodedAssetData = (await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync()).slice(
0,
72,
);
const amount = new BigNumber(1);
const expectedError = new ExchangeRevertErrors.AssetProxyDispatchError(
ExchangeRevertErrors.AssetProxyDispatchErrorCode.InvalidAssetDataLength,
orderHash,
encodedAssetData,
);
const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync(
orderHash,
encodedAssetData,
makerAddress,
takerAddress,
amount,
{ from: owner },
);
const tx = assetProxyDispatcher
.dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount)
.sendTransactionAsync({ from: owner });
return expect(tx).to.revertWith(expectedError);
});
it('should revert with the reason provided by the AssetProxy when a transfer fails', async () => {
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
await erc20TokenA.approve.awaitTransactionSuccessAsync(erc20Proxy.address, constants.ZERO_AMOUNT, {
await erc20TokenA.approve(erc20Proxy.address, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({
from: makerAddress,
});
const encodedAssetData = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const encodedAssetData = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
const amount = new BigNumber(1);
const nestedError = new StringRevertError(RevertReason.TransferFailed).encode();
const expectedError = new ExchangeRevertErrors.AssetProxyTransferError(
@ -319,25 +297,20 @@ describe('AssetProxyDispatcher', () => {
encodedAssetData,
nestedError,
);
const tx = assetProxyDispatcher.dispatchTransferFrom.sendTransactionAsync(
orderHash,
encodedAssetData,
makerAddress,
takerAddress,
amount,
{ from: owner },
);
const tx = assetProxyDispatcher
.dispatchTransferFrom(orderHash, encodedAssetData, makerAddress, takerAddress, amount)
.sendTransactionAsync({ from: owner });
return expect(tx).to.revertWith(expectedError);
});
});
describe('simulateDispatchTransferFromCalls', () => {
it('should revert with the information specific to the failed transfer', async () => {
await assetProxyDispatcher.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await assetProxyDispatcher.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
const assetDataA = await devUtils.encodeERC20AssetData.callAsync(erc20TokenA.address);
const assetDataB = await devUtils.encodeERC20AssetData.callAsync(erc20TokenB.address);
await erc20TokenB.approve.awaitTransactionSuccessAsync(erc20Proxy.address, constants.ZERO_AMOUNT, {
const assetDataA = await devUtils.encodeERC20AssetData(erc20TokenA.address).callAsync();
const assetDataB = await devUtils.encodeERC20AssetData(erc20TokenB.address).callAsync();
await erc20TokenB.approve(erc20Proxy.address, constants.ZERO_AMOUNT).awaitTransactionSuccessAsync({
from: makerAddress,
});
const transferIndexAsBytes32 = '0x0000000000000000000000000000000000000000000000000000000000000001';
@ -347,59 +320,67 @@ describe('AssetProxyDispatcher', () => {
assetDataB,
nestedError,
);
const tx = assetProxyDispatcher.simulateDispatchTransferFromCalls.sendTransactionAsync(
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(
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(
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(
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);

View File

@ -25,7 +25,6 @@ blockchainTests('ExchangeTransferSimulator', env => {
let recipient: string;
let exampleAssetData: string;
let exchangeTransferSimulator: ExchangeTransferSimulator;
let txHash: string;
let erc20ProxyAddress: string;
const devUtils = new DevUtilsContract(constants.NULL_ADDRESS, env.provider);
before(async function(): Promise<void> {
@ -65,7 +64,7 @@ blockchainTests('ExchangeTransferSimulator', env => {
totalSupply,
);
exampleAssetData = await devUtils.encodeERC20AssetData.callAsync(dummyERC20Token.address);
exampleAssetData = await devUtils.encodeERC20AssetData(dummyERC20Token.address).callAsync();
});
beforeEach(async () => {
await env.blockchainLifecycle.startAsync();
@ -103,10 +102,9 @@ blockchainTests('ExchangeTransferSimulator', env => {
).to.be.rejectedWith(ExchangeContractErrs.InsufficientTakerAllowance);
});
it("throws if the user doesn't have enough balance", async () => {
txHash = await dummyERC20Token.approve.sendTransactionAsync(erc20ProxyAddress, transferAmount, {
await dummyERC20Token.approve(erc20ProxyAddress, transferAmount).awaitTransactionSuccessAsync({
from: sender,
});
await env.web3Wrapper.awaitTransactionSuccessAsync(txHash);
return expect(
exchangeTransferSimulator.transferFromAsync(
exampleAssetData,
@ -119,15 +117,12 @@ blockchainTests('ExchangeTransferSimulator', env => {
).to.be.rejectedWith(ExchangeContractErrs.InsufficientMakerBalance);
});
it('updates balances and proxyAllowance after transfer', async () => {
txHash = await dummyERC20Token.transfer.sendTransactionAsync(sender, transferAmount, {
await dummyERC20Token.transfer(sender, transferAmount).awaitTransactionSuccessAsync({
from: coinbase,
});
await env.web3Wrapper.awaitTransactionSuccessAsync(txHash);
txHash = await dummyERC20Token.approve.sendTransactionAsync(erc20ProxyAddress, transferAmount, {
await dummyERC20Token.approve(erc20ProxyAddress, transferAmount).awaitTransactionSuccessAsync({
from: sender,
});
await env.web3Wrapper.awaitTransactionSuccessAsync(txHash);
await exchangeTransferSimulator.transferFromAsync(
exampleAssetData,
@ -146,18 +141,14 @@ blockchainTests('ExchangeTransferSimulator', env => {
expect(senderProxyAllowance).to.be.bignumber.equal(0);
});
it("doesn't update proxyAllowance after transfer if unlimited", async () => {
txHash = await dummyERC20Token.transfer.sendTransactionAsync(sender, transferAmount, {
await dummyERC20Token.transfer(sender, transferAmount).awaitTransactionSuccessAsync({
from: coinbase,
});
await env.web3Wrapper.awaitTransactionSuccessAsync(txHash);
txHash = await dummyERC20Token.approve.sendTransactionAsync(
erc20ProxyAddress,
constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
{
await dummyERC20Token
.approve(erc20ProxyAddress, constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)
.awaitTransactionSuccessAsync({
from: sender,
},
);
await env.web3Wrapper.awaitTransactionSuccessAsync(txHash);
});
await exchangeTransferSimulator.transferFromAsync(
exampleAssetData,
sender,

View File

@ -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(
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<TestExchangeInternalsDispatchTransferFromCalledEventArgs>
>;
@ -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(
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(
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<TestExchangeInternalsDispatchTransferFromCalledEventArgs>
>;
@ -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<TestExchangeInternalsDispatchTransferFromCalledEventArgs>
>;

View File

@ -14,7 +14,7 @@ import * as _ from 'lodash';
import { artifacts } from './artifacts';
import { TestLibExchangeRichErrorDecoderContract } from './wrappers';
blockchainTests.resets('LibExchangeRichErrorDecoder', ({ provider, txDefaults }) => {
blockchainTests.resets.only('LibExchangeRichErrorDecoder', ({ provider, txDefaults }) => {
const ASSET_PROXY_ID_LENGTH = 4;
const SIGNATURE_LENGTH = 66;
const ASSET_DATA_LENGTH = 36;
@ -38,7 +38,7 @@ blockchainTests.resets('LibExchangeRichErrorDecoder', ({ provider, txDefaults })
// Solidity counterparts.
const endpointName = `decode${revert.name}`;
const callAsync = (_encoded: string) => {
return (decoder as any)[endpointName].callAsync.call((decoder as any)[endpointName], _encoded);
return (decoder as any)[endpointName](_encoded).callAsync.call((decoder as any)[endpointName]);
};
describe(`${endpointName}()`, async () => {
it('decodes encoded parameters', async () => {

View File

@ -146,28 +146,28 @@ describe('matchOrders', () => {
await exchangeWrapper.registerAssetProxyAsync(erc1155Proxy.address, owner);
await exchangeWrapper.registerAssetProxyAsync(multiAssetProxyContract.address, owner);
// Authorize proxies.
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await multiAssetProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(exchange.address, {
await erc20Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await erc721Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await erc1155Proxy.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
await multiAssetProxyContract.addAuthorizedAddress(exchange.address).awaitTransactionSuccessAsync({
from: owner,
});
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxyContract.address, {
await erc20Proxy.addAuthorizedAddress(multiAssetProxyContract.address).awaitTransactionSuccessAsync({
from: owner,
});
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxyContract.address, {
await erc721Proxy.addAuthorizedAddress(multiAssetProxyContract.address).awaitTransactionSuccessAsync({
from: owner,
});
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxyContract.address, {
await erc1155Proxy.addAuthorizedAddress(multiAssetProxyContract.address).awaitTransactionSuccessAsync({
from: owner,
});
await multiAssetProxyContract.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await multiAssetProxyContract.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
await multiAssetProxyContract.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, {
await multiAssetProxyContract.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
await multiAssetProxyContract.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, {
await multiAssetProxyContract.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
@ -182,10 +182,10 @@ describe('matchOrders', () => {
const defaultOrderParamsLeft = {
...constants.STATIC_ORDER_PARAMS,
makerAddress: makerAddressLeft,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress),
takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(),
takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(),
feeRecipientAddress: feeRecipientAddressLeft,
exchangeAddress: exchange.address,
chainId,
@ -193,10 +193,10 @@ describe('matchOrders', () => {
const defaultOrderParamsRight = {
...constants.STATIC_ORDER_PARAMS,
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress),
takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultFeeTokenAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(),
takerFeeAssetData: await devUtils.encodeERC20AssetData(defaultFeeTokenAddress).callAsync(),
feeRecipientAddress: feeRecipientAddressRight,
exchangeAddress: exchange.address,
chainId,
@ -349,8 +349,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(83, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(49, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -403,8 +403,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -454,8 +454,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(83, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(49, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -503,8 +503,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -548,8 +548,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(2126, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1063, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -1173,7 +1173,7 @@ describe('matchOrders', () => {
const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
feeRecipientAddress: makerAddressLeft,
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
@ -1270,7 +1270,7 @@ describe('matchOrders', () => {
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(2, 18),
});
@ -1297,7 +1297,7 @@ describe('matchOrders', () => {
it('should revert if the right maker asset is not equal to the left taker asset', async () => {
// Create orders to match
const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
});
@ -1451,8 +1451,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(87, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(48, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -1539,8 +1539,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -1590,8 +1590,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(87, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(48, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -1636,8 +1636,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -1681,8 +1681,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(89, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -1800,8 +1800,8 @@ describe('matchOrders', () => {
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
makerAddress: makerAddressRight,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(2126, 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(1063, 0),
feeRecipientAddress: feeRecipientAddressRight,
@ -2254,7 +2254,7 @@ describe('matchOrders', () => {
const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
makerFeeAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
feeRecipientAddress: makerAddressLeft,
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
@ -2351,7 +2351,7 @@ describe('matchOrders', () => {
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
});
const signedOrderRight = await orderFactoryRight.newSignedOrderAsync({
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(2, 18),
});
@ -2378,7 +2378,7 @@ describe('matchOrders', () => {
it('should revert if the right maker asset is not equal to the left taker asset', async () => {
// Create orders to match
const signedOrderLeft = await orderFactoryLeft.newSignedOrderAsync({
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(5, 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(10, 18),
});
@ -2687,29 +2687,29 @@ describe('matchOrders', () => {
let nameToMultiAssetAsset: { [name: string]: [BigNumber[], string[]] };
async function getAssetDataAsync(assetType: AssetType): Promise<string> {
const encodeERC20AssetData = await devUtils.encodeERC20AssetData.callAsync;
const encodeERC721AssetData = await devUtils.encodeERC721AssetData.callAsync;
const encodeERC1155AssetData = await devUtils.encodeERC1155AssetData.callAsync;
const encodeMultiAssetData = await devUtils.encodeMultiAssetData.callAsync;
if (nameToERC20Asset[assetType] !== undefined) {
const tokenAddress = nameToERC20Asset[assetType];
return encodeERC20AssetData(tokenAddress);
return devUtils.encodeERC20AssetData(tokenAddress).callAsync();
}
if (nameToERC721Asset[assetType] !== undefined) {
const [tokenAddress, tokenId] = nameToERC721Asset[assetType];
return encodeERC721AssetData(tokenAddress, tokenId);
return devUtils.encodeERC721AssetData(tokenAddress, tokenId).callAsync();
}
if (nameToERC1155FungibleAsset[assetType] !== undefined) {
const [tokenAddress, tokenId] = nameToERC1155FungibleAsset[assetType];
return encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES);
return devUtils
.encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES)
.callAsync();
}
if (nameToERC1155NonFungibleAsset[assetType] !== undefined) {
const [tokenAddress, tokenId] = nameToERC1155NonFungibleAsset[assetType];
return encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES);
return devUtils
.encodeERC1155AssetData(tokenAddress, [tokenId], [ONE], constants.NULL_BYTES)
.callAsync();
}
if (nameToMultiAssetAsset[assetType] !== undefined) {
const [amounts, nestedAssetData] = nameToMultiAssetAsset[assetType];
return encodeMultiAssetData(amounts, nestedAssetData);
return devUtils.encodeMultiAssetData(amounts, nestedAssetData).callAsync();
}
throw new Error(`Unknown asset type: ${assetType}`);
}
@ -2755,49 +2755,57 @@ describe('matchOrders', () => {
MULTI_ASSET_A: [
[ONE, TWO],
[
await devUtils.encodeERC20AssetData.callAsync(erc20Tokens[0].address),
await devUtils.encodeERC1155AssetData.callAsync(
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(
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(
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(
await devUtils.encodeERC20AssetData(erc20Tokens[3].address).callAsync(),
await devUtils
.encodeERC1155AssetData(
erc1155Token.address,
[erc1155FungibleTokens[3]],
[ONE],
constants.NULL_BYTES,
),
)
.callAsync(),
],
],
};

View File

@ -32,244 +32,223 @@ blockchainTests('Protocol Fee Payments', env => {
blockchainTests.resets('fillOrder Protocol Fees', () => {
it('should not pay protocol fee when there is no registered protocol fee collector', async () => {
await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
false,
{
await testProtocolFeesReceiver
.testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, false)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE,
},
);
});
});
it('should not forward ETH when too little value is sent', async () => {
await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE.minus(10),
},
);
});
});
it('should pay protocol fee in ETH when the correct value is sent', async () => {
await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE,
},
);
});
});
it('should pay protocol fee in ETH when extra value is sent', async () => {
await testProtocolFeesReceiver.testFillOrderProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testFillOrderProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE.plus(10),
},
);
});
});
});
blockchainTests.resets('matchOrders Protocol Fees', () => {
it('should not pay protocol fee when there is no registered protocol fee collector', async () => {
await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
false,
{
await testProtocolFeesReceiver
.testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, false)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE,
},
);
});
});
it('should not forward ETH twice when too little value is sent', async () => {
await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE.minus(10),
},
);
});
});
it('should pay protocol fee in ETH and then not forward ETH when exactly one protocol fee is sent', async () => {
await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE,
},
);
});
});
it('should pay protocol fee in ETH and then not forward ETH when a bit more than one protocol fee is sent', async () => {
await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE.plus(10),
},
);
});
});
it('should pay protocol fee in ETH when exactly double the protocol fee is sent', async () => {
await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE.times(2),
},
);
});
});
it('should pay protocol fee in ETH when more than double the protocol fee is sent', async () => {
await testProtocolFeesReceiver.testMatchOrdersProtocolFees.awaitTransactionSuccessAsync(
testProtocolFees.address,
DEFAULT_PROTOCOL_FEE_MULTIPLIER,
true,
{
await testProtocolFeesReceiver
.testMatchOrdersProtocolFees(testProtocolFees.address, DEFAULT_PROTOCOL_FEE_MULTIPLIER, true)
.awaitTransactionSuccessAsync({
gasPrice: DEFAULT_GAS_PRICE,
value: DEFAULT_PROTOCOL_FEE.times(2).plus(10),
},
);
});
});
});
blockchainTests.resets('batchFillOrder ProtocolFees', () => {
it('should not pay protocol fees when there is not a protocolFeeCollector registered', async () => {
await testProtocolFeesReceiver.testBatchFillOrdersProtocolFees.awaitTransactionSuccessAsync(
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(
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(
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(
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(
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(
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(
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(
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(
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),
},
);
});
});
});
});

View File

@ -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.

View File

@ -102,8 +102,8 @@ blockchainTests.resets('Reentrancy Tests', env => {
for (const fn of NON_REENTRANT_FUNCTIONS) {
it(`${fn.name}()`, async () => {
const inputs = createFunctionInputs(fn.inputs);
const callData = (testerContract as any)[fn.name].getABIEncodedTransactionData(...inputs);
const isReentrant = await testerContract.isReentrant.callAsync(callData);
const callData = (testerContract as any)[fn.name](...inputs).getABIEncodedTransactionData();
const isReentrant = await testerContract.isReentrant(callData).callAsync();
expect(isReentrant).to.be.false();
});
}
@ -113,8 +113,8 @@ blockchainTests.resets('Reentrancy Tests', env => {
for (const fn of REENTRANT_FUNCTIONS) {
it(`${fn.name}()`, async () => {
const inputs = createFunctionInputs(fn.inputs);
const callData = (testerContract as any)[fn.name].getABIEncodedTransactionData(...inputs);
const isReentrant = await testerContract.isReentrant.callAsync(callData);
const callData = (testerContract as any)[fn.name](...inputs).getABIEncodedTransactionData();
const isReentrant = await testerContract.isReentrant(callData).callAsync();
expect(isReentrant).to.be.true();
});
}

View File

@ -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

View File

@ -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(
const returnData = await exchangeInstance
.batchExecuteTransactions(
[transaction1, transaction2],
[transaction1.signature, transaction2.signature],
{ from: senderAddress },
);
)
.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(
const returnData = await exchangeInstance
.batchExecuteTransactions(
[transaction1, transaction2],
[transaction1.signature, transaction2.signature],
{ from: senderAddress },
);
)
.callAsync({ from: senderAddress });
const abi = artifacts.Exchange.compilerOutput.abi;
const methodAbi = abi.filter(
abiItem => (abiItem as MethodAbi).name === ExchangeFunctionName.FillOrder,

View File

@ -1,4 +1,4 @@
import { blockchainTests, constants, describe, expect, hexRandom, TransactionHelper } from '@0x/contracts-test-utils';
import { blockchainTests, constants, describe, expect, hexRandom } from '@0x/contracts-test-utils';
import { ExchangeRevertErrors, transactionHashUtils } from '@0x/order-utils';
import { EIP712DomainWithDefaultSchema, ZeroExTransaction } from '@0x/types';
import { BigNumber, StringRevertError } from '@0x/utils';
@ -30,8 +30,6 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
const DEADBEEF_RETURN_DATA = '0xdeadbeef';
const INVALID_SIGNATURE = '0x0000';
const transactionHelper = new TransactionHelper(web3Wrapper, artifacts);
before(async () => {
// A list of available addresses to use during testing.
accounts = await web3Wrapper.getAvailableAddressesAsync();
@ -55,11 +53,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
* Generates calldata for a call to `executable()` in the `TestTransactions` contract.
*/
function getExecutableCallData(shouldSucceed: boolean, callData: string, returnData: string): string {
return (transactionsContract as any).executable.getABIEncodedTransactionData(
shouldSucceed,
callData,
returnData,
);
return (transactionsContract as any)
.executable(shouldSucceed, callData, returnData)
.getABIEncodedTransactionData();
}
interface GenerateZeroExTransactionParams {
@ -110,10 +106,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
);
// Call the `batchExecuteTransactions()` function and ensure that it reverts with the expected revert error.
const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync(
[transaction],
[randomSignature()],
);
const tx = transactionsContract
.batchExecuteTransactions([transaction], [randomSignature()])
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -133,10 +128,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
);
// Call the `batchExecuteTransactions()` function and ensure that it reverts with the expected revert error.
const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync(
[transaction1, transaction2],
[randomSignature(), randomSignature()],
);
const tx = transactionsContract
.batchExecuteTransactions([transaction1, transaction2], [randomSignature(), randomSignature()])
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -156,10 +150,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
);
// Call the `batchExecuteTransactions()` function and ensure that it reverts with the expected revert error.
const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync(
[transaction1, transaction2],
[randomSignature(), randomSignature()],
);
const tx = transactionsContract
.batchExecuteTransactions([transaction1, transaction2], [randomSignature(), randomSignature()])
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -177,13 +170,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
ExchangeRevertErrors.TransactionErrorCode.AlreadyExecuted,
transactionHash2,
);
const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync(
[transaction1, transaction2],
[randomSignature(), randomSignature()],
{
const tx = transactionsContract
.batchExecuteTransactions([transaction1, transaction2], [randomSignature(), randomSignature()])
.awaitTransactionSuccessAsync({
from: accounts[0],
},
);
});
return expect(tx).to.revertWith(expectedError);
});
@ -196,15 +187,12 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const validSignature = randomSignature();
const [result, receipt] = await transactionHelper.getResultAndReceiptAsync(
transactionsContract.batchExecuteTransactions,
[transaction],
[validSignature],
{ from: accounts[0] },
);
const contractFn = transactionsContract.batchExecuteTransactions([transaction], [validSignature]);
const result = await contractFn.callAsync({ from: accounts[0] });
const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] });
expect(result.length).to.be.eq(1);
const returnData = transactionsContract.executeTransaction.getABIDecodedReturnData(result[0]);
const returnData = transactionsContract.getABIDecodedReturnData<void>('executeTransaction', result[0]);
expect(returnData).to.equal(DEADBEEF_RETURN_DATA);
// Ensure that the correct number of events were logged.
@ -234,18 +222,18 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
const transactionHash1 = transactionHashUtils.getTransactionHashHex(transaction1);
const transactionHash2 = transactionHashUtils.getTransactionHashHex(transaction2);
const [result, receipt] = await transactionHelper.getResultAndReceiptAsync(
transactionsContract.batchExecuteTransactions,
const contractFn = transactionsContract.batchExecuteTransactions(
[transaction1, transaction2],
[randomSignature(), randomSignature()],
{ from: accounts[0] },
);
const result = await contractFn.callAsync({ from: accounts[0] });
const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] });
expect(result.length).to.be.eq(2);
expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result[0])).to.equal(
expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result[0])).to.equal(
DEADBEEF_RETURN_DATA,
);
expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result[1])).to.equal(returnData2);
expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result[1])).to.equal(returnData2);
// Verify that the correct number of events were logged.
const logs = receipt.logs as Array<LogWithDecodedArgs<TestTransactionsTransactionExecutionEventArgs>>;
@ -270,17 +258,18 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
const innerTransaction2 = await generateZeroExTransactionAsync({ signerAddress: accounts[1] });
const innerBatchExecuteTransaction = await generateZeroExTransactionAsync({
signerAddress: accounts[2],
callData: transactionsContract.batchExecuteTransactions.getABIEncodedTransactionData(
callData: transactionsContract
.batchExecuteTransactions(
[innerTransaction1, innerTransaction2],
[randomSignature(), randomSignature()],
),
)
.getABIEncodedTransactionData(),
});
const outerExecuteTransaction = await generateZeroExTransactionAsync({
signerAddress: accounts[1],
callData: transactionsContract.executeTransaction.getABIEncodedTransactionData(
innerBatchExecuteTransaction,
randomSignature(),
),
callData: transactionsContract
.executeTransaction(innerBatchExecuteTransaction, randomSignature())
.getABIEncodedTransactionData(),
});
const innerBatchExecuteTransactionHash = transactionHashUtils.getTransactionHashHex(
innerBatchExecuteTransaction,
@ -294,11 +283,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
outerExecuteTransactionHash,
innerExpectedError.encode(),
);
const tx = transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync(
[outerExecuteTransaction],
[randomSignature()],
{ from: accounts[2] },
);
const tx = transactionsContract
.batchExecuteTransactions([outerExecuteTransaction], [randomSignature()])
.awaitTransactionSuccessAsync({ from: accounts[2] });
return expect(tx).to.revertWith(outerExpectedError);
});
it('should allow recursion as long as currentContextAddress is not set', async () => {
@ -307,34 +294,32 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
// From this point on, all transactions and calls will have the same sender, which does not change currentContextAddress when called
const innerBatchExecuteTransaction = await generateZeroExTransactionAsync({
signerAddress: accounts[2],
callData: transactionsContract.batchExecuteTransactions.getABIEncodedTransactionData(
callData: transactionsContract
.batchExecuteTransactions(
[innerTransaction1, innerTransaction2],
[randomSignature(), randomSignature()],
),
)
.getABIEncodedTransactionData(),
});
const outerExecuteTransaction = await generateZeroExTransactionAsync({
signerAddress: accounts[2],
callData: transactionsContract.executeTransaction.getABIEncodedTransactionData(
innerBatchExecuteTransaction,
randomSignature(),
),
callData: transactionsContract
.executeTransaction(innerBatchExecuteTransaction, randomSignature())
.getABIEncodedTransactionData(),
});
return expect(
transactionsContract.batchExecuteTransactions.awaitTransactionSuccessAsync(
[outerExecuteTransaction],
[randomSignature()],
{ from: accounts[2] },
),
transactionsContract
.batchExecuteTransactions([outerExecuteTransaction], [randomSignature()])
.awaitTransactionSuccessAsync({ from: accounts[2] }),
).to.be.fulfilled('');
});
});
describe('executeTransaction', () => {
function getExecuteTransactionCallData(transaction: ZeroExTransaction, signature: string): string {
return (transactionsContract as any).executeTransaction.getABIEncodedTransactionData(
transaction,
signature,
);
return (transactionsContract as any)
.executeTransaction(transaction, signature)
.getABIEncodedTransactionData();
}
it('should revert if the current time is past the expiration time', async () => {
const transaction = await generateZeroExTransactionAsync({
@ -345,10 +330,9 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
ExchangeRevertErrors.TransactionErrorCode.Expired,
transactionHash,
);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
transaction,
randomSignature(),
);
const tx = transactionsContract
.executeTransaction(transaction, randomSignature())
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
it('should revert if the transaction is submitted with a gasPrice that does not equal the required gasPrice', async () => {
@ -360,13 +344,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
actualGasPrice,
transaction.gasPrice,
);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
transaction,
randomSignature(),
{
const tx = transactionsContract
.executeTransaction(transaction, randomSignature())
.awaitTransactionSuccessAsync({
gasPrice: actualGasPrice,
},
);
});
return expect(tx).to.revertWith(expectedError);
});
it('should revert if reentrancy occurs in the middle of an executeTransaction call and msg.sender != signer for both calls', async () => {
@ -384,13 +366,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
accounts[0],
).encode();
const expectedError = new ExchangeRevertErrors.TransactionExecutionError(outerTransactionHash, errorData);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
outerTransaction,
validSignature,
{
const tx = transactionsContract
.executeTransaction(outerTransaction, validSignature)
.awaitTransactionSuccessAsync({
from: accounts[1], // Different then the signing addresses
},
);
});
return expect(tx).to.revertWith(expectedError);
});
it('should revert if reentrancy occurs in the middle of an executeTransaction call and msg.sender != signer and then msg.sender == signer', async () => {
@ -408,13 +388,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
accounts[0],
).encode();
const expectedError = new ExchangeRevertErrors.TransactionExecutionError(outerTransactionHash, errorData);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
outerTransaction,
validSignature,
{
const tx = transactionsContract
.executeTransaction(outerTransaction, validSignature)
.awaitTransactionSuccessAsync({
from: accounts[1], // Different then the signing addresses
},
);
});
return expect(tx).to.revertWith(expectedError);
});
it('should allow reentrancy in the middle of an executeTransaction call if msg.sender == signer for both calls', async () => {
@ -426,7 +404,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
returnData: DEADBEEF_RETURN_DATA,
});
return expect(
transactionsContract.executeTransaction.awaitTransactionSuccessAsync(outerTransaction, validSignature, {
transactionsContract.executeTransaction(outerTransaction, validSignature).awaitTransactionSuccessAsync({
from: accounts[0],
}),
).to.be.fulfilled('');
@ -440,7 +418,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
returnData: DEADBEEF_RETURN_DATA,
});
return expect(
transactionsContract.executeTransaction.awaitTransactionSuccessAsync(outerTransaction, validSignature, {
transactionsContract.executeTransaction(outerTransaction, validSignature).awaitTransactionSuccessAsync({
from: accounts[0],
}),
).to.be.fulfilled('');
@ -451,17 +429,16 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
// Use the transaction in execute transaction.
await expect(
transactionsContract.executeTransaction.awaitTransactionSuccessAsync(transaction, validSignature),
transactionsContract.executeTransaction(transaction, validSignature).awaitTransactionSuccessAsync(),
).to.be.fulfilled('');
// Use the same transaction to make another call
const expectedError = new ExchangeRevertErrors.TransactionError(
ExchangeRevertErrors.TransactionErrorCode.AlreadyExecuted,
transactionHash,
);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
transaction,
validSignature,
);
const tx = transactionsContract
.executeTransaction(transaction, validSignature)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
it('should revert if the signer != msg.sender and the signature is not valid', async () => {
@ -473,13 +450,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
accounts[1],
INVALID_SIGNATURE,
);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
transaction,
INVALID_SIGNATURE,
{
const tx = transactionsContract
.executeTransaction(transaction, INVALID_SIGNATURE)
.awaitTransactionSuccessAsync({
from: accounts[0],
},
);
});
return expect(tx).to.revertWith(expectedError);
});
it('should revert if the signer == msg.sender but the delegatecall fails', async () => {
@ -494,13 +469,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
transactionHash,
executableError.encode(),
);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
transaction,
randomSignature(),
{
const tx = transactionsContract
.executeTransaction(transaction, randomSignature())
.awaitTransactionSuccessAsync({
from: accounts[1],
},
);
});
return expect(tx).to.revertWith(expectedError);
});
it('should revert if the signer != msg.sender and the signature is valid but the delegatecall fails', async () => {
@ -516,13 +489,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
transactionHash,
executableError.encode(),
);
const tx = transactionsContract.executeTransaction.awaitTransactionSuccessAsync(
transaction,
validSignature,
{
const tx = transactionsContract
.executeTransaction(transaction, validSignature)
.awaitTransactionSuccessAsync({
from: accounts[0],
},
);
});
return expect(tx).to.revertWith(expectedError);
});
it('should succeed with the correct return hash and event emitted when msg.sender != signer', async () => {
@ -534,14 +505,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
});
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const [result, receipt] = await transactionHelper.getResultAndReceiptAsync(
transactionsContract.executeTransaction,
transaction,
validSignature,
{ from: accounts[0] },
);
const contractFn = transactionsContract.executeTransaction(transaction, validSignature);
const result = await contractFn.callAsync({ from: accounts[0] });
expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result)).to.equal(
const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] });
expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result)).to.equal(
DEADBEEF_RETURN_DATA,
);
@ -565,14 +533,11 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
});
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const [result, receipt] = await transactionHelper.getResultAndReceiptAsync(
transactionsContract.executeTransaction,
transaction,
validSignature,
{ from: accounts[0] },
);
const contractFn = transactionsContract.executeTransaction(transaction, validSignature);
const result = await contractFn.callAsync({ from: accounts[0] });
expect(transactionsContract.executeTransaction.getABIDecodedReturnData(result)).to.equal(
const receipt = await contractFn.awaitTransactionSuccessAsync({ from: accounts[0] });
expect(transactionsContract.getABIDecodedReturnData('executeTransaction', result)).to.equal(
DEADBEEF_RETURN_DATA,
);
@ -600,7 +565,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
transactionHash,
);
expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature()),
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync(),
).to.revertWith(expectedError);
});
it('should revert if the gasPrice is less than required', async () => {
@ -613,7 +578,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
transaction.gasPrice,
);
expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), {
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({
gasPrice: actualGasPrice,
}),
).to.revertWith(expectedError);
@ -628,30 +593,30 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
transaction.gasPrice,
);
expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), {
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({
gasPrice: actualGasPrice,
}),
).to.revertWith(expectedError);
});
it('should revert if currentContextAddress is non-zero', async () => {
await transactionsContract.setCurrentContextAddress.awaitTransactionSuccessAsync(accounts[0]);
await transactionsContract.setCurrentContextAddress(accounts[0]).awaitTransactionSuccessAsync();
const transaction = await generateZeroExTransactionAsync();
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const expectedError = new ExchangeRevertErrors.TransactionInvalidContextError(transactionHash, accounts[0]);
expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature()),
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync(),
).to.revertWith(expectedError);
});
it('should revert if the transaction has already been executed', async () => {
const transaction = await generateZeroExTransactionAsync();
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
await transactionsContract.setTransactionExecuted.awaitTransactionSuccessAsync(transactionHash);
await transactionsContract.setTransactionExecuted(transactionHash).awaitTransactionSuccessAsync();
const expectedError = new ExchangeRevertErrors.TransactionError(
ExchangeRevertErrors.TransactionErrorCode.AlreadyExecuted,
transactionHash,
);
expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature()),
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync(),
).to.revertWith(expectedError);
});
it('should revert if signer != msg.sender and the signature is invalid', async () => {
@ -664,7 +629,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
INVALID_SIGNATURE,
);
expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, INVALID_SIGNATURE, {
transactionsContract.assertExecutableTransaction(transaction, INVALID_SIGNATURE).callAsync({
from: accounts[1],
}),
).to.revertWith(expectedError);
@ -672,7 +637,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
it('should be successful if signer == msg.sender and the signature is invalid', async () => {
const transaction = await generateZeroExTransactionAsync({ signerAddress: accounts[0] });
return expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, INVALID_SIGNATURE, {
transactionsContract.assertExecutableTransaction(transaction, INVALID_SIGNATURE).callAsync({
from: accounts[0],
}),
).to.be.fulfilled('');
@ -680,7 +645,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
it('should be successful if signer == msg.sender and the signature is valid', async () => {
const transaction = await generateZeroExTransactionAsync({ signerAddress: accounts[0] });
return expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), {
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({
from: accounts[0],
}),
).to.be.fulfilled('');
@ -688,7 +653,7 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
it('should be successful if not expired, the gasPrice is correct, the tx has not been executed, currentContextAddress has not been set, signer != msg.sender, and the signature is valid', async () => {
const transaction = await generateZeroExTransactionAsync({ signerAddress: accounts[0] });
return expect(
transactionsContract.assertExecutableTransaction.callAsync(transaction, randomSignature(), {
transactionsContract.assertExecutableTransaction(transaction, randomSignature()).callAsync({
from: accounts[1],
}),
).to.be.fulfilled('');
@ -698,30 +663,27 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
describe('setCurrentContextAddressIfRequired', () => {
it('should set the currentContextAddress if signer not equal to sender', async () => {
const randomAddress = hexRandom(20);
await transactionsContract.setCurrentContextAddressIfRequired.awaitTransactionSuccessAsync(
randomAddress,
randomAddress,
);
const currentContextAddress = await transactionsContract.currentContextAddress.callAsync();
await transactionsContract
.setCurrentContextAddressIfRequired(randomAddress, randomAddress)
.awaitTransactionSuccessAsync();
const currentContextAddress = await transactionsContract.currentContextAddress().callAsync();
expect(currentContextAddress).to.eq(randomAddress);
});
it('should not set the currentContextAddress if signer equal to sender', async () => {
const randomAddress = hexRandom(20);
await transactionsContract.setCurrentContextAddressIfRequired.awaitTransactionSuccessAsync(
accounts[0],
randomAddress,
{
await transactionsContract
.setCurrentContextAddressIfRequired(accounts[0], randomAddress)
.awaitTransactionSuccessAsync({
from: accounts[0],
},
);
const currentContextAddress = await transactionsContract.currentContextAddress.callAsync();
});
const currentContextAddress = await transactionsContract.currentContextAddress().callAsync();
expect(currentContextAddress).to.eq(constants.NULL_ADDRESS);
});
});
describe('getCurrentContext', () => {
it('should return the sender address when there is not a saved context address', async () => {
const currentContextAddress = await transactionsContract.getCurrentContextAddress.callAsync({
const currentContextAddress = await transactionsContract.getCurrentContextAddress().callAsync({
from: accounts[0],
});
expect(currentContextAddress).to.be.eq(accounts[0]);
@ -729,10 +691,10 @@ blockchainTests.resets('Transaction Unit Tests', ({ provider, web3Wrapper, txDef
it('should return the sender address when there is a saved context address', async () => {
// Set the current context address to the taker address
await transactionsContract.setCurrentContextAddress.awaitTransactionSuccessAsync(accounts[1]);
await transactionsContract.setCurrentContextAddress(accounts[1]).awaitTransactionSuccessAsync();
// Ensure that the queried current context address is the same as the address that was set.
const currentContextAddress = await transactionsContract.getCurrentContextAddress.callAsync({
const currentContextAddress = await transactionsContract.getCurrentContextAddress().callAsync({
from: accounts[0],
});
expect(currentContextAddress).to.be.eq(accounts[1]);

View File

@ -10,11 +10,11 @@ export class AssetBalanceAndProxyAllowanceFetcher implements AbstractBalanceAndP
this._devUtilsContract = devUtilsContract;
}
public async getBalanceAsync(assetData: string, userAddress: string): Promise<BigNumber> {
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<BigNumber> {
const proxyAllowance = await this._devUtilsContract.getAssetProxyAllowance.callAsync(userAddress, assetData);
const proxyAllowance = await this._devUtilsContract.getAssetProxyAllowance(userAddress, assetData).callAsync();
return proxyAllowance;
}
}

View File

@ -32,7 +32,7 @@ export class AssetWrapper {
});
}
public async getBalanceAsync(userAddress: string, assetData: string): Promise<BigNumber> {
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<void> {
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<void> {
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<BigNumber> {
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<void> {
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),

View File

@ -77,7 +77,7 @@ export class ExchangeTransferSimulator {
tradeSide: TradeSide,
transferType: TransferType,
): Promise<void> {
const assetProxyId = await this._devUtils.decodeAssetProxyId.callAsync(assetData);
const assetProxyId = await this._devUtils.decodeAssetProxyId(assetData).callAsync();
switch (assetProxyId) {
case AssetProxyId.ERC1155:
case AssetProxyId.ERC20:
@ -110,7 +110,7 @@ export class ExchangeTransferSimulator {
break;
}
case AssetProxyId.MultiAsset: {
const decodedAssetData = await this._devUtils.decodeMultiAssetData.callAsync(assetData);
const decodedAssetData = await this._devUtils.decodeMultiAssetData(assetData).callAsync();
await this._decreaseBalanceAsync(assetData, from, amountInBaseUnits);
await this._increaseBalanceAsync(assetData, to, amountInBaseUnits);
for (const [index, nestedAssetDataElement] of decodedAssetData[2].entries()) {

View File

@ -24,17 +24,14 @@ export class ExchangeWrapper {
opts: { takerAssetFillAmount?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.batchFillOrders.awaitTransactionSuccessAsync(
return this.exchangeContract
.batchFillOrders(
orders,
opts.takerAssetFillAmounts === undefined
? orders.map(signedOrder => signedOrder.takerAssetAmount)
: opts.takerAssetFillAmounts,
orders.map(signedOrder => signedOrder.signature),
{ from, gasPrice: opts.gasPrice },
);
)
.awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice });
}
public async batchFillOrKillOrdersAsync(
orders: SignedOrder[],
from: string,
opts: { takerAssetFillAmounts?: BigNumber[]; gasPrice?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.batchFillOrKillOrders.awaitTransactionSuccessAsync(
return this.exchangeContract
.batchFillOrKillOrders(
orders,
opts.takerAssetFillAmounts === undefined
? orders.map(signedOrder => signedOrder.takerAssetAmount)
: opts.takerAssetFillAmounts,
orders.map(signedOrder => signedOrder.signature),
{ from, gasPrice: opts.gasPrice },
);
)
.awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice });
}
public async batchFillOrdersNoThrowAsync(
orders: SignedOrder[],
from: string,
opts: { takerAssetFillAmounts?: BigNumber[]; gas?: number; gasPrice?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.batchFillOrdersNoThrow.awaitTransactionSuccessAsync(
return this.exchangeContract
.batchFillOrdersNoThrow(
orders,
opts.takerAssetFillAmounts === undefined
? orders.map(signedOrder => signedOrder.takerAssetAmount)
: opts.takerAssetFillAmounts,
orders.map(signedOrder => signedOrder.signature),
{ from, gas: opts.gas, gasPrice: opts.gasPrice },
);
)
.awaitTransactionSuccessAsync({ from, gas: opts.gas, gasPrice: opts.gasPrice });
}
public async marketSellOrdersNoThrowAsync(
orders: SignedOrder[],
from: string,
opts: { takerAssetFillAmount: BigNumber; gas?: number; gasPrice?: BigNumber },
): Promise<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.marketSellOrdersNoThrow.awaitTransactionSuccessAsync(
return this.exchangeContract
.marketSellOrdersNoThrow(
orders,
opts.takerAssetFillAmount,
orders.map(signedOrder => signedOrder.signature),
{ from, gas: opts.gas, gasPrice: opts.gasPrice },
);
)
.awaitTransactionSuccessAsync({ from, gas: opts.gas, gasPrice: opts.gasPrice });
}
public async marketBuyOrdersNoThrowAsync(
orders: SignedOrder[],
from: string,
opts: { makerAssetFillAmount: BigNumber; gas?: number; gasPrice?: BigNumber },
): Promise<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.marketSellOrdersFillOrKill.awaitTransactionSuccessAsync(
return this.exchangeContract
.marketSellOrdersFillOrKill(
orders,
opts.takerAssetFillAmount,
orders.map(signedOrder => signedOrder.signature),
{ from, gas: opts.gas },
);
)
.awaitTransactionSuccessAsync({ from, gas: opts.gas });
}
public async marketBuyOrdersFillOrKillAsync(
orders: SignedOrder[],
from: string,
opts: { makerAssetFillAmount: BigNumber; gas?: number },
): Promise<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.marketBuyOrdersFillOrKill.awaitTransactionSuccessAsync(
return this.exchangeContract
.marketBuyOrdersFillOrKill(
orders,
opts.makerAssetFillAmount,
orders.map(signedOrder => signedOrder.signature),
{ from, gas: opts.gas },
);
)
.awaitTransactionSuccessAsync({ from, gas: opts.gas });
}
public async batchCancelOrdersAsync(
orders: SignedOrder[],
from: string,
): Promise<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.batchCancelOrders.awaitTransactionSuccessAsync(orders, { from });
return this.exchangeContract.batchCancelOrders(orders).awaitTransactionSuccessAsync({ from });
}
public async cancelOrdersUpToAsync(salt: BigNumber, from: string): Promise<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<BigNumber> {
const filledAmount = await this.exchangeContract.filled.callAsync(orderHashHex);
const filledAmount = await this.exchangeContract.filled(orderHashHex).callAsync();
return filledAmount;
}
public async isCancelledAsync(orderHashHex: string): Promise<boolean> {
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<BigNumber> {
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<OrderInfo> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<BatchMatchedFillResults> {
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<TransactionReceiptWithDecodedLogs> {
const params = orderUtils.createBatchMatchOrders(signedOrdersLeft, signedOrdersRight);
return this.exchangeContract.batchMatchOrdersWithMaximalFill.awaitTransactionSuccessAsync(
return this.exchangeContract
.batchMatchOrdersWithMaximalFill(
params.leftOrders,
params.rightOrders,
params.leftSignatures,
params.rightSignatures,
{ from, gasPrice: opts.gasPrice },
);
)
.awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice });
}
public async batchMatchOrdersWithMaximalFillRawAsync(
params: BatchMatchOrder,
from: string,
opts: { gasPrice?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
return this.exchangeContract.batchMatchOrdersWithMaximalFill.awaitTransactionSuccessAsync(
return this.exchangeContract
.batchMatchOrdersWithMaximalFill(
params.leftOrders,
params.rightOrders,
params.leftSignatures,
params.rightSignatures,
{ from, gasPrice: opts.gasPrice },
);
)
.awaitTransactionSuccessAsync({ from, gasPrice: opts.gasPrice });
}
public async getBatchMatchOrdersWithMaximalFillResultsAsync(
signedOrdersLeft: SignedOrder[],
@ -284,13 +266,14 @@ export class ExchangeWrapper {
opts: { gasPrice?: BigNumber } = {},
): Promise<BatchMatchedFillResults> {
const params = orderUtils.createBatchMatchOrders(signedOrdersLeft, signedOrdersRight);
const batchMatchedFillResults = await this.exchangeContract.batchMatchOrdersWithMaximalFill.callAsync(
const batchMatchedFillResults = await this.exchangeContract
.batchMatchOrdersWithMaximalFill(
params.leftOrders,
params.rightOrders,
params.leftSignatures,
params.rightSignatures,
{ from, gasPrice: opts.gasPrice },
);
)
.callAsync({ from, gasPrice: opts.gasPrice });
return batchMatchedFillResults;
}
public async matchOrdersAsync(
@ -300,13 +283,9 @@ export class ExchangeWrapper {
opts: { gasPrice?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
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<MatchedFillResults> {
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<TransactionReceiptWithDecodedLogs> {
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<MatchedFillResults> {
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<FillResults> {
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 {

View File

@ -128,37 +128,37 @@ export async function fillOrderCombinatorialUtilsFactoryAsync(
await exchangeWrapper.registerAssetProxyAsync(erc1155Proxy.address, ownerAddress);
await exchangeWrapper.registerAssetProxyAsync(multiAssetProxy.address, ownerAddress);
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, {
await erc20Proxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({
from: ownerAddress,
});
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, {
await erc721Proxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({
from: ownerAddress,
});
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, {
await erc1155Proxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({
from: ownerAddress,
});
await multiAssetProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(exchangeContract.address, {
await multiAssetProxy.addAuthorizedAddress(exchangeContract.address).awaitTransactionSuccessAsync({
from: ownerAddress,
});
await erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, { from: ownerAddress });
await erc20Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({ from: ownerAddress });
await erc721Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, {
await erc721Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({
from: ownerAddress,
});
await erc1155Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(multiAssetProxy.address, {
await erc1155Proxy.addAuthorizedAddress(multiAssetProxy.address).awaitTransactionSuccessAsync({
from: ownerAddress,
});
await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, { from: ownerAddress });
await multiAssetProxy.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({ from: ownerAddress });
await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, { from: ownerAddress });
await multiAssetProxy.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({ from: ownerAddress });
await multiAssetProxy.registerAssetProxy.awaitTransactionSuccessAsync(erc1155Proxy.address, { from: ownerAddress });
await multiAssetProxy.registerAssetProxy(erc1155Proxy.address).awaitTransactionSuccessAsync({ from: ownerAddress });
const orderFactory = new OrderFactoryFromScenario(
devUtils,

View File

@ -1,10 +1,4 @@
import {
constants,
filterLogsToArguments,
MutatorContractFunction,
TransactionHelper,
txDefaults as testTxDefaults,
} from '@0x/contracts-test-utils';
import { constants, filterLogsToArguments, txDefaults as testTxDefaults } from '@0x/contracts-test-utils';
import { orderHashUtils } from '@0x/order-utils';
import { FillResults, Order, OrderInfo, SignatureType } from '@0x/types';
import { BigNumber } from '@0x/utils';
@ -41,7 +35,6 @@ export const DEFAULT_BAD_SIGNATURE = createBadSignature();
export class IsolatedExchangeWrapper {
public static readonly CHAIN_ID = 1337;
public readonly instance: IsolatedExchangeContract;
public readonly txHelper: TransactionHelper;
public lastTxEvents: IsolatedExchangeEvents = createEmptyEvents();
public lastTxBalanceChanges: AssetBalances = {};
@ -71,19 +64,18 @@ export class IsolatedExchangeWrapper {
public constructor(web3Wrapper: Web3Wrapper, instance: IsolatedExchangeContract) {
this.instance = instance;
this.txHelper = new TransactionHelper(web3Wrapper, artifacts);
}
public async getTakerAssetFilledAmountAsync(order: Order): Promise<BigNumber> {
return this.instance.filled.callAsync(this.getOrderHash(order));
return this.instance.filled(this.getOrderHash(order)).callAsync();
}
public async cancelOrderAsync(order: Order, txOpts?: TxData): Promise<void> {
await this.instance.cancelOrder.awaitTransactionSuccessAsync(order, txOpts);
await this.instance.cancelOrder(order).awaitTransactionSuccessAsync(txOpts);
}
public async cancelOrdersUpToAsync(epoch: BigNumber, txOpts?: TxData): Promise<void> {
await this.instance.cancelOrdersUpTo.awaitTransactionSuccessAsync(epoch, txOpts);
await this.instance.cancelOrdersUpTo(epoch).awaitTransactionSuccessAsync(txOpts);
}
public async fillOrderAsync(
@ -92,13 +84,14 @@ export class IsolatedExchangeWrapper {
signature: string = DEFAULT_GOOD_SIGNATURE,
txOpts?: TxData,
): Promise<FillResults> {
return this._runFillContractFunctionAsync(
this.instance.fillOrder,
order,
new BigNumber(takerAssetFillAmount),
signature,
txOpts,
);
this.lastTxEvents = createEmptyEvents();
this.lastTxBalanceChanges = {};
const fillOrderFn = this.instance.fillOrder(order, new BigNumber(takerAssetFillAmount), signature);
const result = await fillOrderFn.callAsync();
const receipt = await fillOrderFn.awaitTransactionSuccessAsync(txOpts);
this.lastTxEvents = extractEvents(receipt.logs);
this.lastTxBalanceChanges = getBalanceChangesFromTransferFromCalls(this.lastTxEvents.transferFromCalls);
return result;
}
public getOrderHash(order: Order): string {
@ -110,7 +103,7 @@ export class IsolatedExchangeWrapper {
}
public async getOrderInfoAsync(order: Order): Promise<OrderInfo> {
return this.instance.getOrderInfo.callAsync(order);
return this.instance.getOrderInfo(order).callAsync();
}
public getBalanceChange(assetData: string, address: string): BigNumber {
@ -122,23 +115,6 @@ export class IsolatedExchangeWrapper {
}
return constants.ZERO_AMOUNT;
}
protected async _runFillContractFunctionAsync<
TCallAsyncArgs extends any[],
TAwaitTransactionSuccessAsyncArgs extends any[],
TResult
>(
contractFunction: MutatorContractFunction<TCallAsyncArgs, TAwaitTransactionSuccessAsyncArgs, TResult>,
// tslint:disable-next-line: trailing-comma
...args: TAwaitTransactionSuccessAsyncArgs
): Promise<TResult> {
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;
}
}
/**

View File

@ -631,11 +631,11 @@ async function transferAssetAsync(
matchResults: MatchResults,
devUtils: DevUtilsContract,
): Promise<void> {
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];

View File

@ -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(
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(
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(
makerAssetData = await this._devUtils
.encodeMultiAssetData(
[ONE_UNITS_EIGHTEEN_DECIMALS, ONE_UNITS_FIVE_DECIMALS],
[
await this._devUtils.encodeERC20AssetData.callAsync(
this._erc20EighteenDecimalTokenAddresses[0],
),
await this._devUtils.encodeERC20AssetData.callAsync(this._erc20FiveDecimalTokenAddresses[0]),
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(
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(
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(
takerAssetData = await this._devUtils
.encodeMultiAssetData(
[ONE_UNITS_EIGHTEEN_DECIMALS, ONE_UNITS_FIVE_DECIMALS],
[
await this._devUtils.encodeERC20AssetData.callAsync(
this._erc20EighteenDecimalTokenAddresses[1],
),
await this._devUtils.encodeERC20AssetData.callAsync(this._erc20FiveDecimalTokenAddresses[1]),
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(
await this._devUtils
.encodeERC1155AssetData(
this._erc1155TokenAddress,
[erc1155FungibleTokenId],
[ONE_UNITS_ZERO_DECIMALS],
erc1155CallbackData,
),
)
.callAsync(),
];
case FeeAssetDataScenario.ERC1155NonFungible:
return [
feeAmount,
await this._devUtils.encodeERC1155AssetData.callAsync(
await this._devUtils
.encodeERC1155AssetData(
this._erc1155TokenAddress,
[erc1155NonFungibleAssetId],
[ONE_UNITS_ZERO_DECIMALS],
erc1155CallbackData,
),
)
.callAsync(),
];
case FeeAssetDataScenario.MultiAssetERC20:
return [
feeAmount,
await this._devUtils.encodeMultiAssetData.callAsync(
await this._devUtils
.encodeMultiAssetData(
[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
.encodeERC20AssetData(erc20EighteenDecimalTokenAddress)
.callAsync(),
await this._devUtils.encodeERC20AssetData(erc20FiveDecimalTokenAddress).callAsync(),
],
),
)
.callAsync(),
];
default:
throw errorUtils.spawnSwitchErr('FeeAssetDataScenario', feeAssetDataScenario);

View File

@ -13,13 +13,15 @@ export class SimpleERC20BalanceAndProxyAllowanceFetcher implements AbstractBalan
public async getBalanceAsync(_assetData: string, userAddress: string): Promise<BigNumber> {
// 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<BigNumber> {
// 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;
}
}

View File

@ -1,13 +1,6 @@
import { ContractTxFunctionObj } from '@0x/base-contract';
import { ReferenceFunctions as LibReferenceFunctions } from '@0x/contracts-exchange-libs';
import {
blockchainTests,
constants,
describe,
expect,
hexRandom,
MutatorContractFunction,
TransactionHelper,
} from '@0x/contracts-test-utils';
import { blockchainTests, constants, describe, expect, hexRandom } from '@0x/contracts-test-utils';
import { ReferenceFunctions as UtilReferenceFunctions } from '@0x/contracts-utils';
import { ExchangeRevertErrors, orderHashUtils } from '@0x/order-utils';
import { FillResults, Order } from '@0x/types';
@ -44,13 +37,11 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
protocolFeePaid: constants.ZERO_AMOUNT,
};
let testContract: TestWrapperFunctionsContract;
let txHelper: TransactionHelper;
let owner: string;
let senderAddress: string;
before(async () => {
[owner, senderAddress] = await env.getAccountAddressesAsync();
txHelper = new TransactionHelper(env.web3Wrapper, artifacts);
testContract = await TestWrapperFunctionsContract.deployFrom0xArtifactAsync(
artifacts.TestWrapperFunctions,
env.provider,
@ -62,7 +53,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
// Set the protocol fee multiplier.
await testContract.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(protocolFeeMultiplier, {
await testContract.setProtocolFeeMultiplier(protocolFeeMultiplier).awaitTransactionSuccessAsync({
from: owner,
});
});
@ -152,12 +143,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signature = createOrderSignature(order);
const expectedResult = getExpectedFillResults(order, signature);
const expectedCalls = [[order, fillAmount, signature]];
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.fillOrKillOrder,
order,
fillAmount,
signature,
);
const contractFn = testContract.fillOrKillOrder(order, fillAmount, signature);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -175,7 +163,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
fillAmount,
fillAmount.minus(1),
);
const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature);
const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -192,7 +180,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
fillAmount,
fillAmount.plus(1),
);
const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature);
const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -203,7 +191,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
});
const signature = createOrderSignature(order);
const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR;
const tx = testContract.fillOrKillOrder.awaitTransactionSuccessAsync(order, fillAmount, signature);
const tx = testContract.fillOrKillOrder(order, fillAmount, signature).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -215,12 +203,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signature = createOrderSignature(order);
const expectedResult = getExpectedFillResults(order, signature);
const expectedCalls = [[order, fillAmount, signature]];
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.fillOrderNoThrow,
order,
fillAmount,
signature,
);
const contractFn = testContract.fillOrderNoThrow(order, fillAmount, signature);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -232,12 +217,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
});
const signature = createOrderSignature(order);
const expectedResult = EMPTY_FILL_RESULTS;
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.fillOrderNoThrow,
order,
fillAmount,
signature,
);
const contractFn = testContract.fillOrderNoThrow(order, fillAmount, signature);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, []);
});
@ -245,12 +227,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
describe('batchFillOrders', () => {
it('works with no fills', async () => {
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrders,
[],
[],
[],
);
const contractFn = testContract.batchFillOrders([], [], []);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq([]);
assertFillOrderCallsFromLogs(receipt.logs, []);
});
@ -262,12 +241,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrders,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrders(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -279,12 +255,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrders,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrders(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -298,12 +271,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrders,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrders(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -314,7 +284,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const fillAmounts = _.times(COUNT - 1, i => orders[i].takerAssetAmount);
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedError = new AnyRevertError(); // Just a generic revert.
const tx = txHelper.getResultAndReceiptAsync(testContract.batchFillOrders, orders, fillAmounts, signatures);
const tx = testContract.batchFillOrders(orders, fillAmounts, signatures).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -324,19 +294,16 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount);
const signatures = _.times(COUNT - 1, i => createOrderSignature(orders[i]));
const expectedError = new AnyRevertError(); // Just a generic revert.
const tx = txHelper.getResultAndReceiptAsync(testContract.batchFillOrders, orders, fillAmounts, signatures);
const tx = testContract.batchFillOrders(orders, fillAmounts, signatures).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});
describe('batchFillOrKillOrders', () => {
it('works with no fills', async () => {
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
[],
[],
[],
);
const contractFn = testContract.batchFillOrKillOrders([], [], []);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq([]);
assertFillOrderCallsFromLogs(receipt.logs, []);
});
@ -348,12 +315,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrKillOrders(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -365,12 +329,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrKillOrders(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -384,12 +345,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrKillOrders(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -410,12 +368,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
failingAmount,
failingAmount.minus(1),
);
const tx = txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const tx = testContract
.batchFillOrKillOrders(orders, fillAmounts, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -435,12 +390,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
failingAmount,
failingAmount.plus(1),
);
const tx = txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const tx = testContract
.batchFillOrKillOrders(orders, fillAmounts, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -450,12 +402,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const fillAmounts = _.times(COUNT - 1, i => orders[i].takerAssetAmount);
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedError = new AnyRevertError(); // Just a generic revert.
const tx = txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const tx = testContract
.batchFillOrKillOrders(orders, fillAmounts, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -465,24 +414,18 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount);
const signatures = _.times(COUNT - 1, i => createOrderSignature(orders[i]));
const expectedError = new AnyRevertError(); // Just a generic revert.
const tx = txHelper.getResultAndReceiptAsync(
testContract.batchFillOrKillOrders,
orders,
fillAmounts,
signatures,
);
const tx = testContract
.batchFillOrKillOrders(orders, fillAmounts, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});
describe('batchFillOrdersNoThrow', () => {
it('works with no fills', async () => {
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
[],
[],
[],
);
const contractFn = testContract.batchFillOrdersNoThrow([], [], []);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq([]);
assertFillOrderCallsFromLogs(receipt.logs, []);
});
@ -494,12 +437,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -511,12 +451,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -530,12 +467,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -551,12 +485,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const expectedResult = _.times(COUNT, i => getExpectedFillResults(orders[i], signatures[i]));
const expectedCalls = _.zip(orders, fillAmounts, signatures);
expectedCalls.splice(FAILING_ORDER_INDEX, 1);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
orders,
fillAmounts,
signatures,
);
const contractFn = testContract.batchFillOrdersNoThrow(orders, fillAmounts, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls as any);
});
@ -567,12 +498,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const fillAmounts = _.times(COUNT - 1, i => orders[i].takerAssetAmount);
const signatures = _.times(COUNT, i => createOrderSignature(orders[i]));
const expectedError = new AnyRevertError(); // Just a generic revert.
const tx = txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
orders,
fillAmounts,
signatures,
);
const tx = testContract
.batchFillOrdersNoThrow(orders, fillAmounts, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -582,24 +510,21 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const fillAmounts = _.times(COUNT, i => orders[i].takerAssetAmount);
const signatures = _.times(COUNT - 1, i => createOrderSignature(orders[i]));
const expectedError = new AnyRevertError(); // Just a generic revert.
const tx = txHelper.getResultAndReceiptAsync(
testContract.batchFillOrdersNoThrow,
orders,
fillAmounts,
signatures,
);
const tx = testContract
.batchFillOrdersNoThrow(orders, fillAmounts, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});
type ExpectedFillOrderCallArgs = [Order, BigNumber, string];
type MarketSellBuyArgs = [Order[], BigNumber, string[], ...any[]];
type MarketSellBuyContractFunction = MutatorContractFunction<MarketSellBuyArgs, MarketSellBuyArgs, FillResults>;
type MarketSellBuyContractFn = (...args: MarketSellBuyArgs) => ContractTxFunctionObj<FillResults>;
type MarketSellBuySimulator = (...args: MarketSellBuyArgs) => [FillResults, ExpectedFillOrderCallArgs[]];
describe('marketSell*', () => {
function defineCommonMarketSellOrdersTests(
getContractFn: () => MarketSellBuyContractFunction,
getContractFn: () => MarketSellBuyContractFn,
simulator: MarketSellBuySimulator,
): void {
it('works with one order', async () => {
@ -613,12 +538,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures);
expect(expectedCalls.length).to.eq(COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
takerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -634,12 +556,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures);
expect(expectedCalls.length).to.eq(COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
takerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -657,12 +576,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures);
expect(expectedCalls.length).to.eq(COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
takerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -680,12 +596,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures);
// It should stop filling after the penultimate order.
expect(expectedCalls.length).to.eq(COUNT - 1);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
takerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -706,12 +619,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const [expectedResult, expectedCalls] = simulator(orders, takerAssetFillAmount, signatures);
// It should stop filling after first order.
expect(expectedCalls.length).to.eq(1);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
takerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, takerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -727,20 +637,16 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
orders[0].takerAssetAmount,
orders[1].takerAssetAmount,
);
const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, takerAssetFillAmount, signatures);
const tx = getContractFn()(orders, takerAssetFillAmount, signatures).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
it('returns empty fill results with no orders', async () => {
const [expectedResult, expectedCalls] = simulator([], constants.ZERO_AMOUNT, []);
expect(expectedCalls.length).to.eq(0);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
[],
constants.ZERO_AMOUNT,
[],
);
const fnWithArgs = getContractFn()([], constants.ZERO_AMOUNT, []);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -767,7 +673,10 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
}
describe('marketSellOrdersNoThrow', () => {
defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders);
defineCommonMarketSellOrdersTests(
() => testContract.marketSellOrdersNoThrow.bind(testContract),
simulateMarketSellOrders,
);
it('works when any fills revert', async () => {
const COUNT = 4;
@ -789,12 +698,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
signatures,
);
expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.marketSellOrdersNoThrow,
orders,
takerAssetFillAmount,
signatures,
);
const contractFn = testContract.marketSellOrdersNoThrow(orders, takerAssetFillAmount, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -814,19 +720,19 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
signatures,
);
expect(expectedCalls.length).to.eq(0);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.marketSellOrdersNoThrow,
orders,
takerAssetFillAmount,
signatures,
);
const contractFn = testContract.marketSellOrdersNoThrow(orders, takerAssetFillAmount, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
});
describe('marketSellOrdersFillOrKill', () => {
defineCommonMarketSellOrdersTests(() => testContract.marketSellOrdersNoThrow, simulateMarketSellOrders);
defineCommonMarketSellOrdersTests(
() => testContract.marketSellOrdersNoThrow.bind(testContract),
simulateMarketSellOrders,
);
it('reverts when filled < `takerAssetFillAmount`', async () => {
const COUNT = 4;
@ -842,12 +748,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
takerAssetFillAmount,
takerAssetFillAmount.minus(1),
);
const tx = txHelper.getResultAndReceiptAsync(
testContract.marketSellOrdersFillOrKill,
orders,
takerAssetFillAmount,
signatures,
);
const tx = testContract
.marketSellOrdersFillOrKill(orders, takerAssetFillAmount, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -871,12 +774,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
signatures,
);
expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.marketSellOrdersFillOrKill,
orders,
takerAssetFillAmount,
signatures,
);
const contractFn = testContract.marketSellOrdersFillOrKill(orders, takerAssetFillAmount, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -907,12 +807,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
takerAssetFillAmount,
takerAssetFillAmount.minus(1),
);
const tx = txHelper.getResultAndReceiptAsync(
testContract.marketSellOrdersFillOrKill,
orders,
takerAssetFillAmount,
signatures,
);
const tx = testContract
.marketSellOrdersFillOrKill(orders, takerAssetFillAmount, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -920,7 +817,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
describe('marketBuy*', () => {
function defineCommonMarketBuyOrdersTests(
getContractFn: () => MarketSellBuyContractFunction,
getContractFn: () => MarketSellBuyContractFn,
simulator: MarketSellBuySimulator,
): void {
it('works with one order', async () => {
@ -934,12 +831,10 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures);
expect(expectedCalls.length).to.eq(COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
makerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -955,12 +850,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures);
expect(expectedCalls.length).to.eq(COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
makerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -978,12 +870,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
);
const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures);
expect(expectedCalls.length).to.eq(COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
makerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1001,12 +890,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures);
// It should stop filling after the penultimate order.
expect(expectedCalls.length).to.eq(COUNT - 1);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
makerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1027,12 +913,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const [expectedResult, expectedCalls] = simulator(orders, makerAssetFillAmount, signatures);
// It should stop filling after first order.
expect(expectedCalls.length).to.eq(1);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
orders,
makerAssetFillAmount,
signatures,
);
const fnWithArgs = getContractFn()(orders, makerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1046,7 +929,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
orders[0].takerAssetAmount,
makerAssetFillAmount,
);
const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures);
const tx = getContractFn()(orders, makerAssetFillAmount, signatures).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -1059,7 +942,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
orders[0].takerAssetAmount.times(makerAssetFillAmount),
orders[0].makerAssetAmount,
);
const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures);
const tx = getContractFn()(orders, makerAssetFillAmount, signatures).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -1081,20 +964,16 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
orders[0].makerAssetAmount,
orders[1].makerAssetAmount,
);
const tx = txHelper.getResultAndReceiptAsync(getContractFn(), orders, makerAssetFillAmount, signatures);
const tx = getContractFn()(orders, makerAssetFillAmount, signatures).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
it('returns empty fill results with no orders', async () => {
const [expectedResult, expectedCalls] = simulator([], constants.ZERO_AMOUNT, []);
expect(expectedCalls.length).to.eq(0);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
getContractFn(),
[],
constants.ZERO_AMOUNT,
[],
);
const fnWithArgs = getContractFn()([], constants.ZERO_AMOUNT, []);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1126,7 +1005,10 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
}
describe('marketBuyOrdersNoThrow', () => {
defineCommonMarketBuyOrdersTests(() => testContract.marketBuyOrdersNoThrow, simulateMarketBuyOrdersNoThrow);
defineCommonMarketBuyOrdersTests(
() => testContract.marketBuyOrdersNoThrow.bind(testContract),
simulateMarketBuyOrdersNoThrow,
);
it('works when any fills revert', async () => {
const COUNT = 4;
@ -1148,12 +1030,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
signatures,
);
expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.marketBuyOrdersNoThrow,
orders,
makerAssetFillAmount,
signatures,
);
const contractFn = testContract.marketBuyOrdersNoThrow(orders, makerAssetFillAmount, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1173,12 +1052,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
signatures,
);
expect(expectedCalls.length).to.eq(0);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.marketBuyOrdersNoThrow,
orders,
makerAssetFillAmount,
signatures,
);
const contractFn = testContract.marketBuyOrdersNoThrow(orders, makerAssetFillAmount, signatures);
const actualResult = await contractFn.callAsync();
const receipt = await contractFn.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1186,7 +1062,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
describe('marketBuyOrdersFillOrKill', () => {
defineCommonMarketBuyOrdersTests(
() => testContract.marketBuyOrdersFillOrKill,
() => testContract.marketBuyOrdersFillOrKill.bind(testContract),
simulateMarketBuyOrdersNoThrow,
);
@ -1204,12 +1080,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
makerAssetFillAmount,
makerAssetFillAmount.minus(1),
);
const tx = txHelper.getResultAndReceiptAsync(
testContract.marketBuyOrdersFillOrKill,
orders,
makerAssetFillAmount,
signatures,
);
const tx = testContract
.marketBuyOrdersFillOrKill(orders, makerAssetFillAmount, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -1233,12 +1106,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
signatures,
);
expect(expectedCalls.length).to.eq(COUNT - BAD_ORDERS_COUNT);
const [actualResult, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.marketBuyOrdersFillOrKill,
orders,
makerAssetFillAmount,
signatures,
);
const fnWithArgs = testContract.marketBuyOrdersFillOrKill(orders, makerAssetFillAmount, signatures);
const actualResult = await fnWithArgs.callAsync();
const receipt = await fnWithArgs.awaitTransactionSuccessAsync();
expect(actualResult).to.deep.eq(expectedResult);
assertFillOrderCallsFromLogs(receipt.logs, expectedCalls);
});
@ -1269,12 +1139,9 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
makerAssetFillAmount,
makerAssetFillAmount.minus(1),
);
const tx = txHelper.getResultAndReceiptAsync(
testContract.marketBuyOrdersFillOrKill,
orders,
makerAssetFillAmount,
signatures,
);
const tx = testContract
.marketBuyOrdersFillOrKill(orders, makerAssetFillAmount, signatures)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -1294,15 +1161,15 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
}
it('works with no orders', async () => {
const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, []);
assertCancelOrderCallsFromLogs(receipt.logs, []);
const { logs } = await testContract.batchCancelOrders([]).awaitTransactionSuccessAsync();
assertCancelOrderCallsFromLogs(logs, []);
});
it('works with many orders', async () => {
const COUNT = 8;
const orders = _.times(COUNT, () => randomOrder({ makerAddress: senderAddress }));
const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders);
assertCancelOrderCallsFromLogs(receipt.logs, orders);
const { logs } = await testContract.batchCancelOrders(orders).awaitTransactionSuccessAsync();
assertCancelOrderCallsFromLogs(logs, orders);
});
it('works with duplicate orders', async () => {
@ -1310,8 +1177,8 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const COUNT = 6;
const uniqueOrders = _.times(UNIQUE_ORDERS, () => randomOrder({ makerAddress: senderAddress }));
const orders = _.shuffle(_.flatten(_.times(COUNT / UNIQUE_ORDERS, () => uniqueOrders)));
const [, receipt] = await txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders);
assertCancelOrderCallsFromLogs(receipt.logs, orders);
const { logs } = await testContract.batchCancelOrders(orders).awaitTransactionSuccessAsync();
assertCancelOrderCallsFromLogs(logs, orders);
});
it('reverts if one `_cancelOrder()` reverts', async () => {
@ -1321,7 +1188,7 @@ blockchainTests('Exchange wrapper functions unit tests.', env => {
const failingOrder = orders[FAILING_ORDER_INDEX];
failingOrder.salt = ALWAYS_FAILING_SALT;
const expectedError = ALWAYS_FAILING_SALT_REVERT_ERROR;
const tx = txHelper.getResultAndReceiptAsync(testContract.batchCancelOrders, orders);
const tx = testContract.batchCancelOrders(orders).awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(expectedError);
});
});

View File

@ -129,7 +129,7 @@ describe(ContractName.BalanceThresholdFilter, () => {
);
defaultMakerAssetAddress = erc20TokenA.address;
defaultTakerAssetAddress = erc20TokenB.address;
zrxAssetData = await devUtils.encodeERC20AssetData.callAsync(zrxToken.address);
zrxAssetData = await devUtils.encodeERC20AssetData(zrxToken.address).callAsync();
// Create proxies
const erc20Proxy = await erc20Wrapper.deployProxyAsync();
await erc20Wrapper.setBalancesAndAllowancesAsync();
@ -143,10 +143,10 @@ describe(ContractName.BalanceThresholdFilter, () => {
new BigNumber(chainId),
);
// Register proxies
await exchangeInstance.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await exchangeInstance.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, {
await erc20Proxy.addAuthorizedAddress(exchangeInstance.address).awaitTransactionSuccessAsync({
from: owner,
});
// Deploy Balance Threshold Filters
@ -177,8 +177,8 @@ describe(ContractName.BalanceThresholdFilter, () => {
// Default order parameters
defaultOrderParams = {
feeRecipientAddress,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(),
makerAssetAmount,
takerAssetAmount,
makerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(100), DECIMALS_DEFAULT),
@ -300,12 +300,9 @@ describe(ContractName.BalanceThresholdFilter, () => {
const badSelectorHex = '0x00000000';
const signatureHex = '0x';
// Call valid forwarder
const tx = erc721BalanceThresholdFilterInstance.executeTransaction.sendTransactionAsync(
salt,
validTakerAddress,
badSelectorHex,
signatureHex,
);
const tx = erc721BalanceThresholdFilterInstance
.executeTransaction(salt, validTakerAddress, badSelectorHex, signatureHex)
.sendTransactionAsync();
return expect(tx).to.revertWith(RevertReason.InvalidOrBlockedExchangeSelector);
});
it('should revert if senderAddress is not set to the valid forwarding contract', async () => {
@ -1243,8 +1240,8 @@ describe(ContractName.BalanceThresholdFilter, () => {
feeRecipientAddress,
});
const signedOrderRight = await orderFactory2.newSignedOrderAsync({
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(75), 0),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(13), 0),
makerFee: Web3Wrapper.toBaseUnitAmount(new BigNumber(1), 18),

View File

@ -91,7 +91,7 @@ describe(ContractName.DutchAuction, () => {
wethContract = await WETH9Contract.deployFrom0xArtifactAsync(artifacts.WETH9, provider, txDefaults, artifacts);
erc20Wrapper.addDummyTokenContract(wethContract as any);
const zrxAssetData = await devUtils.encodeERC20AssetData.callAsync(zrxToken.address);
const zrxAssetData = await devUtils.encodeERC20AssetData(zrxToken.address).callAsync();
const exchangeInstance = await ExchangeContract.deployFrom0xArtifactAsync(
artifacts.Exchange,
provider,
@ -107,10 +107,10 @@ describe(ContractName.DutchAuction, () => {
from: owner,
});
await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, {
await erc20Proxy.addAuthorizedAddress(exchangeInstance.address).sendTransactionAsync({
from: owner,
});
await erc721Proxy.addAuthorizedAddress.sendTransactionAsync(exchangeInstance.address, {
await erc721Proxy.addAuthorizedAddress(exchangeInstance.address).sendTransactionAsync({
from: owner,
});
@ -135,11 +135,9 @@ describe(ContractName.DutchAuction, () => {
}),
);
await web3Wrapper.awaitTransactionSuccessAsync(
await wethContract.approve.sendTransactionAsync(
erc20Proxy.address,
constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS,
{ from: takerAddress },
),
await wethContract
.approve(erc20Proxy.address, constants.UNLIMITED_ALLOWANCE_IN_BASE_UNITS)
.sendTransactionAsync({ from: takerAddress }),
);
web3Wrapper.abiDecoder.addABI(exchangeInstance.abi);
web3Wrapper.abiDecoder.addABI(zrxToken.abi);
@ -161,11 +159,11 @@ describe(ContractName.DutchAuction, () => {
// taker address or sender address should be set to the ducth auction contract
takerAddress: dutchAuctionContract.address,
makerAssetData: assetDataUtils.encodeDutchAuctionAssetData(
await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress),
await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(),
auctionBeginTimeSeconds,
auctionBeginAmount,
),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultTakerAssetAddress),
takerAssetData: await devUtils.encodeERC20AssetData(defaultTakerAssetAddress).callAsync(),
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(200), DECIMALS_DEFAULT),
takerAssetAmount: auctionEndAmount,
expirationTimeSeconds: auctionEndTimeSeconds,
@ -187,7 +185,7 @@ describe(ContractName.DutchAuction, () => {
const takerPrivateKey = constants.TESTRPC_PRIVATE_KEYS[accounts.indexOf(takerAddress)];
sellerOrderFactory = new OrderFactory(makerPrivateKey, sellerDefaultOrderParams);
buyerOrderFactory = new OrderFactory(takerPrivateKey, buyerDefaultOrderParams);
defaultERC20MakerAssetData = await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress);
defaultERC20MakerAssetData = await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync();
});
after(async () => {
await blockchainLifecycle.revertAsync();
@ -326,7 +324,7 @@ describe(ContractName.DutchAuction, () => {
});
it('asset data contains auction parameters', async () => {
sellOrder = await sellerOrderFactory.newSignedOrderAsync({
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(defaultMakerAssetAddress),
makerAssetData: await devUtils.encodeERC20AssetData(defaultMakerAssetAddress).callAsync(),
});
const tx = dutchAuctionTestWrapper.matchOrdersAsync(buyOrder, sellOrder, takerAddress);
return expect(tx).to.revertWith(RevertReason.InvalidAssetData);
@ -335,10 +333,9 @@ describe(ContractName.DutchAuction, () => {
describe('ERC721', () => {
it('should match orders when ERC721', async () => {
const makerAssetId = erc721MakerAssetIds[0];
const erc721MakerAssetData = await devUtils.encodeERC721AssetData.callAsync(
erc721Token.address,
makerAssetId,
);
const erc721MakerAssetData = await devUtils
.encodeERC721AssetData(erc721Token.address, makerAssetId)
.callAsync();
const makerAssetData = assetDataUtils.encodeDutchAuctionAssetData(
erc721MakerAssetData,
auctionBeginTimeSeconds,
@ -361,7 +358,7 @@ describe(ContractName.DutchAuction, () => {
expect(newBalances[makerAddress][wethContract.address]).to.be.bignumber.gte(
erc20Balances[makerAddress][wethContract.address].plus(afterAuctionDetails.currentAmount),
);
const newOwner = await erc721Token.ownerOf.callAsync(makerAssetId);
const newOwner = await erc721Token.ownerOf(makerAssetId).callAsync();
expect(newOwner).to.be.bignumber.equal(takerAddress);
});
});

View File

@ -116,17 +116,17 @@ describe('OrderMatcher', () => {
provider,
txDefaults,
artifacts,
await devUtils.encodeERC20AssetData.callAsync(zrxToken.address),
await devUtils.encodeERC20AssetData(zrxToken.address).callAsync(),
new BigNumber(chainId),
);
await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc20Proxy.address, {
await exchange.registerAssetProxy(erc20Proxy.address).awaitTransactionSuccessAsync({
from: owner,
});
await exchange.registerAssetProxy.awaitTransactionSuccessAsync(erc721Proxy.address, {
await exchange.registerAssetProxy(erc721Proxy.address).awaitTransactionSuccessAsync({
from: owner,
}); // Authorize ERC20 trades by exchange
await web3Wrapper.awaitTransactionSuccessAsync(
await erc20Proxy.addAuthorizedAddress.sendTransactionAsync(exchange.address, {
await erc20Proxy.addAuthorizedAddress(exchange.address).sendTransactionAsync({
from: owner,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
@ -142,35 +142,24 @@ describe('OrderMatcher', () => {
// Set default addresses
defaultERC20MakerAssetAddress = erc20TokenA.address;
defaultERC20TakerAssetAddress = erc20TokenB.address;
leftMakerAssetData = await devUtils.encodeERC20AssetData.callAsync(defaultERC20MakerAssetAddress);
leftTakerAssetData = await devUtils.encodeERC20AssetData.callAsync(defaultERC20TakerAssetAddress);
leftMakerAssetData = await devUtils.encodeERC20AssetData(defaultERC20MakerAssetAddress).callAsync();
leftTakerAssetData = await devUtils.encodeERC20AssetData(defaultERC20TakerAssetAddress).callAsync();
// Set OrderMatcher balances and allowances
await web3Wrapper.awaitTransactionSuccessAsync(
await erc20TokenA.setBalance.sendTransactionAsync(orderMatcher.address, constants.INITIAL_ERC20_BALANCE, {
from: owner,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await erc20TokenB.setBalance.sendTransactionAsync(orderMatcher.address, constants.INITIAL_ERC20_BALANCE, {
from: owner,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.approveAssetProxy.sendTransactionAsync(
leftMakerAssetData,
constants.INITIAL_ERC20_ALLOWANCE,
),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.approveAssetProxy.sendTransactionAsync(
leftTakerAssetData,
constants.INITIAL_ERC20_ALLOWANCE,
),
constants.AWAIT_TRANSACTION_MINED_MS,
);
await erc20TokenA
.setBalance(orderMatcher.address, constants.INITIAL_ERC20_BALANCE)
.awaitTransactionSuccessAsync({ from: owner }, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS });
await erc20TokenB
.setBalance(orderMatcher.address, constants.INITIAL_ERC20_BALANCE)
.awaitTransactionSuccessAsync({ from: owner }, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS });
await orderMatcher
.approveAssetProxy(leftMakerAssetData, constants.INITIAL_ERC20_ALLOWANCE)
.awaitTransactionSuccessAsync({}, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS });
await orderMatcher
.approveAssetProxy(leftTakerAssetData, constants.INITIAL_ERC20_ALLOWANCE)
.awaitTransactionSuccessAsync({}, { pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS });
// Create default order parameters
const defaultOrderParamsLeft = {
@ -242,12 +231,9 @@ describe('OrderMatcher', () => {
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(2), 18),
});
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
const tx = web3Wrapper.sendTransactionAsync({
data,
to: orderMatcher.address,
@ -277,13 +263,10 @@ describe('OrderMatcher', () => {
// Taker
leftMakerAssetSpreadAmount: signedOrderLeft.makerAssetAmount.minus(signedOrderRight.takerAssetAmount),
};
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
await web3Wrapper.awaitTransactionSuccessAsync(
await web3Wrapper.sendTransactionAsync({
data,
@ -293,7 +276,7 @@ describe('OrderMatcher', () => {
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const newErc20Balances = await erc20Wrapper.getBalancesAsync();
expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal(
erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus(
@ -338,13 +321,10 @@ describe('OrderMatcher', () => {
amountSoldByRightMaker: signedOrderRight.makerAssetAmount,
amountBoughtByRightMaker: signedOrderRight.takerAssetAmount,
};
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
await web3Wrapper.awaitTransactionSuccessAsync(
await web3Wrapper.sendTransactionAsync({
data,
@ -354,7 +334,7 @@ describe('OrderMatcher', () => {
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const newErc20Balances = await erc20Wrapper.getBalancesAsync();
expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal(
erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus(
@ -400,15 +380,12 @@ describe('OrderMatcher', () => {
leftMakerAssetSpreadAmount: signedOrderLeft.makerAssetAmount.minus(signedOrderRight.takerAssetAmount),
leftTakerAssetSpreadAmount: signedOrderRight.makerAssetAmount.minus(signedOrderLeft.takerAssetAmount),
};
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address);
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync();
// Match signedOrderLeft with signedOrderRight
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
await web3Wrapper.awaitTransactionSuccessAsync(
await web3Wrapper.sendTransactionAsync({
data,
@ -418,8 +395,8 @@ describe('OrderMatcher', () => {
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync();
const newErc20Balances = await erc20Wrapper.getBalancesAsync();
expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal(
erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus(
@ -458,12 +435,9 @@ describe('OrderMatcher', () => {
makerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(10), 18),
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(2), 18),
});
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
const logDecoder = new LogDecoder(web3Wrapper, artifacts);
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await web3Wrapper.sendTransactionAsync({
@ -491,25 +465,16 @@ describe('OrderMatcher', () => {
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(2), 18),
});
let params = orderUtils.createFill(signedOrderLeft, signedOrderLeft.takerAssetAmount.dividedToIntegerBy(5));
await exchange.fillOrder.awaitTransactionSuccessAsync(
params.order,
params.takerAssetFillAmount,
params.signature,
{ from: takerAddress },
);
await exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.awaitTransactionSuccessAsync({ from: takerAddress });
params = orderUtils.createFill(signedOrderRight, signedOrderRight.takerAssetAmount.dividedToIntegerBy(5));
await exchange.fillOrder.awaitTransactionSuccessAsync(
params.order,
params.takerAssetFillAmount,
params.signature,
{ from: takerAddress },
);
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
await exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.awaitTransactionSuccessAsync({ from: takerAddress });
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
const logDecoder = new LogDecoder(web3Wrapper, artifacts);
const txReceipt = await logDecoder.getTxWithDecodedLogsAsync(
await web3Wrapper.sendTransactionAsync({
@ -552,15 +517,12 @@ describe('OrderMatcher', () => {
leftMakerAssetSpreadAmount: constants.ZERO_AMOUNT,
leftTakerAssetSpreadAmount,
};
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address);
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync();
// Match signedOrderLeft with signedOrderRight
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
await web3Wrapper.awaitTransactionSuccessAsync(
await web3Wrapper.sendTransactionAsync({
data,
@ -570,8 +532,8 @@ describe('OrderMatcher', () => {
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync();
const newErc20Balances = await erc20Wrapper.getBalancesAsync();
expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal(
erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus(
@ -622,17 +584,14 @@ describe('OrderMatcher', () => {
leftMakerAssetSpreadAmount: signedOrderLeft.makerAssetAmount.minus(signedOrderRight.takerAssetAmount),
leftTakerAssetSpreadAmount: signedOrderRight.makerAssetAmount.minus(signedOrderLeft.takerAssetAmount),
};
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address);
const initialLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const initialLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync();
// Match signedOrderLeft with signedOrderRight
signedOrderRight.makerAssetData = constants.NULL_BYTES;
signedOrderRight.takerAssetData = constants.NULL_BYTES;
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
await web3Wrapper.awaitTransactionSuccessAsync(
await web3Wrapper.sendTransactionAsync({
data,
@ -642,8 +601,8 @@ describe('OrderMatcher', () => {
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf.callAsync(orderMatcher.address);
const newLeftMakerAssetTakerBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
const newLeftTakerAssetTakerBalance = await erc20TokenB.balanceOf(orderMatcher.address).callAsync();
const newErc20Balances = await erc20Wrapper.getBalancesAsync();
expect(newErc20Balances[makerAddressLeft][defaultERC20MakerAssetAddress]).to.be.bignumber.equal(
erc20BalancesByOwner[makerAddressLeft][defaultERC20MakerAssetAddress].minus(
@ -683,12 +642,9 @@ describe('OrderMatcher', () => {
takerAssetAmount: Web3Wrapper.toBaseUnitAmount(new BigNumber(5), 18),
});
signedOrderRight.signature = `0xff${signedOrderRight.signature.slice(4)}`;
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
const expectedError = new ExchangeRevertErrors.SignatureError();
const tx = web3Wrapper.sendTransactionAsync({
data,
@ -710,17 +666,14 @@ describe('OrderMatcher', () => {
});
// Matcher will not have enough allowance to fill rightOrder
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.approveAssetProxy.sendTransactionAsync(leftMakerAssetData, constants.ZERO_AMOUNT, {
await orderMatcher.approveAssetProxy(leftMakerAssetData, constants.ZERO_AMOUNT).sendTransactionAsync({
from: owner,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const data = exchange.matchOrders.getABIEncodedTransactionData(
signedOrderLeft,
signedOrderRight,
signedOrderLeft.signature,
signedOrderRight.signature,
);
const data = exchange
.matchOrders(signedOrderLeft, signedOrderRight, signedOrderLeft.signature, signedOrderRight.signature)
.getABIEncodedTransactionData();
const expectedError = new ExchangeRevertErrors.AssetProxyTransferError();
const tx = web3Wrapper.sendTransactionAsync({
data,
@ -733,14 +686,14 @@ describe('OrderMatcher', () => {
});
describe('withdrawAsset', () => {
it('should allow owner to withdraw ERC20 tokens', async () => {
const erc20AWithdrawAmount = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const erc20AWithdrawAmount = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
expect(erc20AWithdrawAmount).to.be.bignumber.gt(constants.ZERO_AMOUNT);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.withdrawAsset.sendTransactionAsync(leftMakerAssetData, erc20AWithdrawAmount, {
await orderMatcher.withdrawAsset(leftMakerAssetData, erc20AWithdrawAmount).sendTransactionAsync({
from: owner,
}),
);
const newBalance = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const newBalance = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
expect(newBalance).to.be.bignumber.equal(constants.ZERO_AMOUNT);
});
it('should allow owner to withdraw ERC721 tokens', async () => {
@ -754,22 +707,22 @@ describe('OrderMatcher', () => {
);
const tokenId = new BigNumber(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await erc721Token.mint.sendTransactionAsync(orderMatcher.address, tokenId, { from: owner }),
await erc721Token.mint(orderMatcher.address, tokenId).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const assetData = await devUtils.encodeERC721AssetData.callAsync(erc721Token.address, tokenId);
const assetData = await devUtils.encodeERC721AssetData(erc721Token.address, tokenId).callAsync();
const withdrawAmount = new BigNumber(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.withdrawAsset.sendTransactionAsync(assetData, withdrawAmount, { from: owner }),
await orderMatcher.withdrawAsset(assetData, withdrawAmount).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const erc721Owner = await erc721Token.ownerOf.callAsync(tokenId);
const erc721Owner = await erc721Token.ownerOf(tokenId).callAsync();
expect(erc721Owner).to.be.equal(owner);
});
it('should revert if not called by owner', async () => {
const erc20AWithdrawAmount = await erc20TokenA.balanceOf.callAsync(orderMatcher.address);
const erc20AWithdrawAmount = await erc20TokenA.balanceOf(orderMatcher.address).callAsync();
expect(erc20AWithdrawAmount).to.be.bignumber.gt(constants.ZERO_AMOUNT);
const tx = orderMatcher.withdrawAsset.sendTransactionAsync(leftMakerAssetData, erc20AWithdrawAmount, {
const tx = orderMatcher.withdrawAsset(leftMakerAssetData, erc20AWithdrawAmount).sendTransactionAsync({
from: takerAddress,
});
return expect(tx).to.revertWith(RevertReason.OnlyContractOwner);
@ -779,12 +732,12 @@ describe('OrderMatcher', () => {
it('should be able to set an allowance for ERC20 tokens', async () => {
const allowance = new BigNumber(55465465426546);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.approveAssetProxy.sendTransactionAsync(leftMakerAssetData, allowance, {
await orderMatcher.approveAssetProxy(leftMakerAssetData, allowance).sendTransactionAsync({
from: owner,
}),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const newAllowance = await erc20TokenA.allowance.callAsync(orderMatcher.address, erc20Proxy.address);
const newAllowance = await erc20TokenA.allowance(orderMatcher.address, erc20Proxy.address).callAsync();
expect(newAllowance).to.be.bignumber.equal(allowance);
});
it('should be able to approve an ERC721 token by passing in allowance = 1', async () => {
@ -796,16 +749,17 @@ describe('OrderMatcher', () => {
constants.DUMMY_TOKEN_NAME,
constants.DUMMY_TOKEN_SYMBOL,
);
const assetData = await devUtils.encodeERC721AssetData.callAsync(
erc721Token.address,
constants.ZERO_AMOUNT,
);
const assetData = await devUtils
.encodeERC721AssetData(erc721Token.address, constants.ZERO_AMOUNT)
.callAsync();
const allowance = new BigNumber(1);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.approveAssetProxy.sendTransactionAsync(assetData, allowance, { from: owner }),
await orderMatcher.approveAssetProxy(assetData, allowance).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isApproved = await erc721Token.isApprovedForAll.callAsync(orderMatcher.address, erc721Proxy.address);
const isApproved = await erc721Token
.isApprovedForAll(orderMatcher.address, erc721Proxy.address)
.callAsync();
expect(isApproved).to.be.equal(true);
});
it('should be able to approve an ERC721 token by passing in allowance > 1', async () => {
@ -817,21 +771,22 @@ describe('OrderMatcher', () => {
constants.DUMMY_TOKEN_NAME,
constants.DUMMY_TOKEN_SYMBOL,
);
const assetData = await devUtils.encodeERC721AssetData.callAsync(
erc721Token.address,
constants.ZERO_AMOUNT,
);
const assetData = await devUtils
.encodeERC721AssetData(erc721Token.address, constants.ZERO_AMOUNT)
.callAsync();
const allowance = new BigNumber(2);
await web3Wrapper.awaitTransactionSuccessAsync(
await orderMatcher.approveAssetProxy.sendTransactionAsync(assetData, allowance, { from: owner }),
await orderMatcher.approveAssetProxy(assetData, allowance).sendTransactionAsync({ from: owner }),
constants.AWAIT_TRANSACTION_MINED_MS,
);
const isApproved = await erc721Token.isApprovedForAll.callAsync(orderMatcher.address, erc721Proxy.address);
const isApproved = await erc721Token
.isApprovedForAll(orderMatcher.address, erc721Proxy.address)
.callAsync();
expect(isApproved).to.be.equal(true);
});
it('should revert if not called by owner', async () => {
const approval = new BigNumber(1);
const tx = orderMatcher.approveAssetProxy.sendTransactionAsync(leftMakerAssetData, approval, {
const tx = orderMatcher.approveAssetProxy(leftMakerAssetData, approval).sendTransactionAsync({
from: takerAddress,
});
return expect(tx).to.revertWith(RevertReason.OnlyContractOwner);

View File

@ -41,11 +41,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmount?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount);
const data = this._exchange.fillOrder.getABIEncodedTransactionData(
params.order,
params.takerAssetFillAmount,
params.signature,
);
const data = this._exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -55,11 +53,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmount?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount);
const data = this._exchange.fillOrKillOrder.getABIEncodedTransactionData(
params.order,
params.takerAssetFillAmount,
params.signature,
);
const data = this._exchange
.fillOrKillOrder(params.order, params.takerAssetFillAmount, params.signature)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -69,11 +65,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmount?: BigNumber; gas?: number } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount);
const data = this._exchange.fillOrderNoThrow.getABIEncodedTransactionData(
params.order,
params.takerAssetFillAmount,
params.signature,
);
const data = this._exchange
.fillOrderNoThrow(params.order, params.takerAssetFillAmount, params.signature)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from, opts.gas);
return txReceipt;
}
@ -83,11 +77,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmounts?: BigNumber[] } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts);
const data = this._exchange.batchFillOrders.getABIEncodedTransactionData(
params.orders,
params.takerAssetFillAmounts,
params.signatures,
);
const data = this._exchange
.batchFillOrders(params.orders, params.takerAssetFillAmounts, params.signatures)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -97,11 +89,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmounts?: BigNumber[] } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts);
const data = this._exchange.batchFillOrKillOrders.getABIEncodedTransactionData(
params.orders,
params.takerAssetFillAmounts,
params.signatures,
);
const data = this._exchange
.batchFillOrKillOrders(params.orders, params.takerAssetFillAmounts, params.signatures)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -111,11 +101,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmounts?: BigNumber[]; gas?: number } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
const params = formatters.createBatchFill(orders, opts.takerAssetFillAmounts);
const data = this._exchange.batchFillOrKillOrders.getABIEncodedTransactionData(
params.orders,
params.takerAssetFillAmounts,
params.signatures,
);
const data = this._exchange
.batchFillOrKillOrders(params.orders, params.takerAssetFillAmounts, params.signatures)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from, opts.gas);
return txReceipt;
}
@ -125,11 +113,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmount: BigNumber },
): Promise<TransactionReceiptWithDecodedLogs> {
const params = formatters.createMarketSellOrders(orders, opts.takerAssetFillAmount);
const data = this._exchange.marketSellOrders.getABIEncodedTransactionData(
params.orders,
params.takerAssetFillAmount,
params.signatures,
);
const data = this._exchange
.marketSellOrders(params.orders, params.takerAssetFillAmount, params.signatures)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -139,11 +125,9 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmount: BigNumber; gas?: number },
): Promise<TransactionReceiptWithDecodedLogs> {
const params = formatters.createMarketSellOrders(orders, opts.takerAssetFillAmount);
const data = this._exchange.marketSellOrdersNoThrow.getABIEncodedTransactionData(
params.orders,
params.takerAssetFillAmount,
params.signatures,
);
const data = this._exchange
.marketSellOrdersNoThrow(params.orders, params.takerAssetFillAmount, params.signatures)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from, opts.gas);
return txReceipt;
}
@ -153,11 +137,9 @@ export class BalanceThresholdWrapper {
opts: { makerAssetFillAmount: BigNumber },
): Promise<TransactionReceiptWithDecodedLogs> {
const params = formatters.createMarketBuyOrders(orders, opts.makerAssetFillAmount);
const data = this._exchange.marketBuyOrders.getABIEncodedTransactionData(
params.orders,
params.makerAssetFillAmount,
params.signatures,
);
const data = this._exchange
.marketBuyOrders(params.orders, params.makerAssetFillAmount, params.signatures)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -167,17 +149,15 @@ export class BalanceThresholdWrapper {
opts: { makerAssetFillAmount: BigNumber; gas?: number },
): Promise<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
const params = orderUtils.createCancel(signedOrder);
const data = this._exchange.cancelOrder.getABIEncodedTransactionData(params.order);
const data = this._exchange.cancelOrder(params.order).getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -186,33 +166,33 @@ export class BalanceThresholdWrapper {
from: string,
): Promise<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<BigNumber> {
const filledAmount = await this._exchange.filled.callAsync(orderHashHex);
const filledAmount = await this._exchange.filled(orderHashHex).callAsync();
return filledAmount;
}
public async isCancelledAsync(orderHashHex: string): Promise<boolean> {
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<BigNumber> {
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<OrderInfo> {
const orderInfo = await this._exchange.getOrderInfo.callAsync(signedOrder);
const orderInfo = await this._exchange.getOrderInfo(signedOrder).callAsync();
return orderInfo;
}
public async getOrdersInfoAsync(signedOrders: SignedOrder[]): Promise<OrderInfo[]> {
const ordersInfo = (await this._exchange.getOrdersInfo.callAsync(signedOrders)) as OrderInfo[];
const ordersInfo = (await this._exchange.getOrdersInfo(signedOrders)).callAsync() as OrderInfo[];
return ordersInfo;
}
public async matchOrdersAsync(
@ -221,12 +201,9 @@ export class BalanceThresholdWrapper {
from: string,
): Promise<TransactionReceiptWithDecodedLogs> {
const params = orderUtils.createMatchOrders(signedOrderLeft, signedOrderRight);
const data = this._exchange.matchOrders.getABIEncodedTransactionData(
params.left,
params.right,
params.leftSignature,
params.rightSignature,
);
const data = this._exchange
.matchOrders(params.left, params.right, params.leftSignature, params.rightSignature)
.getABIEncodedTransactionData();
const txReceipt = this._executeTransactionAsync(data, from);
return txReceipt;
}
@ -236,21 +213,16 @@ export class BalanceThresholdWrapper {
opts: { takerAssetFillAmount?: BigNumber } = {},
): Promise<FillResults> {
const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount);
const fillResults = await this._exchange.fillOrder.callAsync(
params.order,
params.takerAssetFillAmount,
params.signature,
{ from },
);
const fillResults = await this._exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.callAsync({ from });
return fillResults;
}
public abiEncodeFillOrder(signedOrder: SignedOrder, opts: { takerAssetFillAmount?: BigNumber } = {}): string {
const params = orderUtils.createFill(signedOrder, opts.takerAssetFillAmount);
const data = this._exchange.fillOrder.getABIEncodedTransactionData(
params.order,
params.takerAssetFillAmount,
params.signature,
);
const data = this._exchange
.fillOrder(params.order, params.takerAssetFillAmount, params.signature)
.getABIEncodedTransactionData();
return data;
}
public getBalanceThresholdAddress(): string {
@ -266,13 +238,15 @@ export class BalanceThresholdWrapper {
): Promise<TransactionReceiptWithDecodedLogs> {
const signedExchangeTx = this._signerTransactionFactory.newSignedTransaction(abiEncodedExchangeTxData);
const txOpts = gas === undefined ? { from } : { from, gas };
const txHash = await this._balanceThresholdFilter.executeTransaction.sendTransactionAsync(
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;
}

View File

@ -38,15 +38,11 @@ export class DutchAuctionTestWrapper {
sellOrder: SignedOrder,
from: string,
): Promise<TransactionReceiptWithDecodedLogs> {
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<DutchAuctionDetails> {
const auctionDetails = await this._dutchAuctionContract.getAuctionDetails.callAsync(sellOrder);
const auctionDetails = await this._dutchAuctionContract.getAuctionDetails(sellOrder).callAsync();
return auctionDetails;
}
}

View File

@ -1,16 +1,10 @@
import { PromiseWithTransactionHash } from '@0x/base-contract';
import { ContractFunctionObj, ContractTxFunctionObj } from '@0x/base-contract';
import { TransactionReceiptWithDecodedLogs } from 'ethereum-types';
import * as _ from 'lodash';
// tslint:disable:max-classes-per-file
export interface ContractGetterFunction {
callAsync: (...args: any[]) => Promise<any>;
}
export interface ContractWrapperFunction extends ContractGetterFunction {
awaitTransactionSuccessAsync?: (...args: any[]) => PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs>;
}
export type GenericContractFunction<T> = (...args: any[]) => ContractFunctionObj<T>;
export interface FunctionResult {
data?: any;
@ -53,14 +47,21 @@ export interface AssertionResult<TBefore = unknown> {
* This class implements `Assertion` and represents a "Hoare Triple" that can be
* executed.
*/
export class FunctionAssertion<TBefore> implements Assertion {
export class FunctionAssertion<TBefore, ReturnDataType> implements Assertion {
// A condition that will be applied to `wrapperFunction`.
public condition: Condition<TBefore>;
// The wrapper function that will be wrapped in assertions.
public wrapperFunction: ContractWrapperFunction;
public wrapperFunction: (
...args: any[] // tslint:disable-line:trailing-comma
) => ContractTxFunctionObj<ReturnDataType> | ContractFunctionObj<ReturnDataType>;
constructor(wrapperFunction: ContractWrapperFunction, condition: Partial<Condition<TBefore>> = {}) {
constructor(
wrapperFunction: (
...args: any[] // tslint:disable-line:trailing-comma
) => ContractTxFunctionObj<ReturnDataType> | ContractFunctionObj<ReturnDataType>,
condition: Partial<Condition<TBefore>> = {},
) {
this.condition = {
before: _.noop.bind(this),
after: _.noop.bind(this),
@ -83,11 +84,11 @@ export class FunctionAssertion<TBefore> implements Assertion {
// Try to make the call to the function. If it is successful, pass the
// result and receipt to the after condition.
try {
callResult.data = await this.wrapperFunction.callAsync(...args);
// tslint:disable:await-promise
const functionWithArgs = this.wrapperFunction(...args) as ContractTxFunctionObj<ReturnDataType>;
callResult.data = await functionWithArgs.callAsync();
callResult.receipt =
this.wrapperFunction.awaitTransactionSuccessAsync !== undefined
? await this.wrapperFunction.awaitTransactionSuccessAsync(...args)
functionWithArgs.awaitTransactionSuccessAsync !== undefined
? await functionWithArgs.awaitTransactionSuccessAsync() // tslint:disable-line:await-promise
: undefined;
// tslint:enable:await-promise
} catch (error) {

View File

@ -54,22 +54,19 @@ export class Actor {
amount?: BigNumber,
): Promise<void> {
if (token instanceof DummyERC20TokenContract) {
await token.setBalance.awaitTransactionSuccessAsync(
this.address,
amount || constants.INITIAL_ERC20_BALANCE,
);
await token
.setBalance(this.address, amount || constants.INITIAL_ERC20_BALANCE)
.awaitTransactionSuccessAsync();
} else {
await token.deposit.awaitTransactionSuccessAsync({
await token.deposit().awaitTransactionSuccessAsync({
from: this.address,
value: amount || constants.ONE_ETHER,
});
}
await token.approve.awaitTransactionSuccessAsync(
spender || this.deployment.assetProxies.erc20Proxy.address,
constants.MAX_UINT256,
{ from: this.address },
);
await token
.approve(spender || this.deployment.assetProxies.erc20Proxy.address, constants.MAX_UINT256)
.awaitTransactionSuccessAsync({ from: this.address });
}
/**
@ -84,19 +81,17 @@ export class Actor {
const tokenIds: BigNumber[] = [];
_.times(numToMint, async () => {
const tokenId = getRandomInteger(constants.ZERO_AMOUNT, constants.MAX_UINT256);
await token.mint.awaitTransactionSuccessAsync(this.address, tokenId, {
await token.mint(this.address, tokenId).awaitTransactionSuccessAsync({
from: this.address,
});
tokenIds.push(tokenId);
});
await token.setApprovalForAll.awaitTransactionSuccessAsync(
spender || this.deployment.assetProxies.erc721Proxy.address,
true,
{
await token
.setApprovalForAll(spender || this.deployment.assetProxies.erc721Proxy.address, true)
.awaitTransactionSuccessAsync({
from: this.address,
},
);
});
return tokenIds;
}

View File

@ -37,14 +37,14 @@ export function KeeperMixin<TBase extends Constructor>(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<TBase extends Constructor>(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<IStakingEventsStakingPoolEarnedRewardsInEpochEventArgs>(
await stakingWrapper.getLogsAsync(
TestStakingEvents.StakingPoolEarnedRewardsInEpoch,
@ -69,7 +69,7 @@ export function KeeperMixin<TBase extends Constructor>(Base: TBase): TBase & Con
return Promise.all(
poolIds.map(async poolId =>
stakingWrapper.finalizePool.awaitTransactionSuccessAsync(poolId, {
stakingWrapper.finalizePool(poolId).awaitTransactionSuccessAsync({
from: this.actor.address,
}),
),

View File

@ -59,7 +59,7 @@ export function MakerMixin<TBase extends Constructor>(Base: TBase): TBase & Cons
*/
public async cancelOrderAsync(order: SignedOrder): Promise<TransactionReceiptWithDecodedLogs> {
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<TBase extends Constructor>(Base: TBase): TBase & Cons
public async joinStakingPoolAsync(poolId: string): Promise<TransactionReceiptWithDecodedLogs> {
const stakingContract = this.actor.deployment.staking.stakingWrapper;
this.makerPoolId = poolId;
return stakingContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, {
return stakingContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({
from: this.actor.address,
});
}

View File

@ -54,11 +54,9 @@ export function PoolOperatorMixin<TBase extends Constructor>(Base: TBase): TBase
addOperatorAsMaker: boolean = false,
): Promise<string> {
const stakingContract = this.actor.deployment.staking.stakingWrapper;
const txReceipt = await stakingContract.createStakingPool.awaitTransactionSuccessAsync(
operatorShare,
addOperatorAsMaker,
{ from: this.actor.address },
);
const txReceipt = await stakingContract
.createStakingPool(operatorShare, addOperatorAsMaker)
.awaitTransactionSuccessAsync({ from: this.actor.address });
const createStakingPoolLog = txReceipt.logs[0];
const poolId = (createStakingPoolLog as any).args.poolId;
@ -73,11 +71,9 @@ export function PoolOperatorMixin<TBase extends Constructor>(Base: TBase): TBase
newOperatorShare: number,
): Promise<TransactionReceiptWithDecodedLogs> {
const stakingContract = this.actor.deployment.staking.stakingWrapper;
return stakingContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
newOperatorShare,
{ from: this.actor.address },
);
return stakingContract
.decreaseStakingPoolOperatorShare(poolId, newOperatorShare)
.awaitTransactionSuccessAsync({ from: this.actor.address });
}
private _getOperatorPoolIds(stakingPools: StakingPoolById): string[] {

View File

@ -51,16 +51,17 @@ export function StakerMixin<TBase extends Constructor>(Base: TBase): TBase & Con
*/
public async stakeAsync(amount: BigNumber, poolId?: string): Promise<void> {
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(
await stakingWrapper
.moveStake(
new StakeInfo(StakeStatus.Undelegated),
new StakeInfo(StakeStatus.Delegated, poolId),
amount,
{ from: this.actor.address },
);
)
.awaitTransactionSuccessAsync({ from: this.actor.address });
}
}
@ -84,10 +85,9 @@ export function StakerMixin<TBase extends Constructor>(Base: TBase): TBase & Con
while (true) {
await balanceStore.updateErc20BalancesAsync();
const undelegatedStake = await stakingWrapper.getOwnerStakeByStatus.callAsync(
this.actor.address,
StakeStatus.Undelegated,
);
const undelegatedStake = await stakingWrapper
.getOwnerStakeByStatus(this.actor.address, StakeStatus.Undelegated)
.callAsync();
const withdrawableStake = BigNumber.min(
undelegatedStake.currentEpochBalance,
undelegatedStake.nextEpochBalance,

View File

@ -41,17 +41,14 @@ export function TakerMixin<TBase extends Constructor>(Base: TBase): TBase & Cons
fillAmount: BigNumber,
txData: Partial<TxData> = {},
): Promise<TransactionReceiptWithDecodedLogs> {
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,
},
);
});
}
};
}

View File

@ -63,10 +63,10 @@ blockchainTests.resets('Coordinator integration tests', env => {
orderConfig: {
senderAddress: coordinator.address,
feeRecipientAddress: feeRecipient.address,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(makerToken.address),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(takerToken.address),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(makerFeeToken.address),
takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(takerFeeToken.address),
makerAssetData: await devUtils.encodeERC20AssetData(makerToken.address).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(takerToken.address).callAsync(),
makerFeeAssetData: await devUtils.encodeERC20AssetData(makerFeeToken.address).callAsync(),
takerFeeAssetData: await devUtils.encodeERC20AssetData(takerFeeToken.address).callAsync(),
},
});
@ -140,7 +140,7 @@ blockchainTests.resets('Coordinator integration tests', env => {
taker.address,
deployment.staking.stakingProxy.address,
DeploymentManager.protocolFee,
await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address),
await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(),
);
}
}
@ -186,13 +186,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
it(`${fnName} should fill the order with a signed approval`, async () => {
await balanceStore.updateBalancesAsync();
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[approval.signature],
{ from: taker.address, value: DeploymentManager.protocolFee },
);
const txReceipt = await coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [approval.signature])
.awaitTransactionSuccessAsync({ from: taker.address, value: DeploymentManager.protocolFee });
const expectedBalances = await simulateFillsAsync([order], txReceipt, DeploymentManager.protocolFee);
await balanceStore.updateBalancesAsync();
@ -201,13 +197,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
});
it(`${fnName} should fill the order if called by approver (eth protocol fee, no refund)`, async () => {
await balanceStore.updateBalancesAsync();
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
feeRecipient.address,
transaction.signature,
[],
{ from: feeRecipient.address, value: DeploymentManager.protocolFee },
);
const txReceipt = await coordinator
.executeTransaction(transaction, feeRecipient.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: feeRecipient.address, value: DeploymentManager.protocolFee });
const expectedBalances = await simulateFillsAsync([order], txReceipt, DeploymentManager.protocolFee);
await balanceStore.updateBalancesAsync();
@ -216,13 +208,12 @@ blockchainTests.resets('Coordinator integration tests', env => {
});
it(`${fnName} should fill the order if called by approver (eth protocol fee, refund)`, async () => {
await balanceStore.updateBalancesAsync();
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
feeRecipient.address,
transaction.signature,
[],
{ from: feeRecipient.address, value: DeploymentManager.protocolFee.plus(1) },
);
const txReceipt = await coordinator
.executeTransaction(transaction, feeRecipient.address, transaction.signature, [])
.awaitTransactionSuccessAsync({
from: feeRecipient.address,
value: DeploymentManager.protocolFee.plus(1),
});
const expectedBalances = await simulateFillsAsync(
[order],
@ -235,13 +226,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
});
it(`${fnName} should fill the order if called by approver (weth protocol fee, no refund)`, async () => {
await balanceStore.updateBalancesAsync();
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
feeRecipient.address,
transaction.signature,
[],
{ from: feeRecipient.address },
);
const txReceipt = await coordinator
.executeTransaction(transaction, feeRecipient.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: feeRecipient.address });
const expectedBalances = await simulateFillsAsync([order], txReceipt);
await balanceStore.updateBalancesAsync();
@ -250,13 +237,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
});
it(`${fnName} should fill the order if called by approver (weth protocol fee, refund)`, async () => {
await balanceStore.updateBalancesAsync();
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
feeRecipient.address,
transaction.signature,
[],
{ from: feeRecipient.address, value: new BigNumber(1) },
);
const txReceipt = await coordinator
.executeTransaction(transaction, feeRecipient.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: feeRecipient.address, value: new BigNumber(1) });
const expectedBalances = await simulateFillsAsync([order], txReceipt, new BigNumber(1));
await balanceStore.updateBalancesAsync();
@ -265,13 +248,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
});
it(`${fnName} should revert with no approval signature`, async () => {
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[],
{ from: taker.address, value: DeploymentManager.protocolFee },
);
const tx = coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: taker.address, value: DeploymentManager.protocolFee });
const expectedError = new CoordinatorRevertErrors.InvalidApprovalSignatureError(
transactionHash,
@ -286,13 +265,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
hexSlice(approval.signature, 6),
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[approvalSignature],
{ from: taker.address, value: DeploymentManager.protocolFee },
);
const tx = coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [approvalSignature])
.awaitTransactionSuccessAsync({ from: taker.address, value: DeploymentManager.protocolFee });
const expectedError = new CoordinatorRevertErrors.InvalidApprovalSignatureError(
transactionHash,
@ -301,13 +276,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
return expect(tx).to.revertWith(expectedError);
});
it(`${fnName} should revert if not called by tx signer or approver`, async () => {
const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[approval.signature],
{ from: maker.address, value: DeploymentManager.protocolFee },
);
const tx = coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [approval.signature])
.awaitTransactionSuccessAsync({ from: maker.address, value: DeploymentManager.protocolFee });
const expectedError = new CoordinatorRevertErrors.InvalidOriginError(taker.address);
return expect(tx).to.revertWith(expectedError);
@ -334,13 +305,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
it(`${fnName} should fill the orders with a signed approval`, async () => {
await balanceStore.updateBalancesAsync();
const value = DeploymentManager.protocolFee.times(orders.length);
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[approval.signature],
{ from: taker.address, value },
);
const txReceipt = await coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [approval.signature])
.awaitTransactionSuccessAsync({ from: taker.address, value });
const expectedBalances = await simulateFillsAsync(orders, txReceipt, value);
await balanceStore.updateBalancesAsync();
@ -350,13 +317,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
it(`${fnName} should fill the orders if called by approver (eth fee, no refund)`, async () => {
await balanceStore.updateBalancesAsync();
const value = DeploymentManager.protocolFee.times(orders.length);
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
feeRecipient.address,
transaction.signature,
[],
{ from: feeRecipient.address, value },
);
const txReceipt = await coordinator
.executeTransaction(transaction, feeRecipient.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: feeRecipient.address, value });
const expectedBalances = await simulateFillsAsync(orders, txReceipt, value);
await balanceStore.updateBalancesAsync();
@ -366,13 +329,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
it(`${fnName} should fill the orders if called by approver (mixed fees, refund)`, async () => {
await balanceStore.updateBalancesAsync();
const value = DeploymentManager.protocolFee.plus(1);
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
feeRecipient.address,
transaction.signature,
[],
{ from: feeRecipient.address, value },
);
const txReceipt = await coordinator
.executeTransaction(transaction, feeRecipient.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: feeRecipient.address, value });
const expectedBalances = await simulateFillsAsync(orders, txReceipt, value);
await balanceStore.updateBalancesAsync();
@ -386,13 +345,12 @@ blockchainTests.resets('Coordinator integration tests', env => {
hexSlice(approval.signature, 6),
);
const transactionHash = transactionHashUtils.getTransactionHashHex(transaction);
const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[approvalSignature],
{ from: taker.address, value: DeploymentManager.protocolFee.times(orders.length) },
);
const tx = coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [approvalSignature])
.awaitTransactionSuccessAsync({
from: taker.address,
value: DeploymentManager.protocolFee.times(orders.length),
});
const expectedError = new CoordinatorRevertErrors.InvalidApprovalSignatureError(
transactionHash,
feeRecipient.address,
@ -400,13 +358,12 @@ blockchainTests.resets('Coordinator integration tests', env => {
return expect(tx).to.revertWith(expectedError);
});
it(`${fnName} should revert if not called by tx signer or approver`, async () => {
const tx = coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
taker.address,
transaction.signature,
[approval.signature],
{ from: maker.address, value: DeploymentManager.protocolFee.times(orders.length) },
);
const tx = coordinator
.executeTransaction(transaction, taker.address, transaction.signature, [approval.signature])
.awaitTransactionSuccessAsync({
from: maker.address,
value: DeploymentManager.protocolFee.times(orders.length),
});
const expectedError = new CoordinatorRevertErrors.InvalidOriginError(taker.address);
return expect(tx).to.revertWith(expectedError);
});
@ -431,13 +388,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
data,
gasPrice: DeploymentManager.gasPrice,
});
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
maker.address,
transaction.signature,
[],
{ from: maker.address },
);
const txReceipt = await coordinator
.executeTransaction(transaction, maker.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: maker.address });
verifyEvents(txReceipt, [expectedCancelEvent(order)], ExchangeEvents.Cancel);
});
@ -448,13 +401,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
data,
gasPrice: DeploymentManager.gasPrice,
});
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
maker.address,
transaction.signature,
[],
{ from: maker.address },
);
const txReceipt = await coordinator
.executeTransaction(transaction, maker.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: maker.address });
verifyEvents(txReceipt, orders.map(order => expectedCancelEvent(order)), ExchangeEvents.Cancel);
});
@ -464,13 +413,9 @@ blockchainTests.resets('Coordinator integration tests', env => {
data,
gasPrice: DeploymentManager.gasPrice,
});
const txReceipt = await coordinator.executeTransaction.awaitTransactionSuccessAsync(
transaction,
maker.address,
transaction.signature,
[],
{ from: maker.address },
);
const txReceipt = await coordinator
.executeTransaction(transaction, maker.address, transaction.signature, [])
.awaitTransactionSuccessAsync({ from: maker.address });
const expectedEvent: ExchangeCancelUpToEventArgs = {
makerAddress: maker.address,

View File

@ -38,7 +38,7 @@ async function batchAddAuthorizedAddressAsync(
): Promise<void> {
for (const authorizer of authorizers) {
for (const authority of authorities) {
await authorizer.addAuthorizedAddress.awaitTransactionSuccessAsync(authority, { from: owner });
await authorizer.addAuthorizedAddress(authority).awaitTransactionSuccessAsync({ from: owner });
}
}
}
@ -56,7 +56,7 @@ async function batchRegisterAssetProxyAsync(
): Promise<void> {
for (const registry of registries) {
for (const proxy of proxies) {
await registry.registerAssetProxy.awaitTransactionSuccessAsync(proxy, { from: owner });
await registry.registerAssetProxy(proxy).awaitTransactionSuccessAsync({ from: owner });
}
}
}
@ -73,7 +73,7 @@ async function batchTransferOwnershipAsync(
ownedContracts: Ownable[],
): Promise<void> {
for (const ownedContract of ownedContracts) {
await ownedContract.transferOwnership.awaitTransactionSuccessAsync(newOwner.address, { from: owner });
await ownedContract.transferOwnership(newOwner.address).awaitTransactionSuccessAsync({ from: owner });
}
}
@ -171,16 +171,16 @@ export class DeploymentManager {
await DeploymentManager._configureExchangeWithStakingAsync(exchange, staking, owner);
// Authorize the asset-proxy owner in the staking proxy and in the zrx vault.
await staking.stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address, {
await staking.stakingProxy.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync({
from: owner,
});
await staking.zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address, {
await staking.zrxVault.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync({
from: owner,
});
// Remove authorization for the original owner address.
await staking.stakingProxy.removeAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner });
await staking.zrxVault.removeAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner });
await staking.stakingProxy.removeAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner });
await staking.zrxVault.removeAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner });
// Transfer complete ownership of the system to the asset proxy owner.
await batchTransferOwnershipAsync(owner, governor, [
@ -275,13 +275,13 @@ export class DeploymentManager {
owner: string,
): Promise<void> {
// Configure the exchange for staking.
await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync(staking.stakingProxy.address, {
await exchange.setProtocolFeeCollectorAddress(staking.stakingProxy.address).awaitTransactionSuccessAsync({
from: owner,
});
await exchange.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(DeploymentManager.protocolFeeMultiplier);
await exchange.setProtocolFeeMultiplier(DeploymentManager.protocolFeeMultiplier).awaitTransactionSuccessAsync();
// Register the exchange contract in staking.
await staking.stakingWrapper.addExchangeAddress.awaitTransactionSuccessAsync(exchange.address, { from: owner });
await staking.stakingWrapper.addExchangeAddress(exchange.address).awaitTransactionSuccessAsync({ from: owner });
}
/**
@ -374,20 +374,20 @@ export class DeploymentManager {
const stakingWrapper = new TestStakingContract(stakingProxy.address, environment.provider, txDefaults);
// Add the zrx vault and the weth contract to the staking proxy.
await stakingWrapper.setWethContract.awaitTransactionSuccessAsync(tokens.weth.address, { from: owner });
await stakingWrapper.setZrxVault.awaitTransactionSuccessAsync(zrxVault.address, { from: owner });
await stakingWrapper.setWethContract(tokens.weth.address).awaitTransactionSuccessAsync({ from: owner });
await stakingWrapper.setZrxVault(zrxVault.address).awaitTransactionSuccessAsync({ from: owner });
// Authorize the owner address in the staking proxy and the zrx vault.
await stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner });
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(owner, { from: owner });
await stakingProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner });
await zrxVault.addAuthorizedAddress(owner).awaitTransactionSuccessAsync({ from: owner });
// Authorize the zrx vault in the erc20 proxy
await assetProxies.erc20Proxy.addAuthorizedAddress.awaitTransactionSuccessAsync(zrxVault.address, {
await assetProxies.erc20Proxy.addAuthorizedAddress(zrxVault.address).awaitTransactionSuccessAsync({
from: owner,
});
// Configure the zrx vault and the staking contract.
await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy.address, { from: owner });
await zrxVault.setStakingProxy(stakingProxy.address).awaitTransactionSuccessAsync({ from: owner });
return {
stakingLogic,

View File

@ -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(
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(
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(
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(
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);

View File

@ -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(
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<MarketSellOptions> = {},
): Promise<void> {
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(
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()) {

View File

@ -18,20 +18,20 @@ blockchainTests('Deployment Manager', env => {
authorizedContracts: Authorizable[],
): Promise<void> {
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<void> {
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,

View File

@ -24,11 +24,14 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => {
describe('executeAsync', () => {
it('should call the before function with the provided arguments', async () => {
let sideEffectTarget = ZERO_AMOUNT;
const assertion = new FunctionAssertion(exampleContract.returnInteger, {
const assertion = new FunctionAssertion<void, BigNumber>(
exampleContract.returnInteger.bind(exampleContract),
{
before: async (_input: BigNumber) => {
sideEffectTarget = randomInput;
},
});
},
);
const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256);
await assertion.executeAsync(randomInput);
expect(sideEffectTarget).bignumber.to.be.eq(randomInput);
@ -36,43 +39,52 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => {
it('should call the after function with the provided arguments', async () => {
let sideEffectTarget = ZERO_AMOUNT;
const assertion = new FunctionAssertion(exampleContract.returnInteger, {
const assertion = new FunctionAssertion<void, BigNumber>(
exampleContract.returnInteger.bind(exampleContract),
{
after: async (_beforeInfo: any, _result: FunctionResult, input: BigNumber) => {
sideEffectTarget = input;
},
});
},
);
const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256);
await assertion.executeAsync(randomInput);
expect(sideEffectTarget).bignumber.to.be.eq(randomInput);
});
it('should not fail immediately if the wrapped function fails', async () => {
const assertion = new FunctionAssertion<{}>(exampleContract.emptyRevert);
const assertion = new FunctionAssertion<{}, void>(exampleContract.emptyRevert.bind(exampleContract));
await assertion.executeAsync();
});
it('should pass the return value of "before" to "after"', async () => {
const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256);
let sideEffectTarget = ZERO_AMOUNT;
const assertion = new FunctionAssertion(exampleContract.returnInteger, {
const assertion = new FunctionAssertion<BigNumber, BigNumber>(
exampleContract.returnInteger.bind(exampleContract),
{
before: async (_input: BigNumber) => {
return randomInput;
},
after: async (beforeInfo: any, _result: FunctionResult, _input: BigNumber) => {
sideEffectTarget = beforeInfo;
},
});
},
);
await assertion.executeAsync(randomInput);
expect(sideEffectTarget).bignumber.to.be.eq(randomInput);
});
it('should pass the result from the function call to "after"', async () => {
let sideEffectTarget = ZERO_AMOUNT;
const assertion = new FunctionAssertion(exampleContract.returnInteger, {
const assertion = new FunctionAssertion<void, BigNumber>(
exampleContract.returnInteger.bind(exampleContract),
{
after: async (_beforeInfo: any, result: FunctionResult, _input: BigNumber) => {
sideEffectTarget = result.data;
},
});
},
);
const randomInput = getRandomInteger(ZERO_AMOUNT, MAX_UINT256);
await assertion.executeAsync(randomInput);
expect(sideEffectTarget).bignumber.to.be.eq(randomInput);
@ -80,7 +92,7 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => {
it('should pass the receipt from the function call to "after"', async () => {
let sideEffectTarget: TransactionReceiptWithDecodedLogs;
const assertion = new FunctionAssertion(exampleContract.emitEvent, {
const assertion = new FunctionAssertion<void, void>(exampleContract.emitEvent.bind(exampleContract), {
after: async (_beforeInfo: any, result: FunctionResult, _input: string) => {
if (result.receipt) {
sideEffectTarget = result.receipt;
@ -101,7 +113,7 @@ blockchainTests.resets('FunctionAssertion Unit Tests', env => {
it('should pass the error to "after" if the function call fails', async () => {
let sideEffectTarget: Error;
const assertion = new FunctionAssertion(exampleContract.stringRevert, {
const assertion = new FunctionAssertion<void, void>(exampleContract.stringRevert.bind(exampleContract), {
after: async (_beforeInfo: any, result: FunctionResult, _input: string) => {
sideEffectTarget = result.data;
},

View File

@ -15,13 +15,13 @@ import { DeploymentManager } from '../deployment_manager';
export function validCreateStakingPoolAssertion(
deployment: DeploymentManager,
pools: StakingPoolById,
): FunctionAssertion<string> {
): FunctionAssertion<string, string> {
const { stakingWrapper } = deployment.staking;
return new FunctionAssertion(stakingWrapper.createStakingPool, {
// Returns the expected ID of th created pool
before: async () => {
const lastPoolId = await stakingWrapper.lastPoolId.callAsync();
const lastPoolId = await stakingWrapper.lastPoolId().callAsync();
// Effectively the last poolId + 1, but as a bytestring
return `0x${new BigNumber(lastPoolId)
.plus(1)

View File

@ -12,15 +12,15 @@ import { DeploymentManager } from '../deployment_manager';
export function validDecreaseStakingPoolOperatorShareAssertion(
deployment: DeploymentManager,
pools: StakingPoolById,
): FunctionAssertion<{}> {
): FunctionAssertion<{}, void> {
const { stakingWrapper } = deployment.staking;
return new FunctionAssertion<{}>(stakingWrapper.decreaseStakingPoolOperatorShare, {
return new FunctionAssertion<{}, void>(stakingWrapper.decreaseStakingPoolOperatorShare, {
after: async (_beforeInfo, _result: FunctionResult, poolId: string, expectedOperatorShare: number) => {
logUtils.log(`decreaseStakingPoolOperatorShare(${poolId}, ${expectedOperatorShare})`);
// Checks that the on-chain pool's operator share has been updated.
const { operatorShare } = await stakingWrapper.getStakingPool.callAsync(poolId);
const { operatorShare } = await stakingWrapper.getStakingPool(poolId).callAsync();
expect(operatorShare).to.bignumber.equal(expectedOperatorShare);
// Updates the pool in local state.
pools[poolId].operatorShare = operatorShare;

View File

@ -81,10 +81,10 @@ export function validMoveStakeAssertion(
globalStake: GlobalStakeByStatus,
ownerStake: OwnerStakeByStatus,
pools: StakingPoolById,
): FunctionAssertion<{}> {
): FunctionAssertion<{}, void> {
const { stakingWrapper } = deployment.staking;
return new FunctionAssertion<{}>(stakingWrapper.moveStake, {
return new FunctionAssertion<{}, void>(stakingWrapper.moveStake, {
after: async (
_beforeInfo,
_result,
@ -107,30 +107,29 @@ export function validMoveStakeAssertion(
// Fetches on-chain owner stake balances and checks against local balances
const ownerUndelegatedStake = {
...new StoredBalance(),
...(await stakingWrapper.getOwnerStakeByStatus.callAsync(owner, StakeStatus.Undelegated)),
...(await stakingWrapper.getOwnerStakeByStatus(owner, StakeStatus.Undelegated).callAsync()),
};
const ownerDelegatedStake = {
...new StoredBalance(),
...(await stakingWrapper.getOwnerStakeByStatus.callAsync(owner, StakeStatus.Delegated)),
...(await stakingWrapper.getOwnerStakeByStatus(owner, StakeStatus.Delegated).callAsync()),
};
expect(ownerUndelegatedStake).to.deep.equal(ownerStake[StakeStatus.Undelegated]);
expect(ownerDelegatedStake).to.deep.equal(ownerStake[StakeStatus.Delegated].total);
// Fetches on-chain global stake balances and checks against local balances
const globalUndelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync(
StakeStatus.Undelegated,
);
const globalDelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync(StakeStatus.Delegated);
const globalUndelegatedStake = await stakingWrapper
.getGlobalStakeByStatus(StakeStatus.Undelegated)
.callAsync();
const globalDelegatedStake = await stakingWrapper.getGlobalStakeByStatus(StakeStatus.Delegated).callAsync();
expect(globalUndelegatedStake).to.deep.equal(globalStake[StakeStatus.Undelegated]);
expect(globalDelegatedStake).to.deep.equal(globalStake[StakeStatus.Delegated]);
// Fetches on-chain pool stake balances and checks against local balances
for (const poolId of updatedPools) {
const stakeDelegatedByOwner = await stakingWrapper.getStakeDelegatedToPoolByOwner.callAsync(
owner,
poolId,
);
const totalStakeDelegated = await stakingWrapper.getTotalStakeDelegatedToPool.callAsync(poolId);
const stakeDelegatedByOwner = await stakingWrapper
.getStakeDelegatedToPoolByOwner(owner, poolId)
.callAsync();
const totalStakeDelegated = await stakingWrapper.getTotalStakeDelegatedToPool(poolId).callAsync();
expect(stakeDelegatedByOwner).to.deep.equal(ownerStake[StakeStatus.Delegated][poolId]);
expect(totalStakeDelegated).to.deep.equal(pools[poolId].delegatedStake);
}

View File

@ -28,7 +28,7 @@ export function validStakeAssertion(
balanceStore: BlockchainBalanceStore,
globalStake: GlobalStakeByStatus,
ownerStake: OwnerStakeByStatus,
): FunctionAssertion<LocalBalanceStore> {
): FunctionAssertion<LocalBalanceStore, void> {
const { stakingWrapper, zrxVault } = deployment.staking;
return new FunctionAssertion(stakingWrapper.stake, {
@ -39,7 +39,7 @@ export function validStakeAssertion(
txData.from as string,
zrxVault.address,
amount,
await deployment.devUtils.encodeERC20AssetData.callAsync(deployment.tokens.zrx.address),
await deployment.devUtils.encodeERC20AssetData(deployment.tokens.zrx.address).callAsync(),
);
return expectedBalances;
},
@ -56,19 +56,18 @@ export function validStakeAssertion(
balanceStore.assertEquals(expectedBalances);
// Checks that the owner's undelegated stake has increased by the stake amount
const ownerUndelegatedStake = await stakingWrapper.getOwnerStakeByStatus.callAsync(
txData.from as string,
StakeStatus.Undelegated,
);
const ownerUndelegatedStake = await stakingWrapper
.getOwnerStakeByStatus(txData.from as string, StakeStatus.Undelegated)
.callAsync();
const expectedOwnerUndelegatedStake = expectedUndelegatedStake(ownerStake, amount);
expect(ownerUndelegatedStake, 'Owner undelegated stake').to.deep.equal(expectedOwnerUndelegatedStake);
// Updates local state accordingly
ownerStake[StakeStatus.Undelegated] = expectedOwnerUndelegatedStake;
// Checks that the global undelegated stake has also increased by the stake amount
const globalUndelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync(
StakeStatus.Undelegated,
);
const globalUndelegatedStake = await stakingWrapper
.getGlobalStakeByStatus(StakeStatus.Undelegated)
.callAsync();
const expectedGlobalUndelegatedStake = expectedUndelegatedStake(globalStake, amount);
expect(globalUndelegatedStake, 'Global undelegated stake').to.deep.equal(expectedGlobalUndelegatedStake);
// Updates local state accordingly

View File

@ -28,7 +28,7 @@ export function validUnstakeAssertion(
balanceStore: BlockchainBalanceStore,
globalStake: GlobalStakeByStatus,
ownerStake: OwnerStakeByStatus,
): FunctionAssertion<LocalBalanceStore> {
): FunctionAssertion<LocalBalanceStore, void> {
const { stakingWrapper, zrxVault } = deployment.staking;
return new FunctionAssertion(stakingWrapper.unstake, {
@ -39,7 +39,7 @@ export function validUnstakeAssertion(
zrxVault.address,
txData.from as string,
amount,
await deployment.devUtils.encodeERC20AssetData.callAsync(deployment.tokens.zrx.address),
await deployment.devUtils.encodeERC20AssetData(deployment.tokens.zrx.address).callAsync(),
);
return expectedBalances;
},
@ -56,19 +56,18 @@ export function validUnstakeAssertion(
balanceStore.assertEquals(expectedBalances);
// Checks that the owner's undelegated stake has decreased by the stake amount
const ownerUndelegatedStake = await stakingWrapper.getOwnerStakeByStatus.callAsync(
txData.from as string,
StakeStatus.Undelegated,
);
const ownerUndelegatedStake = await stakingWrapper
.getOwnerStakeByStatus(txData.from as string, StakeStatus.Undelegated)
.callAsync();
const expectedOwnerUndelegatedStake = expectedUndelegatedStake(ownerStake, amount);
expect(ownerUndelegatedStake, 'Owner undelegated stake').to.deep.equal(expectedOwnerUndelegatedStake);
// Updates local state accordingly
ownerStake[StakeStatus.Undelegated] = expectedOwnerUndelegatedStake;
// Checks that the global undelegated stake has also decreased by the stake amount
const globalUndelegatedStake = await stakingWrapper.getGlobalStakeByStatus.callAsync(
StakeStatus.Undelegated,
);
const globalUndelegatedStake = await stakingWrapper
.getGlobalStakeByStatus(StakeStatus.Undelegated)
.callAsync();
const expectedGlobalUndelegatedStake = expectedUndelegatedStake(globalStake, amount);
expect(globalUndelegatedStake, 'Global undelegated stake').to.deep.equal(expectedGlobalUndelegatedStake);
// Updates local state accordingly

View File

@ -115,7 +115,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
);
// Authorize owner in the staking proxy.
await stakingProxy.addAuthorizedAddress.awaitTransactionSuccessAsync(owner);
await stakingProxy.addAuthorizedAddress(owner).awaitTransactionSuccessAsync();
// Deploy the asset proxy contracts.
erc20Proxy = await ERC20ProxyContract.deployFrom0xArtifactAsync(
@ -163,12 +163,11 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
assetProxyId: string,
): Promise<void> {
// 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<ExchangeAssetProxyRegisteredEventArgs>(
@ -178,7 +177,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
expect(logs).to.be.deep.eq([{ id: assetProxyId, assetProxy: assetProxyAddress }]);
// Ensure that the asset proxy was actually registered.
const proxyAddress = await registrationContract.getAssetProxy.callAsync(assetProxyId);
const proxyAddress = await registrationContract.getAssetProxy(assetProxyId).callAsync();
expect(proxyAddress).to.be.eq(assetProxyAddress);
}
@ -188,10 +187,9 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
newAuthorityAddress: string,
): Promise<void> {
// 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<AuthorizableAuthorizedAddressAddedEventArgs>(
@ -201,7 +199,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
expect(logs).to.be.deep.eq([{ target: newAuthorityAddress, caller: owner }]);
// Ensure that the address was actually authorized.
const wasAuthorized = await authorizable.authorized.callAsync(newAuthorityAddress);
const wasAuthorized = await authorizable.authorized(newAuthorityAddress).callAsync();
expect(wasAuthorized).to.be.true();
}
@ -261,13 +259,13 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
describe('staking specific', () => {
it('should have properly configured the staking proxy with the logic contract', async () => {
// Ensure that the registered staking contract is correct.
const stakingAddress = await stakingProxy.stakingContract.callAsync();
const stakingAddress = await stakingProxy.stakingContract().callAsync();
expect(stakingAddress).to.be.eq(staking.address);
});
it('should have initialized the correct parameters in the staking proxy', async () => {
// Ensure that the correct parameters were set.
const params = await stakingWrapper.getParams.callAsync();
const params = await stakingWrapper.getParams().callAsync();
expect(params).to.be.deep.eq([
stakingConstants.DEFAULT_PARAMS.epochDurationInSeconds,
stakingConstants.DEFAULT_PARAMS.rewardDelegatedStakeWeight,
@ -281,7 +279,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
describe('exchange and staking integration', () => {
it('should successfully register the exchange in the staking contract', async () => {
// Register the exchange.
const receipt = await stakingWrapper.addExchangeAddress.awaitTransactionSuccessAsync(exchange.address, {
const receipt = await stakingWrapper.addExchangeAddress(exchange.address).awaitTransactionSuccessAsync({
from: owner,
});
@ -293,18 +291,17 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
expect(logs).to.be.deep.eq([{ exchangeAddress: exchange.address }]);
// Ensure that the exchange was registered.
const wasRegistered = await stakingWrapper.validExchanges.callAsync(exchange.address);
const wasRegistered = await stakingWrapper.validExchanges(exchange.address).callAsync();
expect(wasRegistered).to.be.true();
});
it('should successfully register the staking contract in the exchange', async () => {
// Register the staking contract.
const receipt = await exchange.setProtocolFeeCollectorAddress.awaitTransactionSuccessAsync(
stakingProxy.address,
{
const receipt = await exchange
.setProtocolFeeCollectorAddress(stakingProxy.address)
.awaitTransactionSuccessAsync({
from: owner,
},
);
});
// Ensure that the correct events were logged.
const logs = filterLogsToArguments<ExchangeProtocolFeeCollectorAddressEventArgs>(
@ -319,15 +316,15 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
]);
// Ensure that the staking contract was registered.
const feeCollector = await exchange.protocolFeeCollector.callAsync();
const feeCollector = await exchange.protocolFeeCollector().callAsync();
expect(feeCollector).to.be.eq(stakingProxy.address);
});
it('should successfully update the protocol fee multiplier in the staking contract', async () => {
// Update the protocol fee multiplier.
const receipt = await exchange.setProtocolFeeMultiplier.awaitTransactionSuccessAsync(
protocolFeeMultiplier,
);
const receipt = await exchange
.setProtocolFeeMultiplier(protocolFeeMultiplier)
.awaitTransactionSuccessAsync();
// Ensure that the correct events were logged.
const logs = filterLogsToArguments<ExchangeProtocolFeeMultiplierEventArgs>(
@ -342,7 +339,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
]);
// Ensure that the protocol fee multiplier was set correctly.
const multiplier = await exchange.protocolFeeMultiplier.callAsync();
const multiplier = await exchange.protocolFeeMultiplier().callAsync();
expect(multiplier).bignumber.to.be.eq(protocolFeeMultiplier);
});
});
@ -353,7 +350,7 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
// to the asset proxy owner.
async function transferAuthorizationAndAssertSuccessAsync(contract: Authorizable): Promise<void> {
// 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<AuthorizableAuthorizedAddressRemovedEventArgs>(
@ -363,11 +360,11 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
expect(logs).to.be.deep.eq([{ target: owner, caller: owner }]);
// Ensure that the owner was actually removed.
let isAuthorized = await contract.authorized.callAsync(owner);
let isAuthorized = await contract.authorized(owner).callAsync();
expect(isAuthorized).to.be.false();
// Authorize the asset-proxy owner.
receipt = await contract.addAuthorizedAddress.awaitTransactionSuccessAsync(governor.address, {
receipt = await contract.addAuthorizedAddress(governor.address).awaitTransactionSuccessAsync({
from: owner,
});
@ -379,17 +376,17 @@ blockchainTests('Deployment and Configuration End to End Tests', env => {
expect(logs).to.be.deep.eq([{ target: governor.address, caller: owner }]);
// Ensure that the asset-proxy owner was actually authorized.
isAuthorized = await contract.authorized.callAsync(governor.address);
isAuthorized = await contract.authorized(governor.address).callAsync();
expect(isAuthorized).to.be.true();
}
// Transfers ownership of a contract to the asset-proxy owner, and ensures that the change was actually made.
async function transferOwnershipAndAssertSuccessAsync(contract: Ownable): Promise<void> {
// 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);
}

View File

@ -1,15 +1,12 @@
import { artifacts as assetProxyArtifacts } from '@0x/contracts-asset-proxy';
import { DevUtilsContract } from '@0x/contracts-dev-utils';
import { artifacts as erc20Artifacts, ERC20TokenEvents, ERC20TokenTransferEventArgs } from '@0x/contracts-erc20';
import { ERC20TokenEvents, ERC20TokenTransferEventArgs } from '@0x/contracts-erc20';
import {
artifacts as exchangeArtifacts,
BlockchainBalanceStore,
IExchangeEvents,
IExchangeFillEventArgs,
LocalBalanceStore,
} from '@0x/contracts-exchange';
import { ReferenceFunctions } from '@0x/contracts-exchange-libs';
import { artifacts as stakingArtifacts } from '@0x/contracts-staking';
import {
blockchainTests,
constants,
@ -19,7 +16,6 @@ import {
Numberish,
provider,
toBaseUnitAmount,
TransactionHelper,
verifyEvents,
} from '@0x/contracts-test-utils';
import { ExchangeRevertErrors, orderHashUtils } from '@0x/order-utils';
@ -55,7 +51,6 @@ blockchainTests.resets('Exchange wrappers', env => {
let localBalances: LocalBalanceStore;
let wethAssetData: string;
let txHelper: TransactionHelper;
before(async () => {
[feeRecipient] = await env.getAccountAddressesAsync();
@ -70,10 +65,10 @@ blockchainTests.resets('Exchange wrappers', env => {
name: 'market maker',
deployment,
orderConfig: {
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[0].address),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[1].address),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[2].address),
takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.erc20[2].address),
makerAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[0].address).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[1].address).callAsync(),
makerFeeAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[2].address).callAsync(),
takerFeeAssetData: await devUtils.encodeERC20AssetData(deployment.tokens.erc20[2].address).callAsync(),
feeRecipientAddress: feeRecipient,
},
});
@ -111,14 +106,7 @@ blockchainTests.resets('Exchange wrappers', env => {
initialLocalBalances = LocalBalanceStore.create(devUtils, blockchainBalances);
wethAssetData = await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address);
txHelper = new TransactionHelper(env.web3Wrapper, {
...assetProxyArtifacts,
...exchangeArtifacts,
...stakingArtifacts,
...erc20Artifacts,
});
wethAssetData = await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync();
});
beforeEach(async () => {
@ -323,15 +311,16 @@ blockchainTests.resets('Exchange wrappers', env => {
makerAssetAmount: toBaseUnitAmount(new BigNumber(100)),
takerAssetAmount: toBaseUnitAmount(new BigNumber(200)),
});
const takerAssetFilledAmount = signedOrder.takerAssetAmount.div(2);
const takerAssetFilledAmount = signedOrder.takerAssetAmount.div(5);
const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync(
deployment.exchange.fillOrKillOrder,
const contractFn = deployment.exchange.fillOrKillOrder(
signedOrder,
takerAssetFilledAmount,
signedOrder.signature,
{ from: taker.address, gasPrice: DeploymentManager.gasPrice, value },
);
const callData = { from: taker.address, gasPrice: DeploymentManager.gasPrice, value };
const fillResults = await contractFn.callAsync(callData);
const receipt = await contractFn.awaitTransactionSuccessAsync(callData);
const expectedFillResults = calculateScaledFillResultsWithTaker(signedOrder, takerAssetFilledAmount);
@ -369,12 +358,13 @@ blockchainTests.resets('Exchange wrappers', env => {
});
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrder);
const expectedError = new ExchangeRevertErrors.OrderStatusError(orderHashHex, OrderStatus.Expired);
const tx = deployment.exchange.fillOrKillOrder.awaitTransactionSuccessAsync(
signedOrder,
signedOrder.takerAssetAmount,
signedOrder.signature,
{ from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee },
);
const tx = deployment.exchange
.fillOrKillOrder(signedOrder, signedOrder.takerAssetAmount, signedOrder.signature)
.awaitTransactionSuccessAsync({
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value: DeploymentManager.protocolFee,
});
return expect(tx).to.revertWith(expectedError);
});
@ -382,23 +372,25 @@ blockchainTests.resets('Exchange wrappers', env => {
const signedOrder = await maker.signOrderAsync();
const takerAssetFillAmount = signedOrder.takerAssetAmount;
await deployment.exchange.fillOrder.awaitTransactionSuccessAsync(
signedOrder,
signedOrder.takerAssetAmount.dividedToIntegerBy(2),
signedOrder.signature,
{ from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee },
);
await deployment.exchange
.fillOrder(signedOrder, signedOrder.takerAssetAmount.dividedToIntegerBy(2), signedOrder.signature)
.awaitTransactionSuccessAsync({
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value: DeploymentManager.protocolFee,
});
const expectedError = new ExchangeRevertErrors.IncompleteFillError(
ExchangeRevertErrors.IncompleteFillErrorCode.IncompleteFillOrder,
takerAssetFillAmount,
takerAssetFillAmount.dividedToIntegerBy(2),
);
const tx = deployment.exchange.fillOrKillOrder.awaitTransactionSuccessAsync(
signedOrder,
signedOrder.takerAssetAmount,
signedOrder.signature,
{ from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee },
);
const tx = deployment.exchange
.fillOrKillOrder(signedOrder, signedOrder.takerAssetAmount, signedOrder.signature)
.awaitTransactionSuccessAsync({
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value: DeploymentManager.protocolFee,
});
return expect(tx).to.revertWith(expectedError);
});
});
@ -441,20 +433,20 @@ blockchainTests.resets('Exchange wrappers', env => {
await simulateFillAsync(signedOrder, expectedFillResults, shouldPayWethFees);
}
const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync(
deployment.exchange.batchFillOrders,
const contractFn = deployment.exchange.batchFillOrders(
signedOrders,
takerAssetFillAmounts,
signedOrders.map(signedOrder => signedOrder.signature),
{
);
const callData = {
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value,
},
);
};
const fillResults = await contractFn.callAsync(callData);
const receipt = await contractFn.awaitTransactionSuccessAsync(callData);
expect(totalFillResults).to.be.deep.eq(fillResults);
await assertResultsAsync(receipt, fillTestInfo);
}
@ -503,17 +495,18 @@ blockchainTests.resets('Exchange wrappers', env => {
await simulateFillAsync(signedOrder, expectedFillResults, shouldPayWethFees);
}
const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync(
deployment.exchange.batchFillOrKillOrders,
const contractFn = deployment.exchange.batchFillOrKillOrders(
signedOrders,
takerAssetFillAmounts,
signedOrders.map(order => order.signature),
{
);
const callData = {
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value,
},
);
};
const fillResults = await contractFn.callAsync(callData);
const receipt = await contractFn.awaitTransactionSuccessAsync(callData);
expect(totalFillResults).to.be.deep.eq(fillResults);
@ -535,25 +528,27 @@ blockchainTests.resets('Exchange wrappers', env => {
it('should revert if a single signedOrder does not fill the expected amount', async () => {
const takerAssetFillAmounts = signedOrders.map(signedOrder => signedOrder.takerAssetAmount.div(2));
await deployment.exchange.fillOrKillOrder.awaitTransactionSuccessAsync(
signedOrders[0],
signedOrders[0].takerAssetAmount,
signedOrders[0].signature,
{ from: taker.address, gasPrice: DeploymentManager.gasPrice, value: DeploymentManager.protocolFee },
);
await deployment.exchange
.fillOrKillOrder(signedOrders[0], signedOrders[0].takerAssetAmount, signedOrders[0].signature)
.awaitTransactionSuccessAsync({
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value: DeploymentManager.protocolFee,
});
const orderHashHex = orderHashUtils.getOrderHashHex(signedOrders[0]);
const expectedError = new ExchangeRevertErrors.OrderStatusError(orderHashHex, OrderStatus.FullyFilled);
const tx = deployment.exchange.batchFillOrKillOrders.awaitTransactionSuccessAsync(
const tx = deployment.exchange
.batchFillOrKillOrders(
signedOrders,
takerAssetFillAmounts,
signedOrders.map(order => order.signature),
{
)
.awaitTransactionSuccessAsync({
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value: DeploymentManager.protocolFee.times(signedOrders.length),
},
);
});
return expect(tx).to.revertWith(expectedError);
});
});
@ -597,19 +592,20 @@ blockchainTests.resets('Exchange wrappers', env => {
}
}
const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync(
deployment.exchange.batchFillOrdersNoThrow,
const contractFn = deployment.exchange.batchFillOrdersNoThrow(
signedOrdersWithValidity.map(signedOrderWithValidity => signedOrderWithValidity.signedOrder),
takerAssetFillAmounts,
signedOrdersWithValidity.map(
signedOrderWithValidity => signedOrderWithValidity.signedOrder.signature,
),
{
);
const callData = {
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value,
},
);
};
const fillResults = await contractFn.callAsync(callData);
const receipt = await contractFn.awaitTransactionSuccessAsync(callData);
expect(totalFillResults).to.be.deep.eq(fillResults);
@ -712,18 +708,18 @@ blockchainTests.resets('Exchange wrappers', env => {
}
}
const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync(
deployment.exchange.marketSellOrdersNoThrow,
const contractFn = deployment.exchange.marketSellOrdersNoThrow(
signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder),
takerAssetFillAmount,
signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder.signature),
{
);
const callData = {
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value,
},
);
};
const fillResults = await contractFn.callAsync(callData);
const receipt = await contractFn.awaitTransactionSuccessAsync(callData);
expect(fillResults).to.deep.equal(totalFillResults);
await assertResultsAsync(receipt, fillTestInfo);
@ -782,9 +778,9 @@ blockchainTests.resets('Exchange wrappers', env => {
});
it('should fill a signedOrder that does not use the same takerAssetAddress (eth protocol fee)', async () => {
const differentTakerAssetData = await devUtils.encodeERC20AssetData.callAsync(
deployment.tokens.erc20[2].address,
);
const differentTakerAssetData = await devUtils
.encodeERC20AssetData(deployment.tokens.erc20[2].address)
.callAsync();
signedOrders = [
await maker.signOrderAsync(),
@ -805,9 +801,9 @@ blockchainTests.resets('Exchange wrappers', env => {
});
it('should fill a signedOrder that does not use the same takerAssetAddress (weth protocol fee)', async () => {
const differentTakerAssetData = await devUtils.encodeERC20AssetData.callAsync(
deployment.tokens.erc20[2].address,
);
const differentTakerAssetData = await devUtils
.encodeERC20AssetData(deployment.tokens.erc20[2].address)
.callAsync();
signedOrders = [
await maker.signOrderAsync(),
@ -910,18 +906,18 @@ blockchainTests.resets('Exchange wrappers', env => {
}
}
const [fillResults, receipt] = await txHelper.getResultAndReceiptAsync(
deployment.exchange.marketBuyOrdersNoThrow,
const contractFn = deployment.exchange.marketBuyOrdersNoThrow(
signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder),
makerAssetFillAmount,
signedOrdersWithValidity.map(orderWithValidity => orderWithValidity.signedOrder.signature),
{
);
const callData = {
from: taker.address,
gasPrice: DeploymentManager.gasPrice,
value,
},
);
};
const fillResults = await contractFn.callAsync(callData);
const receipt = await contractFn.awaitTransactionSuccessAsync(callData);
expect(fillResults).to.deep.equal(totalFillResults);
await assertResultsAsync(receipt, fillTestInfo);
@ -980,9 +976,9 @@ blockchainTests.resets('Exchange wrappers', env => {
});
it('should fill a signedOrder that does not use the same makerAssetAddress (eth protocol fee)', async () => {
const differentMakerAssetData = await devUtils.encodeERC20AssetData.callAsync(
deployment.tokens.erc20[2].address,
);
const differentMakerAssetData = await devUtils
.encodeERC20AssetData(deployment.tokens.erc20[2].address)
.callAsync();
signedOrders = [
await maker.signOrderAsync(),
@ -1004,9 +1000,9 @@ blockchainTests.resets('Exchange wrappers', env => {
});
it('should fill a signedOrder that does not use the same makerAssetAddress (weth protocol fee)', async () => {
const differentMakerAssetData = await devUtils.encodeERC20AssetData.callAsync(
deployment.tokens.erc20[2].address,
);
const differentMakerAssetData = await devUtils
.encodeERC20AssetData(deployment.tokens.erc20[2].address)
.callAsync();
signedOrders = [
await maker.signOrderAsync(),
@ -1070,7 +1066,7 @@ blockchainTests.resets('Exchange wrappers', env => {
describe('batchCancelOrders', () => {
it('should be able to cancel multiple signedOrders', async () => {
const receipt = await deployment.exchange.batchCancelOrders.awaitTransactionSuccessAsync(signedOrders, {
const receipt = await deployment.exchange.batchCancelOrders(signedOrders).awaitTransactionSuccessAsync({
from: maker.address,
});
const expectedOrderHashes = signedOrders.map(order => orderHashUtils.getOrderHashHex(order));
@ -1081,13 +1077,13 @@ blockchainTests.resets('Exchange wrappers', env => {
});
it('should not revert if a single cancel noops', async () => {
await deployment.exchange.cancelOrder.awaitTransactionSuccessAsync(signedOrders[1], {
await deployment.exchange.cancelOrder(signedOrders[1]).awaitTransactionSuccessAsync({
from: maker.address,
});
const expectedOrderHashes = [signedOrders[0], ...signedOrders.slice(2)].map(order =>
orderHashUtils.getOrderHashHex(order),
);
const receipt = await deployment.exchange.batchCancelOrders.awaitTransactionSuccessAsync(signedOrders, {
const receipt = await deployment.exchange.batchCancelOrders(signedOrders).awaitTransactionSuccessAsync({
from: maker.address,
});

View File

@ -52,10 +52,10 @@ blockchainTests.resets('fillOrder integration tests', env => {
});
const orderConfig = {
feeRecipientAddress: feeRecipient.address,
makerAssetData: await devUtils.encodeERC20AssetData.callAsync(makerToken.address),
takerAssetData: await devUtils.encodeERC20AssetData.callAsync(takerToken.address),
makerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(makerToken.address),
takerFeeAssetData: await devUtils.encodeERC20AssetData.callAsync(takerToken.address),
makerAssetData: await devUtils.encodeERC20AssetData(makerToken.address).callAsync(),
takerAssetData: await devUtils.encodeERC20AssetData(takerToken.address).callAsync(),
makerFeeAssetData: await devUtils.encodeERC20AssetData(makerToken.address).callAsync(),
takerFeeAssetData: await devUtils.encodeERC20AssetData(takerToken.address).callAsync(),
makerFee: constants.ZERO_AMOUNT,
takerFee: constants.ZERO_AMOUNT,
};
@ -136,7 +136,7 @@ blockchainTests.resets('fillOrder integration tests', env => {
taker.address,
deployment.staking.stakingProxy.address,
DeploymentManager.protocolFee,
await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address),
await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(),
);
}
@ -227,7 +227,7 @@ blockchainTests.resets('fillOrder integration tests', env => {
// now expect a `StakingPoolEarnedRewardsInEpoch` event to be emitted because the staking
// pool now has enough stake in the current epoch to earn rewards.
verifyFillEvents(order, receipt);
const currentEpoch = await deployment.staking.stakingWrapper.currentEpoch.callAsync();
const currentEpoch = await deployment.staking.stakingWrapper.currentEpoch().callAsync();
verifyEvents<IStakingEventsStakingPoolEarnedRewardsInEpochEventArgs>(
receipt,
[
@ -256,7 +256,7 @@ blockchainTests.resets('fillOrder integration tests', env => {
// End the epoch. This should wrap the staking proxy's ETH balance.
const endEpochReceipt = await delegator.endEpochAsync();
const newEpoch = await deployment.staking.stakingWrapper.currentEpoch.callAsync();
const newEpoch = await deployment.staking.stakingWrapper.currentEpoch().callAsync();
// Check balances
expectedBalances.wrapEth(
@ -300,7 +300,7 @@ blockchainTests.resets('fillOrder integration tests', env => {
deployment.staking.stakingProxy.address,
operator.address,
operatorReward,
await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address),
await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(),
);
expectedBalances.burnGas(delegator.address, DeploymentManager.gasPrice.times(finalizePoolReceipt.gasUsed));
await balanceStore.updateBalancesAsync();
@ -341,7 +341,7 @@ blockchainTests.resets('fillOrder integration tests', env => {
await taker.fillOrderAsync(order, order.takerAssetAmount);
// Check that the pool has collected fees from the above fill.
const poolStats = await deployment.staking.stakingWrapper.getStakingPoolStatsThisEpoch.callAsync(poolId);
const poolStats = await deployment.staking.stakingWrapper.getStakingPoolStatsThisEpoch(poolId).callAsync();
expect(poolStats.feesCollected).to.bignumber.equal(DeploymentManager.protocolFee);
});
it('should collect WETH fees and pay out rewards', async () => {
@ -382,7 +382,7 @@ blockchainTests.resets('fillOrder integration tests', env => {
deployment.staking.stakingProxy.address,
operator.address,
operatorReward,
await devUtils.encodeERC20AssetData.callAsync(deployment.tokens.weth.address),
await devUtils.encodeERC20AssetData(deployment.tokens.weth.address).callAsync(),
);
expectedBalances.burnGas(delegator.address, DeploymentManager.gasPrice.times(finalizePoolReceipt.gasUsed));
await balanceStore.updateBalancesAsync();

View File

@ -1,53 +1,21 @@
import { PromiseWithTransactionHash } from '@0x/base-contract';
import { AwaitTransactionSuccessOpts } from '@0x/types';
import { BlockParam, CallData, TransactionReceiptWithDecodedLogs, TxData } from 'ethereum-types';
import { ContractFunctionObj, ContractTxFunctionObj } from '@0x/base-contract';
import { BlockParam, CallData } from 'ethereum-types';
// tslint:disable:max-classes-per-file
// Generated Wrapper Interfaces
export interface AssetProxyDispatcher {
registerAssetProxy: {
awaitTransactionSuccessAsync: (
assetProxy: string,
txData?: Partial<TxData>,
txOpts?: AwaitTransactionSuccessOpts,
) => PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs>;
};
getAssetProxy: {
callAsync(assetProxyId: string, callData?: Partial<CallData>, defaultBlock?: BlockParam): Promise<string>;
};
export abstract class AssetProxyDispatcher {
public abstract registerAssetProxy(assetProxy: string): ContractTxFunctionObj<void>;
public abstract getAssetProxy(assetProxyId: string): ContractFunctionObj<string>;
}
export interface Authorizable extends Ownable {
addAuthorizedAddress: {
awaitTransactionSuccessAsync: (
target: string,
txData?: Partial<TxData>,
txOpts?: AwaitTransactionSuccessOpts,
) => PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs>;
};
removeAuthorizedAddress: {
awaitTransactionSuccessAsync: (
target: string,
txData?: Partial<TxData>,
txOpts?: AwaitTransactionSuccessOpts,
) => PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs>;
};
authorized: {
callAsync(authority: string, callData?: Partial<CallData>, defaultBlock?: BlockParam): Promise<boolean>;
};
getAuthorizedAddresses: {
callAsync(callData?: Partial<CallData>, defaultBlock?: BlockParam): Promise<string[]>;
};
}
export abstract class Ownable {
public abstract transferOwnership(newOwner: string): ContractTxFunctionObj<void>;
export interface Ownable {
transferOwnership: {
awaitTransactionSuccessAsync: (
newOwner: string,
txData?: Partial<TxData>,
txOpts?: AwaitTransactionSuccessOpts,
) => PromiseWithTransactionHash<TransactionReceiptWithDecodedLogs>;
};
owner: {
callAsync(callData?: Partial<CallData>, defaultBlock?: BlockParam): Promise<string>;
};
public abstract owner(callData?: Partial<CallData>, defaultBlock?: BlockParam): ContractFunctionObj<string>;
}
export abstract class Authorizable extends Ownable {
public abstract addAuthorizedAddress(target: string): ContractTxFunctionObj<void>;
public abstract removeAuthorizedAddress(target: string): ContractTxFunctionObj<void>;
public abstract authorized(authority: string): ContractFunctionObj<boolean>;
public abstract getAuthorizedAddresses(): ContractFunctionObj<string[]>;
}

View File

@ -126,9 +126,9 @@ describe('MultiSigWalletWithTimeLock', () => {
});
it('should confirm transaction for caller but not reset the confirmation time if tx is already fully confirmed', async () => {
await multiSigWrapper.confirmTransactionAsync(txId, owners[1]);
const confirmationTimeBefore = await multiSig.confirmationTimes.callAsync(txId);
const confirmationTimeBefore = await multiSig.confirmationTimes(txId).callAsync();
const txReceipt = await multiSigWrapper.confirmTransactionAsync(txId, owners[2]);
const confirmationTimeAfter = await multiSig.confirmationTimes.callAsync(txId);
const confirmationTimeAfter = await multiSig.confirmationTimes(txId).callAsync();
expect(confirmationTimeBefore).to.bignumber.equal(confirmationTimeAfter);
expect(txReceipt.logs.length).to.equal(1);
const log = txReceipt.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockConfirmationEventArgs>;
@ -256,25 +256,25 @@ describe('MultiSigWalletWithTimeLock', () => {
it('should revert when not called by wallet', async () => {
return expectTransactionFailedWithoutReasonAsync(
multiSig.changeTimeLock.sendTransactionAsync(SECONDS_TIME_LOCKED, { from: owners[0] }),
multiSig.changeTimeLock(SECONDS_TIME_LOCKED).sendTransactionAsync({ from: owners[0] }),
);
});
it('should revert without enough confirmations', async () => {
const destination = multiSig.address;
const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED);
const changeTimeLockData = multiSig.changeTimeLock(SECONDS_TIME_LOCKED).getABIEncodedTransactionData();
const res = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]);
const log = res.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockSubmissionEventArgs>;
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<MultiSigWalletWithTimeLockSubmissionEventArgs>;
const txId = subLog.args.transactionId;
@ -288,14 +288,14 @@ describe('MultiSigWalletWithTimeLock', () => {
throw new Error(`Unexpectedly failed to fetch block at #${blockNum}`);
}
const timestamp = new BigNumber(blockInfo.timestamp);
const confirmationTimeBigNum = new BigNumber(await multiSig.confirmationTimes.callAsync(txId));
const confirmationTimeBigNum = new BigNumber(await multiSig.confirmationTimes(txId).callAsync());
expect(timestamp).to.be.bignumber.equal(confirmationTimeBigNum);
});
it('should be executable with enough confirmations and secondsTimeLocked of 0', async () => {
const destination = multiSig.address;
const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(SECONDS_TIME_LOCKED);
const changeTimeLockData = multiSig.changeTimeLock(SECONDS_TIME_LOCKED).getABIEncodedTransactionData();
const subRes = await multiSigWrapper.submitTransactionAsync(destination, changeTimeLockData, owners[0]);
const subLog = subRes.logs[0] as LogWithDecodedArgs<MultiSigWalletWithTimeLockSubmissionEventArgs>;
const txId = subLog.args.transactionId;
@ -303,7 +303,7 @@ describe('MultiSigWalletWithTimeLock', () => {
await multiSigWrapper.confirmTransactionAsync(txId, owners[1]);
await multiSigWrapper.executeTransactionAsync(txId, owners[1]);
const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked.callAsync());
const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked().callAsync());
expect(secondsTimeLocked).to.be.bignumber.equal(SECONDS_TIME_LOCKED);
});
});
@ -328,7 +328,7 @@ describe('MultiSigWalletWithTimeLock', () => {
);
multiSigWrapper = new MultiSigWrapper(multiSig, provider);
const changeTimeLockData = multiSig.changeTimeLock.getABIEncodedTransactionData(newSecondsTimeLocked);
const changeTimeLockData = multiSig.changeTimeLock(newSecondsTimeLocked).getABIEncodedTransactionData();
const res = await multiSigWrapper.submitTransactionAsync(
multiSig.address,
changeTimeLockData,
@ -341,19 +341,21 @@ describe('MultiSigWalletWithTimeLock', () => {
it('should revert if it has enough confirmations but is not past the time lock', async () => {
return expectTransactionFailedAsync(
multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }),
multiSig.executeTransaction(txId).sendTransactionAsync({ from: owners[0] }),
RevertReason.TimeLockIncomplete,
);
});
it('should execute if it has enough confirmations and is past the time lock', async () => {
await increaseTimeAndMineBlockAsync(SECONDS_TIME_LOCKED.toNumber());
await web3Wrapper.awaitTransactionSuccessAsync(
await multiSig.executeTransaction.sendTransactionAsync(txId, { from: owners[0] }),
constants.AWAIT_TRANSACTION_MINED_MS,
await multiSig
.executeTransaction(txId)
.awaitTransactionSuccessAsync(
{ from: owners[0] },
{ pollingIntervalMs: constants.AWAIT_TRANSACTION_MINED_MS },
);
const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked.callAsync());
const secondsTimeLocked = new BigNumber(await multiSig.secondsTimeLocked().callAsync());
expect(secondsTimeLocked).to.be.bignumber.equal(newSecondsTimeLocked);
});
});

View File

@ -25,19 +25,19 @@ export class MultiSigWrapper {
opts: { value?: BigNumber } = {},
): Promise<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
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<TransactionReceiptWithDecodedLogs> {
const txHash = await this._multiSig.executeTransaction.sendTransactionAsync(txId, {
const txHash = await this._multiSig.executeTransaction(txId).sendTransactionAsync({
from,
gas: opts.gas,
});

View File

@ -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(
const txReceipt = await this._governor
.submitTransaction(
hexRandom(20), // submitTransaction will fail if this is a null address
constants.ZERO_AMOUNT,
batchTransactionData,
{ from },
);
)
.awaitTransactionSuccessAsync({ from });
const txId = (txReceipt.logs[0] as LogWithDecodedArgs<ZeroExGovernorSubmissionEventArgs>).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 };
}
}

View File

@ -158,10 +158,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
new BigNumber(REQUIRED_SIGNERS),
new BigNumber(DEFAULT_TIME_LOCK),
);
const timelock = await governorContract.functionCallTimeLocks.callAsync(
reg.functionSelectors[0],
reg.destinations[0],
);
const timelock = await governorContract
.functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0])
.callAsync();
expect(timelock[0]).to.equal(true);
expect(timelock[1]).to.bignumber.equal(reg.functionCallTimeLockSeconds[0]);
});
@ -180,10 +179,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
new BigNumber(DEFAULT_TIME_LOCK),
);
for (const [index, selector] of reg.functionSelectors.entries()) {
const timelock = await governorContract.functionCallTimeLocks.callAsync(
selector,
reg.destinations[index],
);
const timelock = await governorContract
.functionCallTimeLocks(selector, reg.destinations[index])
.callAsync();
expect(timelock[0]).to.equal(true);
expect(timelock[1]).to.bignumber.equal(reg.functionCallTimeLockSeconds[index]);
}
@ -193,23 +191,26 @@ blockchainTests.resets('ZeroExGovernor', env => {
blockchainTests.resets('registerFunctionCall', () => {
it('should revert if not called by wallet', async () => {
const reg = createFunctionRegistration(1, 1, 1);
const tx = governor.registerFunctionCall.awaitTransactionSuccessAsync(
const tx = governor
.registerFunctionCall(
true,
reg.functionSelectors[0],
reg.destinations[0],
reg.functionCallTimeLockSeconds[0],
{ from: signerAddresses[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(
const txReceipt = await governor
.registerFunctionCallBypassWallet(
true,
reg.functionSelectors[0],
reg.destinations[0],
reg.functionCallTimeLockSeconds[0],
);
)
.awaitTransactionSuccessAsync();
expect(txReceipt.logs.length).to.eq(1);
const logArgs = (txReceipt.logs[0] as LogWithDecodedArgs<
ZeroExGovernorFunctionCallTimeLockRegistrationEventArgs
@ -218,53 +219,53 @@ blockchainTests.resets('ZeroExGovernor', env => {
expect(logArgs.destination).to.eq(reg.destinations[0]);
expect(logArgs.hasCustomTimeLock).to.eq(true);
expect(logArgs.newSecondsTimeLocked).to.bignumber.eq(reg.functionCallTimeLockSeconds[0]);
const timelock = await governor.functionCallTimeLocks.callAsync(
reg.functionSelectors[0],
reg.destinations[0],
);
const timelock = await governor
.functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0])
.callAsync();
expect(timelock[0]).to.equal(true);
expect(timelock[1]).to.bignumber.equal(reg.functionCallTimeLockSeconds[0]);
});
it('should be able to overwrite existing function calls', async () => {
const reg = createFunctionRegistration(1, 1, 1);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
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(
await governor
.registerFunctionCallBypassWallet(
true,
reg.functionSelectors[0],
reg.destinations[0],
reg.functionCallTimeLockSeconds[0],
);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
)
.awaitTransactionSuccessAsync();
await governor
.registerFunctionCallBypassWallet(
false,
reg.functionSelectors[0],
reg.destinations[0],
reg.functionCallTimeLockSeconds[0],
);
const timelock = await governor.functionCallTimeLocks.callAsync(
reg.functionSelectors[0],
reg.destinations[0],
);
)
.awaitTransactionSuccessAsync();
const timelock = await governor
.functionCallTimeLocks(reg.functionSelectors[0], reg.destinations[0])
.callAsync();
expect(timelock[0]).to.equal(false);
expect(timelock[1]).to.bignumber.equal(constants.ZERO_AMOUNT);
});
@ -272,11 +273,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
describe('assertValidFunctionCall', () => {
it('should revert if the data is less than 4 bytes long', async () => {
const result = governor.assertValidFunctionCall.callAsync(
constants.ZERO_AMOUNT,
constants.NULL_BYTES,
constants.NULL_ADDRESS,
);
const result = governor
.assertValidFunctionCall(constants.ZERO_AMOUNT, constants.NULL_BYTES, constants.NULL_ADDRESS)
.callAsync();
const expectedError = new LibBytesRevertErrors.InvalidByteOperationError(
LibBytesRevertErrors.InvalidByteOperationErrorCodes.LengthGreaterThanOrEqualsFourRequired,
constants.ZERO_AMOUNT,
@ -288,91 +287,87 @@ blockchainTests.resets('ZeroExGovernor', env => {
const latestTimestamp = await getLatestBlockTimestampAsync();
const transactionConfirmationTime = new BigNumber(latestTimestamp);
const reg = createFunctionRegistration(1, 1, 1);
const result = governor.assertValidFunctionCall.callAsync(
transactionConfirmationTime,
reg.functionSelectors[0],
reg.destinations[0],
);
const result = governor
.assertValidFunctionCall(transactionConfirmationTime, reg.functionSelectors[0], reg.destinations[0])
.callAsync();
expect(result).to.revertWith(RevertReason.DefaultTimeLockIncomplete);
});
it('should revert if a registered function is called before the custom timelock', async () => {
const reg = createFunctionRegistration(1, 1, 1);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
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(
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(
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(
await governor
.registerFunctionCallBypassWallet(
true,
reg.functionSelectors[0],
reg.destinations[0],
constants.ZERO_AMOUNT,
);
)
.awaitTransactionSuccessAsync();
const latestTimestamp = await getLatestBlockTimestampAsync();
const result = governor.assertValidFunctionCall.callAsync(
new BigNumber(latestTimestamp),
reg.functionSelectors[0],
reg.destinations[0],
);
const result = governor
.assertValidFunctionCall(new BigNumber(latestTimestamp), reg.functionSelectors[0], reg.destinations[0])
.callAsync();
expect(result).to.be.fulfilled('');
});
});
@ -402,7 +397,7 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom()];
const destinations = [receiver.address];
const results = await governorWrapper.submitTransactionAsync(data, destinations, signerAddresses[0]);
const tx = governor.executeTransaction.awaitTransactionSuccessAsync(results.txId, {
const tx = governor.executeTransaction(results.txId).awaitTransactionSuccessAsync({
from: signerAddresses[1],
});
expect(tx).to.revertWith(RevertReason.TxNotFullyConfirmed);
@ -411,7 +406,7 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom()];
const destinations = [receiver.address];
const results = await governorWrapper.submitTransactionAsync(data, destinations, signerAddresses[0]);
const tx = governor.executeTransaction.awaitTransactionSuccessAsync(results.txId, {
const tx = governor.executeTransaction(results.txId).awaitTransactionSuccessAsync({
from: signerAddresses[0],
});
expect(tx).to.revertWith(RevertReason.TxNotFullyConfirmed);
@ -444,12 +439,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom()];
const destinations = [receiver.address];
const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
true,
data[0].slice(0, 10),
receiver.address,
newTimeLock,
);
await governor
.registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock)
.awaitTransactionSuccessAsync();
const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync(
data,
destinations,
@ -462,12 +454,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom()];
const destinations = [receiver.address];
const newTimeLock = constants.ZERO_AMOUNT;
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
true,
data[0].slice(0, 10),
receiver.address,
newTimeLock,
);
await governor
.registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock)
.awaitTransactionSuccessAsync();
const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync(
data,
destinations,
@ -480,12 +469,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom()];
const destinations = [receiver.address];
const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
true,
data[0].slice(0, 10),
receiver.address,
newTimeLock,
);
await governor
.registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock)
.awaitTransactionSuccessAsync();
const values = [INITIAL_BALANCE];
const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync(
data,
@ -530,12 +516,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom(), hexRandom()];
const destinations = [receiver.address, receiver.address];
const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
true,
data[0].slice(0, 10),
receiver.address,
newTimeLock,
);
await governor
.registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock)
.awaitTransactionSuccessAsync();
const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync(
data,
destinations,
@ -548,12 +531,9 @@ blockchainTests.resets('ZeroExGovernor', env => {
const data = [hexRandom(), hexRandom()];
const destinations = [receiver.address, receiver.address];
const newTimeLock = new BigNumber(DEFAULT_TIME_LOCK).dividedToIntegerBy(2);
await governor.registerFunctionCallBypassWallet.awaitTransactionSuccessAsync(
true,
data[0].slice(0, 10),
receiver.address,
newTimeLock,
);
await governor
.registerFunctionCallBypassWallet(true, data[0].slice(0, 10), receiver.address, newTimeLock)
.awaitTransactionSuccessAsync();
const tx = governorWrapper.submitConfirmAndExecuteTransactionAsync(
data,
destinations,
@ -630,7 +610,7 @@ blockchainTests.resets('ZeroExGovernor', env => {
signerAddresses,
DEFAULT_TIME_LOCK,
);
const tx = governor.executeTransaction.awaitTransactionSuccessAsync(results.txId);
const tx = governor.executeTransaction(results.txId).awaitTransactionSuccessAsync();
expect(tx).to.revertWith(RevertReason.TxAlreadyExecuted);
});
it('should revert if the only call is unsuccessful', async () => {
@ -660,12 +640,14 @@ blockchainTests.resets('ZeroExGovernor', env => {
it('should be able to call registerFunctionCall after the default timelock', async () => {
const reg = createFunctionRegistration(1, 1, 1);
const data = [
governor.registerFunctionCall.getABIEncodedTransactionData(
governor
.registerFunctionCall(
true,
reg.functionSelectors[0],
reg.destinations[0],
reg.functionCallTimeLockSeconds[0],
),
)
.getABIEncodedTransactionData(),
];
const destinations = [governor.address];
const results = await governorWrapper.submitConfirmAndExecuteTransactionAsync(

View File

@ -131,9 +131,17 @@ export class FinalizerActor extends BaseActor {
for (const delegator of delegators) {
let balance = new BigNumber(delegatorBalancesByPoolId[poolId][delegator] || 0);
if (delegator === operator) {
balance = balance.plus(await computeRewardBalanceOfOperator.callAsync(poolId));
balance = balance.plus(
await computeRewardBalanceOfOperator
.bind(this._stakingApiWrapper.stakingContract)(poolId)
.callAsync(),
);
} else {
balance = balance.plus(await computeRewardBalanceOfDelegator.callAsync(poolId, delegator));
balance = balance.plus(
await computeRewardBalanceOfDelegator
.bind(this._stakingApiWrapper.stakingContract)(poolId, delegator)
.callAsync(),
);
}
delegatorBalancesByPoolId[poolId][delegator] = balance;
}
@ -144,16 +152,16 @@ export class FinalizerActor extends BaseActor {
private async _getDelegatorStakesByPoolIdAsync(
delegatorsByPoolId: DelegatorsByPoolId,
): Promise<DelegatorBalancesByPoolId> {
const { getStakeDelegatedToPoolByOwner } = this._stakingApiWrapper.stakingContract;
const delegatorBalancesByPoolId: DelegatorBalancesByPoolId = {};
for (const poolId of Object.keys(delegatorsByPoolId)) {
const delegators = delegatorsByPoolId[poolId];
delegatorBalancesByPoolId[poolId] = {};
for (const delegator of delegators) {
delegatorBalancesByPoolId[poolId][delegator] = (await getStakeDelegatedToPoolByOwner.callAsync(
delegator,
poolId,
)).currentEpochBalance;
delegatorBalancesByPoolId[poolId][
delegator
] = (await this._stakingApiWrapper.stakingContract
.getStakeDelegatedToPoolByOwner(delegator, poolId)
.callAsync()).currentEpochBalance;
}
}
return delegatorBalancesByPoolId;
@ -208,9 +216,9 @@ export class FinalizerActor extends BaseActor {
): Promise<OperatorBalanceByPoolId> {
const operatorBalanceByPoolId: OperatorBalanceByPoolId = {};
for (const poolId of Object.keys(operatorByPoolId)) {
operatorBalanceByPoolId[poolId] = await this._stakingApiWrapper.wethContract.balanceOf.callAsync(
operatorByPoolId[poolId],
);
operatorBalanceByPoolId[poolId] = await this._stakingApiWrapper.wethContract
.balanceOf(operatorByPoolId[poolId])
.callAsync();
}
return operatorBalanceByPoolId;
}
@ -219,7 +227,7 @@ export class FinalizerActor extends BaseActor {
const operatorShareByPoolId: OperatorShareByPoolId = {};
for (const poolId of poolIds) {
operatorShareByPoolId[poolId] = new BigNumber(
(await this._stakingApiWrapper.stakingContract.getStakingPool.callAsync(poolId)).operatorShare,
(await this._stakingApiWrapper.stakingContract.getStakingPool(poolId).callAsync()).operatorShare,
);
}
return operatorShareByPoolId;
@ -228,9 +236,9 @@ export class FinalizerActor extends BaseActor {
private async _getRewardBalanceByPoolIdAsync(poolIds: string[]): Promise<RewardBalanceByPoolId> {
const rewardBalanceByPoolId: RewardBalanceByPoolId = {};
for (const poolId of poolIds) {
rewardBalanceByPoolId[poolId] = await this._stakingApiWrapper.stakingContract.rewardsByPoolId.callAsync(
poolId,
);
rewardBalanceByPoolId[poolId] = await this._stakingApiWrapper.stakingContract
.rewardsByPoolId(poolId)
.callAsync();
}
return rewardBalanceByPoolId;
}
@ -238,7 +246,7 @@ export class FinalizerActor extends BaseActor {
private async _getRewardByPoolIdAsync(poolIds: string[]): Promise<RewardByPoolId> {
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();

View File

@ -7,17 +7,16 @@ import { PoolOperatorActor } from './pool_operator_actor';
export class MakerActor extends PoolOperatorActor {
public async joinStakingPoolAsMakerAsync(poolId: string, revertError?: RevertError): Promise<void> {
// 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);
}
}

View File

@ -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<void> {
// 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);
}
}

View File

@ -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<void> {
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<StakeBalances> {
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;
}

View File

@ -33,14 +33,14 @@ blockchainTests('Epochs', env => {
///// 2/3 Validate Initial Epoch & TimeLock Period /////
{
// epoch
const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync();
const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch().callAsync();
expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH);
}
///// 3/3 Increment Epoch (TimeLock Should Not Increment) /////
await stakingApiWrapper.utils.skipToNextEpochAndFinalizeAsync();
{
// epoch
const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync();
const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch().callAsync();
expect(currentEpoch).to.be.bignumber.equal(stakingConstants.INITIAL_EPOCH.plus(1));
}
});

View File

@ -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<void> {
@ -75,12 +75,12 @@ blockchainTests('Migration tests', env => {
}
async function assertInitStateAsync(proxyContract: TestStakingProxyContract): Promise<void> {
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<TestStakingProxyStakingContractAttachedToProxyEventArgs>(
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({
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({
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({
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({
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({
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({
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({
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({
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({
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({
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM),
});
})
.awaitTransactionSuccessAsync();
return expect(tx).to.be.fulfilled('');
});
});

View File

@ -41,7 +41,7 @@ blockchainTests('Staking Pool Management', env => {
const poolId = await poolOperator.createStakingPoolAsync(operatorShare, false);
expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID);
// check that the next pool id was incremented
const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId.callAsync();
const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId().callAsync();
expect(lastPoolId).to.be.equal(stakingConstants.INITIAL_POOL_ID);
});
it('Should successfully create several staking pools, as long as the operator is only a maker in one', async () => {
@ -78,7 +78,7 @@ blockchainTests('Staking Pool Management', env => {
const poolId = await poolOperator.createStakingPoolAsync(operatorShare, true);
expect(poolId).to.be.equal(stakingConstants.INITIAL_POOL_ID);
// check that the next pool id was incremented
const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId.callAsync();
const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId().callAsync();
expect(lastPoolId).to.be.equal(stakingConstants.INITIAL_POOL_ID);
});
it('Should throw if operatorShare is > PPM_DENOMINATOR', async () => {

View File

@ -59,7 +59,7 @@ blockchainTests.resets('Testing Rewards', env => {
poolOperatorStaker = new StakerActor(poolOperator.getOwner(), stakingApiWrapper);
await poolOperatorStaker.stakeWithPoolAsync(poolId, new BigNumber(2));
// set exchange address
await stakingApiWrapper.stakingContract.addExchangeAddress.awaitTransactionSuccessAsync(exchangeAddress);
await stakingApiWrapper.stakingContract.addExchangeAddress(exchangeAddress).awaitTransactionSuccessAsync();
// associate operators for tracking in Finalizer
const operatorByPoolId: OperatorByPoolId = {};
operatorByPoolId[poolId] = poolOperator.getOwner();
@ -118,21 +118,19 @@ blockchainTests.resets('Testing Rewards', env => {
};
const finalEndBalancesAsArray = await Promise.all([
// staker 1
stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync(
poolId,
stakers[0].getOwner(),
),
stakingApiWrapper.wethContract.balanceOf.callAsync(stakers[0].getOwner()),
stakingApiWrapper.stakingContract
.computeRewardBalanceOfDelegator(poolId, stakers[0].getOwner())
.callAsync(),
stakingApiWrapper.wethContract.balanceOf(stakers[0].getOwner()).callAsync(),
// staker 2
stakingApiWrapper.stakingContract.computeRewardBalanceOfDelegator.callAsync(
poolId,
stakers[1].getOwner(),
),
stakingApiWrapper.wethContract.balanceOf.callAsync(stakers[1].getOwner()),
stakingApiWrapper.stakingContract
.computeRewardBalanceOfDelegator(poolId, stakers[1].getOwner())
.callAsync(),
stakingApiWrapper.wethContract.balanceOf(stakers[1].getOwner()).callAsync(),
// operator
stakingApiWrapper.wethContract.balanceOf.callAsync(poolOperator.getOwner()),
stakingApiWrapper.wethContract.balanceOf(poolOperator.getOwner()).callAsync(),
// undivided balance in reward pool
stakingApiWrapper.stakingContract.rewardsByPoolId.callAsync(poolId),
stakingApiWrapper.stakingContract.rewardsByPoolId(poolId).callAsync(),
]);
expect(finalEndBalancesAsArray[0], 'stakerRewardBalance_1').to.be.bignumber.equal(
expectedEndBalances.stakerRewardBalance_1,
@ -156,12 +154,9 @@ blockchainTests.resets('Testing Rewards', env => {
const payProtocolFeeAndFinalize = async (_fee?: BigNumber) => {
const fee = _fee !== undefined ? _fee : constants.ZERO_AMOUNT;
if (!fee.eq(constants.ZERO_AMOUNT)) {
await stakingApiWrapper.stakingContract.payProtocolFee.awaitTransactionSuccessAsync(
poolOperator.getOwner(),
takerAddress,
fee,
{ from: exchangeAddress, value: fee },
);
await stakingApiWrapper.stakingContract
.payProtocolFee(poolOperator.getOwner(), takerAddress, fee)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: fee });
}
await finalizer.finalizeAsync();
};
@ -575,7 +570,7 @@ blockchainTests.resets('Testing Rewards', env => {
await payProtocolFeeAndFinalize();
// this should go to the delegator
await payProtocolFeeAndFinalize(rewardForDelegator);
await stakingApiWrapper.stakingContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync(poolId, {
await stakingApiWrapper.stakingContract.withdrawDelegatorRewards(poolId).awaitTransactionSuccessAsync({
from: stakers[0].getOwner(),
});
// sanity check final balances
@ -595,18 +590,15 @@ blockchainTests.resets('Testing Rewards', env => {
new StakeInfo(StakeStatus.Delegated, poolId),
stakeAmount,
);
await stakingApiWrapper.stakingContract.payProtocolFee.awaitTransactionSuccessAsync(
poolOperator.getOwner(),
takerAddress,
rewardForDelegator,
{ from: exchangeAddress, value: rewardForDelegator },
);
const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch.callAsync();
await stakingApiWrapper.stakingContract
.payProtocolFee(poolOperator.getOwner(), takerAddress, rewardForDelegator)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: rewardForDelegator });
const currentEpoch = await stakingApiWrapper.stakingContract.currentEpoch().callAsync();
await stakingApiWrapper.utils.fastForwardToNextEpochAsync();
await stakingApiWrapper.utils.endEpochAsync();
const expectedError = new StakingRevertErrors.PoolNotFinalizedError(poolId, currentEpoch);
expect(
stakingApiWrapper.stakingContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync(poolId, {
stakingApiWrapper.stakingContract.withdrawDelegatorRewards(poolId).awaitTransactionSuccessAsync({
from: stakers[0].getOwner(),
}),
).to.revertWith(expectedError);
@ -689,16 +681,18 @@ blockchainTests.resets('Testing Rewards', env => {
const sneakyStakerExpectedWethBalance = expectedStakerRewards[0];
await sneakyStaker.withdrawDelegatorRewardsAsync(poolId);
// Should have been credited the correct amount of rewards.
let sneakyStakerWethBalance = await stakingApiWrapper.wethContract.balanceOf.callAsync(
sneakyStaker.getOwner(),
);
let sneakyStakerWethBalance = await stakingApiWrapper.wethContract
.balanceOf(sneakyStaker.getOwner())
.callAsync();
expect(sneakyStakerWethBalance, 'WETH balance after first undelegate').to.bignumber.eq(
sneakyStakerExpectedWethBalance,
);
// Now he'll try to do it again to see if he gets credited twice.
await sneakyStaker.withdrawDelegatorRewardsAsync(poolId);
/// The total amount credited should remain the same.
sneakyStakerWethBalance = await stakingApiWrapper.wethContract.balanceOf.callAsync(sneakyStaker.getOwner());
sneakyStakerWethBalance = await stakingApiWrapper.wethContract
.balanceOf(sneakyStaker.getOwner())
.callAsync();
expect(sneakyStakerWethBalance, 'WETH balance after second undelegate').to.bignumber.eq(
sneakyStakerExpectedWethBalance,
);

View File

@ -45,7 +45,7 @@ blockchainTests.resets('Stake Statuses', env => {
await stakingApiWrapper.utils.createStakingPoolAsync(poolOperator, 4, false),
await stakingApiWrapper.utils.createStakingPoolAsync(poolOperator, 5, false),
]);
const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId.callAsync();
const lastPoolId = await stakingApiWrapper.stakingContract.lastPoolId().callAsync();
unusedPoolId = `0x${new BigNumber(lastPoolId)
.plus(1)
.toString(16)

View File

@ -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(
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(
await testContract
.setUnfinalizedPoolReward(
_opts.poolId,
_opts.operator,
new BigNumber(_opts.operatorReward),
new BigNumber(_opts.membersReward),
new BigNumber(_opts.membersStake),
);
)
.awaitTransactionSuccessAsync();
// Because the operator share is implicitly defined by the member and
// operator reward, and is stored as a uint32, there will be precision
// loss when the reward is combined then split again in the contracts.
@ -148,8 +152,10 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
stake: getRandomInteger(1, toBaseUnitAmount(10)),
...opts,
};
const fn = now ? testContract.delegateStakeNow : testContract.delegateStake;
const receipt = await fn.awaitTransactionSuccessAsync(_opts.delegator, poolId, new BigNumber(_opts.stake));
const fn = now
? testContract.delegateStakeNow.bind(testContract)
: testContract.delegateStake.bind(testContract);
const receipt = await fn(_opts.delegator, poolId, new BigNumber(_opts.stake)).awaitTransactionSuccessAsync();
const delegatorTransfers = getTransfersFromLogs(receipt.logs, _opts.delegator);
return {
..._opts,
@ -164,9 +170,9 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
): Promise<ResultWithTransfers<{ stake: BigNumber }>> {
const _stake = new BigNumber(
stake ||
(await testContract.getStakeDelegatedToPoolByOwner.callAsync(delegator, poolId)).currentEpochBalance,
(await testContract.getStakeDelegatedToPoolByOwner(delegator, poolId).callAsync()).currentEpochBalance,
);
const receipt = await testContract.undelegateStake.awaitTransactionSuccessAsync(delegator, poolId, _stake);
const receipt = await testContract.undelegateStake(delegator, poolId, _stake).awaitTransactionSuccessAsync();
const delegatorTransfers = getTransfersFromLogs(receipt.logs, delegator);
return {
stake: _stake,
@ -189,17 +195,17 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
}
async function advanceEpochAsync(): Promise<number> {
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<BigNumber> {
return testContract.computeRewardBalanceOfDelegator.callAsync(poolId, delegator);
return testContract.computeRewardBalanceOfDelegator(poolId, delegator).callAsync();
}
async function getOperatorRewardBalanceAsync(poolId: string): Promise<BigNumber> {
return testContract.computeRewardBalanceOfOperator.callAsync(poolId);
return testContract.computeRewardBalanceOfOperator(poolId).callAsync();
}
async function touchStakeAsync(poolId: string, delegator: string): Promise<ResultWithTransfers<{}>> {
@ -207,7 +213,7 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
}
async function finalizePoolAsync(poolId: string): Promise<ResultWithTransfers<{}>> {
const receipt = await testContract.finalizePool.awaitTransactionSuccessAsync(poolId);
const receipt = await testContract.finalizePool(poolId).awaitTransactionSuccessAsync();
const delegatorTransfers = getTransfersFromLogs(receipt.logs, poolId);
return {
delegatorTransfers,

View File

@ -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);

View File

@ -76,13 +76,15 @@ blockchainTests.resets('Finalizer unit tests', env => {
weightedStake: getRandomInteger(0, maxAmount),
...opts,
};
await testContract.addActivePool.awaitTransactionSuccessAsync(
await testContract
.addActivePool(
_opts.poolId,
new BigNumber(_opts.operatorShare * constants.PPM_DENOMINATOR).integerValue(),
new BigNumber(_opts.feesCollected),
new BigNumber(_opts.membersStake),
new BigNumber(_opts.weightedStake),
);
)
.awaitTransactionSuccessAsync();
return _opts;
}
@ -95,13 +97,13 @@ blockchainTests.resets('Finalizer unit tests', env => {
}
async function getUnfinalizedStateAsync(): Promise<UnfinalizedState> {
return testContract.getAggregatedStatsForPreviousEpoch.callAsync();
return testContract.getAggregatedStatsForPreviousEpoch().callAsync();
}
async function finalizePoolsAsync(poolIds: string[]): Promise<LogEntry[]> {
const logs = [] as LogEntry[];
for (const poolId of poolIds) {
const receipt = await testContract.finalizePool.awaitTransactionSuccessAsync(poolId);
const receipt = await testContract.finalizePool(poolId).awaitTransactionSuccessAsync();
logs.splice(logs.length, 0, ...receipt.logs);
}
return logs;
@ -208,13 +210,15 @@ blockchainTests.resets('Finalizer unit tests', env => {
if (feesCollected.isZero()) {
continue;
}
poolRewards[i] = await testContract.cobbDouglas.callAsync(
poolRewards[i] = await testContract
.cobbDouglas(
new BigNumber(rewardsAvailable),
new BigNumber(feesCollected),
new BigNumber(totalFees),
new BigNumber(pool.weightedStake),
new BigNumber(totalStake),
);
)
.callAsync();
}
return poolRewards;
}
@ -257,7 +261,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
}
async function getCurrentEpochAsync(): Promise<BigNumber> {
return testContract.currentEpoch.callAsync();
return testContract.currentEpoch().callAsync();
}
async function getBalanceOfAsync(whom: string): Promise<BigNumber> {
@ -266,13 +270,13 @@ blockchainTests.resets('Finalizer unit tests', env => {
describe('endEpoch()', () => {
it('advances the epoch', async () => {
await testContract.endEpoch.awaitTransactionSuccessAsync();
const currentEpoch = await testContract.currentEpoch.callAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const currentEpoch = await testContract.currentEpoch().callAsync();
expect(currentEpoch).to.bignumber.eq(stakingConstants.INITIAL_EPOCH.plus(1));
});
it('emits an `EpochEnded` event', async () => {
const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync();
assertEpochEndedEvent(receipt.logs, {
epoch: stakingConstants.INITIAL_EPOCH,
numActivePools: ZERO_AMOUNT,
@ -283,7 +287,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
});
it('immediately finalizes if there are no pools to finalize', async () => {
const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync();
assertEpochFinalizedEvent(receipt.logs, {
epoch: stakingConstants.INITIAL_EPOCH,
rewardsPaid: ZERO_AMOUNT,
@ -293,7 +297,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('does not immediately finalize if there is a pool to finalize', async () => {
await addActivePoolAsync();
const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync();
const events = filterLogsToArguments<IStakingEventsEpochFinalizedEventArgs>(
receipt.logs,
IStakingEventsEvents.EpochFinalized,
@ -304,7 +308,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('prepares unfinalized state', async () => {
// Add a pool so there is state to clear.
const pool = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
return assertUnfinalizedStateAsync({
numPoolsToFinalize: 1,
rewardsAvailable: INITIAL_BALANCE,
@ -315,9 +319,9 @@ blockchainTests.resets('Finalizer unit tests', env => {
it("correctly stores the epoch's aggregated stats after ending the epoch", async () => {
const pool = await addActivePoolAsync();
const epoch = await testContract.currentEpoch.callAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
const aggregatedStats = await testContract.aggregatedStatsByEpoch.callAsync(epoch);
const epoch = await testContract.currentEpoch().callAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const aggregatedStats = await testContract.aggregatedStatsByEpoch(epoch).callAsync();
expect(aggregatedStats).to.be.deep.equal([
INITIAL_BALANCE,
new BigNumber(1), // pools to finalize
@ -329,8 +333,8 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('reverts if the prior epoch is unfinalized', async () => {
await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
const tx = testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const tx = testContract.endEpoch().awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.PreviousEpochNotFinalizedError(
stakingConstants.INITIAL_EPOCH,
1,
@ -341,7 +345,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
describe('_finalizePool()', () => {
it('does nothing if there were no pools to finalize', async () => {
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const poolId = hexRandom();
const logs = await finalizePoolsAsync([poolId]);
expect(logs).to.deep.eq([]);
@ -349,21 +353,21 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('can finalize a pool', async () => {
const pool = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const logs = await finalizePoolsAsync([pool.poolId]);
return assertFinalizationLogsAndBalancesAsync(INITIAL_BALANCE, [pool], logs);
});
it('can finalize multiple pools over multiple transactions', async () => {
const pools = await Promise.all(_.times(2, async () => addActivePoolAsync()));
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const logs = await finalizePoolsAsync(pools.map(p => p.poolId));
return assertFinalizationLogsAndBalancesAsync(INITIAL_BALANCE, pools, logs);
});
it('ignores a finalized pool', async () => {
const pools = await Promise.all(_.times(3, async () => addActivePoolAsync()));
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const [finalizedPool] = _.sampleSize(pools, 1);
await finalizePoolsAsync([finalizedPool.poolId]);
const logs = await finalizePoolsAsync([finalizedPool.poolId]);
@ -374,12 +378,11 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('resets pool state after finalizing it', async () => {
const pools = await Promise.all(_.times(3, async () => addActivePoolAsync()));
const pool = _.sample(pools) as ActivePoolOpts;
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await finalizePoolsAsync([pool.poolId]);
const poolState = await testContract.getPoolStatsFromEpoch.callAsync(
stakingConstants.INITIAL_EPOCH,
pool.poolId,
);
const poolState = await testContract
.getPoolStatsFromEpoch(stakingConstants.INITIAL_EPOCH, pool.poolId)
.callAsync();
expect(poolState.feesCollected).to.bignumber.eq(0);
expect(poolState.weightedStake).to.bignumber.eq(0);
expect(poolState.membersStake).to.bignumber.eq(0);
@ -387,7 +390,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('`rewardsPaid` <= `rewardsAvailable` <= contract balance at the end of the epoch', async () => {
const pools = await Promise.all(_.times(3, async () => addActivePoolAsync()));
const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync();
const { rewardsAvailable } = getEpochEndedEvents(receipt.logs)[0];
expect(rewardsAvailable).to.bignumber.lte(INITIAL_BALANCE);
const logs = await finalizePoolsAsync(pools.map(r => r.poolId));
@ -398,7 +401,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('`rewardsPaid` <= `rewardsAvailable` with two equal pools', async () => {
const pool1 = await addActivePoolAsync();
const pool2 = await addActivePoolAsync(_.omit(pool1, 'poolId'));
const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync();
const { rewardsAvailable } = getEpochEndedEvents(receipt.logs)[0];
const logs = await finalizePoolsAsync([pool1, pool2].map(r => r.poolId));
const { rewardsPaid } = getEpochFinalizedEvents(logs)[0];
@ -411,7 +414,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
const numPools = _.random(1, 32);
it(`${i + 1}/${numTests} \`rewardsPaid\` <= \`rewardsAvailable\` (${numPools} pools)`, async () => {
const pools = await Promise.all(_.times(numPools, async () => addActivePoolAsync()));
const receipt = await testContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await testContract.endEpoch().awaitTransactionSuccessAsync();
const { rewardsAvailable } = getEpochEndedEvents(receipt.logs)[0];
const logs = await finalizePoolsAsync(pools.map(r => r.poolId));
const { rewardsPaid } = getEpochFinalizedEvents(logs)[0];
@ -424,18 +427,18 @@ blockchainTests.resets('Finalizer unit tests', env => {
describe('lifecycle', () => {
it('can advance the epoch after the prior epoch is finalized', async () => {
const pool = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await finalizePoolsAsync([pool.poolId]);
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
return expect(getCurrentEpochAsync()).to.become(stakingConstants.INITIAL_EPOCH.plus(2));
});
it('does not reward a pool that only earned rewards 2 epochs ago', async () => {
const pool1 = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await finalizePoolsAsync([pool1.poolId]);
await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
expect(getCurrentEpochAsync()).to.become(stakingConstants.INITIAL_EPOCH.plus(2));
const logs = await finalizePoolsAsync([pool1.poolId]);
const rewardsPaidEvents = getRewardsPaidEvents(logs);
@ -444,11 +447,11 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('does not reward a pool that only earned rewards 3 epochs ago', async () => {
const pool1 = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await finalizePoolsAsync([pool1.poolId]);
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
expect(getCurrentEpochAsync()).to.become(stakingConstants.INITIAL_EPOCH.plus(3));
const logs = await finalizePoolsAsync([pool1.poolId]);
const rewardsPaidEvents = getRewardsPaidEvents(logs);
@ -458,11 +461,11 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('rolls over leftover rewards into the next epoch', async () => {
const poolIds = _.times(3, () => hexRandom());
await Promise.all(poolIds.map(async id => addActivePoolAsync({ poolId: id })));
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const finalizeLogs = await finalizePoolsAsync(poolIds);
const { rewardsRemaining: rolledOverRewards } = getEpochFinalizedEvents(finalizeLogs)[0];
await Promise.all(poolIds.map(async id => addActivePoolAsync({ poolId: id })));
const { logs: endEpochLogs } = await testContract.endEpoch.awaitTransactionSuccessAsync();
const { logs: endEpochLogs } = await testContract.endEpoch().awaitTransactionSuccessAsync();
const { rewardsAvailable } = getEpochEndedEvents(endEpochLogs)[0];
expect(rewardsAvailable).to.bignumber.eq(rolledOverRewards);
});
@ -477,7 +480,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
poolId: string,
expected: Partial<FinalizedPoolRewards>,
): Promise<void> {
const actual = await testContract.getUnfinalizedPoolRewards.callAsync(poolId);
const actual = await testContract.getUnfinalizedPoolRewards(poolId).callAsync();
if (expected.totalReward !== undefined) {
expect(actual.totalReward).to.bignumber.eq(expected.totalReward);
}
@ -498,7 +501,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
});
it('returns empty if pool did not earn rewards', async () => {
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const poolId = hexRandom();
return assertUnfinalizedPoolRewardsAsync(poolId, ZERO_REWARDS);
});
@ -510,7 +513,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('returns empty if pool only earned rewards in the 2 epochs ago', async () => {
const pool = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await finalizePoolsAsync([pool.poolId]);
return assertUnfinalizedPoolRewardsAsync(pool.poolId, ZERO_REWARDS);
});
@ -518,14 +521,14 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('returns empty if pool was already finalized', async () => {
const pools = await Promise.all(_.times(3, async () => addActivePoolAsync()));
const [pool] = _.sampleSize(pools, 1);
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
await finalizePoolsAsync([pool.poolId]);
return assertUnfinalizedPoolRewardsAsync(pool.poolId, ZERO_REWARDS);
});
it('computes one reward among one pool', async () => {
const pool = await addActivePoolAsync();
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const expectedTotalRewards = INITIAL_BALANCE;
return assertUnfinalizedPoolRewardsAsync(pool.poolId, {
totalReward: expectedTotalRewards,
@ -535,7 +538,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('computes one reward among multiple pools', async () => {
const pools = await Promise.all(_.times(3, async () => addActivePoolAsync()));
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
const expectedPoolRewards = await calculatePoolRewardsAsync(INITIAL_BALANCE, pools);
const [pool, reward] = _.sampleSize(shortZip(pools, expectedPoolRewards), 1)[0];
return assertUnfinalizedPoolRewardsAsync(pool.poolId, {
@ -546,7 +549,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('computes a reward with 0% operatorShare', async () => {
const pool = await addActivePoolAsync({ operatorShare: 0 });
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
return assertUnfinalizedPoolRewardsAsync(pool.poolId, {
totalReward: INITIAL_BALANCE,
membersStake: pool.membersStake,
@ -555,7 +558,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('computes a reward with 0% < operatorShare < 100%', async () => {
const pool = await addActivePoolAsync({ operatorShare: Math.random() });
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
return assertUnfinalizedPoolRewardsAsync(pool.poolId, {
totalReward: INITIAL_BALANCE,
membersStake: pool.membersStake,
@ -564,7 +567,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
it('computes a reward with 100% operatorShare', async () => {
const pool = await addActivePoolAsync({ operatorShare: 1 });
await testContract.endEpoch.awaitTransactionSuccessAsync();
await testContract.endEpoch().awaitTransactionSuccessAsync();
return assertUnfinalizedPoolRewardsAsync(pool.poolId, {
totalReward: INITIAL_BALANCE,
membersStake: pool.membersStake,

View File

@ -56,7 +56,8 @@ blockchainTests('LibCobbDouglas unit tests', env => {
...DEFAULT_COBB_DOUGLAS_PARAMS,
...params,
};
return testContract.cobbDouglas.callAsync(
return testContract
.cobbDouglas(
new BigNumber(_params.totalRewards),
new BigNumber(_params.ownerFees),
new BigNumber(_params.totalFees),
@ -64,10 +65,10 @@ blockchainTests('LibCobbDouglas unit tests', env => {
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<CobbDouglasParams>): BigNumber {

View File

@ -41,7 +41,7 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('one()', () => {
it('equals 1', async () => {
const r = await testContract.one.callAsync();
const r = await testContract.one().callAsync();
assertFixedEquals(r, 1);
});
});
@ -49,25 +49,25 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('abs()', () => {
it('abs(n) == n', async () => {
const n = 1337.5912;
const r = await testContract.abs.callAsync(toFixed(n));
const r = await testContract.abs(toFixed(n)).callAsync();
assertFixedEquals(r, n);
});
it('abs(-n) == n', async () => {
const n = -1337.5912;
const r = await testContract.abs.callAsync(toFixed(n));
const r = await testContract.abs(toFixed(n)).callAsync();
assertFixedEquals(r, -n);
});
it('abs(0) == 0', async () => {
const n = 0;
const r = await testContract.abs.callAsync(toFixed(n));
const r = await testContract.abs(toFixed(n)).callAsync();
expect(r).to.bignumber.eq(0);
});
it('abs(MAX_FIXED) == MAX_FIXED', async () => {
const n = MAX_FIXED_VALUE;
const r = await testContract.abs.callAsync(n);
const r = await testContract.abs(n).callAsync();
expect(r).to.bignumber.eq(n);
});
@ -77,19 +77,19 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooSmall,
n,
);
const tx = testContract.abs.callAsync(n);
const tx = testContract.abs(n).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('abs(int(-1)) == int(1)', async () => {
const n = -1;
const r = await testContract.abs.callAsync(new BigNumber(n));
const r = await testContract.abs(new BigNumber(n)).callAsync();
expect(r).to.bignumber.eq(1);
});
it('abs(int(1)) == int(1)', async () => {
const n = 1;
const r = await testContract.abs.callAsync(new BigNumber(n));
const r = await testContract.abs(new BigNumber(n)).callAsync();
expect(r).to.bignumber.eq(1);
});
});
@ -97,19 +97,19 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('invert()', () => {
it('invert(1) == 1', async () => {
const n = 1;
const r = await testContract.invert.callAsync(toFixed(n));
const r = await testContract.invert(toFixed(n)).callAsync();
assertFixedEquals(r, n);
});
it('invert(n) == 1 / n', async () => {
const n = 1337.5912;
const r = await testContract.invert.callAsync(toFixed(n));
const r = await testContract.invert(toFixed(n)).callAsync();
assertFixedRoughlyEquals(r, 1 / n);
});
it('invert(-n) == -1 / n', async () => {
const n = -1337.5912;
const r = await testContract.invert.callAsync(toFixed(n));
const r = await testContract.invert(toFixed(n)).callAsync();
assertFixedRoughlyEquals(r, 1 / n);
});
@ -117,7 +117,7 @@ blockchainTests('LibFixedMath unit tests', env => {
const expectedError = new FixedMathRevertErrors.BinOpError(
FixedMathRevertErrors.BinOpErrorCodes.DivisionByZero,
);
const tx = testContract.invert.callAsync(toFixed(0));
const tx = testContract.invert(toFixed(0)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -125,31 +125,31 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('mulDiv()', () => {
it('mulDiv(0, 0, 1) == 0', async () => {
const [a, n, d] = [0, 0, 1];
const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, 0);
});
it('mulDiv(0, x, y) == 0', async () => {
const [a, n, d] = [0, 13, 300];
const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, 0);
});
it('mulDiv(x, y, y) == x', async () => {
const [a, n, d] = [1.2345, 149, 149];
const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, a);
});
it('mulDiv(x, -y, y) == -x', async () => {
const [a, n, d] = [1.2345, -149, 149];
const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, -a);
});
it('mulDiv(-x, -y, y) == x', async () => {
const [a, n, d] = [-1.2345, -149, 149];
const r = await testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, -a);
});
@ -158,19 +158,19 @@ blockchainTests('LibFixedMath unit tests', env => {
const expectedError = new FixedMathRevertErrors.BinOpError(
FixedMathRevertErrors.BinOpErrorCodes.DivisionByZero,
);
const tx = testContract.mulDiv.callAsync(toFixed(a), new BigNumber(n), new BigNumber(d));
const tx = testContract.mulDiv(toFixed(a), new BigNumber(n), new BigNumber(d)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('mulDiv(int(-1), int(1), int(-1)) == int(1)', async () => {
const [a, n, d] = [-1, 1, -1];
const r = await testContract.mulDiv.callAsync(new BigNumber(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(new BigNumber(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, fromFixed(1));
});
it('mulDiv(int(1), int(-1), int(-1)) == int(1)', async () => {
const [a, n, d] = [1, -1, -1];
const r = await testContract.mulDiv.callAsync(new BigNumber(a), new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(new BigNumber(a), new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, fromFixed(1));
});
@ -181,7 +181,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
n,
);
const tx = testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d));
const tx = testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -192,7 +192,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
n,
);
const tx = testContract.mulDiv.callAsync(new BigNumber(a), n, new BigNumber(d));
const tx = testContract.mulDiv(new BigNumber(a), n, new BigNumber(d)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -203,19 +203,19 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
d,
);
const tx = testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d));
const tx = testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('mulDiv(MAX_FIXED, int(-1), int(1)) == -MAX_FIXED', async () => {
const [a, n, d] = [MAX_FIXED_VALUE, -1, 1];
const r = await testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync();
expect(r).to.bignumber.eq(MAX_FIXED_VALUE.negated());
});
it('mulDiv(MAX_FIXED, int(1), int(-1)) == -MAX_FIXED', async () => {
const [a, n, d] = [MAX_FIXED_VALUE, 1, -1];
const r = await testContract.mulDiv.callAsync(a, new BigNumber(n), new BigNumber(d));
const r = await testContract.mulDiv(a, new BigNumber(n), new BigNumber(d)).callAsync();
expect(r).to.bignumber.eq(MAX_FIXED_VALUE.negated());
});
});
@ -227,19 +227,19 @@ blockchainTests('LibFixedMath unit tests', env => {
it('0 + 0 == 0', async () => {
const [a, b] = [0, 0];
const r = await testContract.add.callAsync(toFixed(a), toFixed(b));
const r = await testContract.add(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, 0);
});
it('adds two positive decimals', async () => {
const [a, b] = ['9310841.31841', '491021921.318948193'];
const r = await testContract.add.callAsync(toFixed(a), toFixed(b));
const r = await testContract.add(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, add(a, b));
});
it('adds two mixed decimals', async () => {
const [a, b] = ['9310841.31841', '-491021921.318948193'];
const r = await testContract.add.callAsync(toFixed(a), toFixed(b));
const r = await testContract.add(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, add(a, b));
});
@ -250,7 +250,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.add.callAsync(a, b);
const tx = testContract.add(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -261,7 +261,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.add.callAsync(a, b);
const tx = testContract.add(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -272,7 +272,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.add.callAsync(a, b);
const tx = testContract.add(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -283,19 +283,19 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.add.callAsync(a, b);
const tx = testContract.add(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('MIN_FIXED + MAX_FIXED == int(-1)', async () => {
const [a, b] = [MIN_FIXED_VALUE, MAX_FIXED_VALUE];
const r = await testContract.add.callAsync(a, b);
const r = await testContract.add(a, b).callAsync();
expect(r).to.bignumber.eq(-1);
});
it('MAX_FIXED + (MIN_FIXED + int(1)) == 0', async () => {
const [a, b] = [MAX_FIXED_VALUE, MIN_FIXED_VALUE.plus(1)];
const r = await testContract.add.callAsync(a, b);
const r = await testContract.add(a, b).callAsync();
expect(r).to.bignumber.eq(0);
});
});
@ -307,19 +307,19 @@ blockchainTests('LibFixedMath unit tests', env => {
it('0 - 0 == 0', async () => {
const [a, b] = [0, 0];
const r = await testContract.sub.callAsync(toFixed(a), toFixed(b));
const r = await testContract.sub(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, 0);
});
it('subtracts two positive decimals', async () => {
const [a, b] = ['9310841.31841', '491021921.318948193'];
const r = await testContract.sub.callAsync(toFixed(a), toFixed(b));
const r = await testContract.sub(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, sub(a, b));
});
it('subtracts two mixed decimals', async () => {
const [a, b] = ['9310841.31841', '-491021921.318948193'];
const r = await testContract.sub.callAsync(toFixed(a), toFixed(b));
const r = await testContract.sub(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, sub(a, b));
});
@ -330,7 +330,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b.negated(),
);
const tx = testContract.sub.callAsync(a, b);
const tx = testContract.sub(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -341,7 +341,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b.negated(),
);
const tx = testContract.sub.callAsync(a, b);
const tx = testContract.sub(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -353,13 +353,13 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooSmall,
b,
);
const tx = testContract.sub.callAsync(a, b);
const tx = testContract.sub(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('MAX_FIXED - MAX_FIXED == 0', async () => {
const [a, b] = [MAX_FIXED_VALUE, MAX_FIXED_VALUE];
const r = await testContract.sub.callAsync(a, b);
const r = await testContract.sub(a, b).callAsync();
expect(r).to.bignumber.eq(0);
});
@ -370,7 +370,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b.negated(),
);
const tx = testContract.sub.callAsync(a, b);
const tx = testContract.sub(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -380,7 +380,7 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooSmall,
b,
);
const tx = testContract.sub.callAsync(a, b);
const tx = testContract.sub(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -396,31 +396,31 @@ blockchainTests('LibFixedMath unit tests', env => {
it('x * 0 == 0', async () => {
const [a, b] = [1337, 0];
const r = await testContract.mul.callAsync(toFixed(a), toFixed(b));
const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, b);
});
it('x * 1 == x', async () => {
const [a, b] = [0.5, 1];
const r = await testContract.mul.callAsync(toFixed(a), toFixed(b));
const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, a);
});
it('x * -1 == -x', async () => {
const [a, b] = [0.5, -1];
const r = await testContract.mul.callAsync(toFixed(a), toFixed(b));
const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, -a);
});
it('multiplies two positive decimals', async () => {
const [a, b] = ['1.25394912112', '0.03413318948193'];
const r = await testContract.mul.callAsync(toFixed(a), toFixed(b));
const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, mul(a, b));
});
it('multiplies two mixed decimals', async () => {
const [a, b] = ['1.25394912112', '-0.03413318948193'];
const r = await testContract.mul.callAsync(toFixed(a), toFixed(b));
const r = await testContract.mul(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, mul(a, b));
});
@ -431,7 +431,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, b);
const tx = testContract.mul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -442,13 +442,13 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, b);
const tx = testContract.mul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('MAX_FIXED * int(1) == MAX_FIXED / FIXED_1', async () => {
const [a, b] = [MAX_FIXED_VALUE, 1];
const r = await testContract.mul.callAsync(a, new BigNumber(b));
const r = await testContract.mul(a, new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(MAX_FIXED_VALUE.dividedToIntegerBy(FIXED_1));
});
@ -459,7 +459,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, new BigNumber(b));
const tx = testContract.mul(a, new BigNumber(b)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -470,7 +470,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, b);
const tx = testContract.mul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -481,7 +481,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, b);
const tx = testContract.mul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -492,7 +492,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, b);
const tx = testContract.mul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -503,7 +503,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(a, new BigNumber(b));
const tx = testContract.mul(a, new BigNumber(b)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -514,13 +514,13 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.mul.callAsync(new BigNumber(a), b);
const tx = testContract.mul(new BigNumber(a), b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('MAX_FIXED * int(-1) == -MAX_FIXED / FIXED_1', async () => {
const [a, b] = [MAX_FIXED_VALUE, -1];
const r = await testContract.mul.callAsync(a, new BigNumber(b));
const r = await testContract.mul(a, new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(MAX_FIXED_VALUE.negated().dividedToIntegerBy(FIXED_1));
});
});
@ -541,31 +541,31 @@ blockchainTests('LibFixedMath unit tests', env => {
toFixed(a).times(FIXED_POINT_DIVISOR),
toFixed(b),
);
const tx = testContract.div.callAsync(toFixed(a), toFixed(b));
const tx = testContract.div(toFixed(a), toFixed(b)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('x / 1 == x', async () => {
const [a, b] = [1.41214552, 1];
const r = await testContract.div.callAsync(toFixed(a), toFixed(b));
const r = await testContract.div(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, a);
});
it('x / -1 == -x', async () => {
const [a, b] = [1.109312, -1];
const r = await testContract.div.callAsync(toFixed(a), toFixed(b));
const r = await testContract.div(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, -a);
});
it('divides two positive decimals', async () => {
const [a, b] = ['1.25394912112', '0.03413318948193'];
const r = await testContract.div.callAsync(toFixed(a), toFixed(b));
const r = await testContract.div(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, div(a, b));
});
it('divides two mixed decimals', async () => {
const [a, b] = ['1.25394912112', '-0.03413318948193'];
const r = await testContract.div.callAsync(toFixed(a), toFixed(b));
const r = await testContract.div(toFixed(a), toFixed(b)).callAsync();
assertFixedEquals(r, div(a, b));
});
@ -576,7 +576,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
FIXED_1,
);
const tx = testContract.div.callAsync(a, new BigNumber(b));
const tx = testContract.div(a, new BigNumber(b)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -587,13 +587,13 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
FIXED_1,
);
const tx = testContract.div.callAsync(a, new BigNumber(b));
const tx = testContract.div(a, new BigNumber(b)).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('int(-1) / MIN_FIXED == 0', async () => {
const [a, b] = [-1, MIN_FIXED_VALUE];
const r = await testContract.div.callAsync(new BigNumber(a), b);
const r = await testContract.div(new BigNumber(a), b).callAsync();
expect(r).to.bignumber.eq(0);
});
});
@ -601,31 +601,31 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('uintMul()', () => {
it('0 * x == 0', async () => {
const [a, b] = [0, 1234];
const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b));
const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(0);
});
it('1 * x == int(x)', async () => {
const [a, b] = [1, 1234];
const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b));
const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(Math.trunc(b));
});
it('-1 * x == 0', async () => {
const [a, b] = [-1, 1234];
const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b));
const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(0);
});
it('0.5 * x == x/2', async () => {
const [a, b] = [0.5, 1234];
const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b));
const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(b / 2);
});
it('0.5 * x == 0 if x = 1', async () => {
const [a, b] = [0.5, 1];
const r = await testContract.uintMul.callAsync(toFixed(a), new BigNumber(b));
const r = await testContract.uintMul(toFixed(a), new BigNumber(b)).callAsync();
expect(r).to.bignumber.eq(0);
});
@ -635,7 +635,7 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooLarge,
b,
);
const tx = testContract.uintMul.callAsync(a, b);
const tx = testContract.uintMul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -646,7 +646,7 @@ blockchainTests('LibFixedMath unit tests', env => {
a,
b,
);
const tx = testContract.uintMul.callAsync(a, b);
const tx = testContract.uintMul(a, b).callAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -654,31 +654,31 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('toInteger()', () => {
it('toInteger(n) == int(n)', async () => {
const n = 1337.5912;
const r = await testContract.toInteger.callAsync(toFixed(n));
const r = await testContract.toInteger(toFixed(n)).callAsync();
expect(r).to.bignumber.eq(Math.trunc(n));
});
it('toInteger(-n) == -int(n)', async () => {
const n = -1337.5912;
const r = await testContract.toInteger.callAsync(toFixed(n));
const r = await testContract.toInteger(toFixed(n)).callAsync();
expect(r).to.bignumber.eq(Math.trunc(n));
});
it('toInteger(n) == 0, when 0 < n < 1', async () => {
const n = 0.9995;
const r = await testContract.toInteger.callAsync(toFixed(n));
const r = await testContract.toInteger(toFixed(n)).callAsync();
expect(r).to.bignumber.eq(0);
});
it('toInteger(-n) == 0, when -1 < n < 0', async () => {
const n = -0.9995;
const r = await testContract.toInteger.callAsync(toFixed(n));
const r = await testContract.toInteger(toFixed(n)).callAsync();
expect(r).to.bignumber.eq(0);
});
it('toInteger(0) == 0', async () => {
const n = 0;
const r = await testContract.toInteger.callAsync(toFixed(n));
const r = await testContract.toInteger(toFixed(n)).callAsync();
expect(r).to.bignumber.eq(0);
});
});
@ -687,37 +687,37 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('signed', () => {
it('converts a positive integer', async () => {
const n = 1337;
const r = await testContract.toFixedSigned1.callAsync(new BigNumber(n));
const r = await testContract.toFixedSigned1(new BigNumber(n)).callAsync();
assertFixedEquals(r, n);
});
it('converts a negative integer', async () => {
const n = -1337;
const r = await testContract.toFixedSigned1.callAsync(new BigNumber(n));
const r = await testContract.toFixedSigned1(new BigNumber(n)).callAsync();
assertFixedEquals(r, n);
});
it('converts a fraction with a positive numerator and denominator', async () => {
const [n, d] = [1337, 1000];
const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d));
const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, n / d);
});
it('converts a fraction with a negative numerator and positive denominator', async () => {
const [n, d] = [-1337, 1000];
const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d));
const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, n / d);
});
it('converts a fraction with a negative numerator and denominator', async () => {
const [n, d] = [-1337, -1000];
const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d));
const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, n / d);
});
it('converts a fraction with a negative numerator and negative denominator', async () => {
const [n, d] = [-1337, -1000];
const r = await testContract.toFixedSigned2.callAsync(new BigNumber(n), new BigNumber(d));
const r = await testContract.toFixedSigned2(new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, n / d);
});
@ -728,7 +728,7 @@ blockchainTests('LibFixedMath unit tests', env => {
n,
FIXED_POINT_DIVISOR,
);
const tx = testContract.toFixedSigned2.callAsync(n, d);
const tx = testContract.toFixedSigned2(n, d).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -739,7 +739,7 @@ blockchainTests('LibFixedMath unit tests', env => {
n.times(FIXED_POINT_DIVISOR),
d,
);
const tx = testContract.toFixedSigned2.callAsync(n, d);
const tx = testContract.toFixedSigned2(n, d).callAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -747,13 +747,13 @@ blockchainTests('LibFixedMath unit tests', env => {
describe('unsigned', () => {
it('converts an integer', async () => {
const n = 1337;
const r = await testContract.toFixedUnsigned1.callAsync(new BigNumber(n));
const r = await testContract.toFixedUnsigned1(new BigNumber(n)).callAsync();
assertFixedEquals(r, n);
});
it('converts a fraction', async () => {
const [n, d] = [1337, 1000];
const r = await testContract.toFixedUnsigned2.callAsync(new BigNumber(n), new BigNumber(d));
const r = await testContract.toFixedUnsigned2(new BigNumber(n), new BigNumber(d)).callAsync();
assertFixedEquals(r, n / d);
});
@ -763,7 +763,7 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooLarge,
n,
);
const tx = testContract.toFixedUnsigned2.callAsync(n, d);
const tx = testContract.toFixedUnsigned2(n, d).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -773,7 +773,7 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooLarge,
d,
);
const tx = testContract.toFixedUnsigned2.callAsync(n, d);
const tx = testContract.toFixedUnsigned2(n, d).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -784,7 +784,7 @@ blockchainTests('LibFixedMath unit tests', env => {
n,
FIXED_POINT_DIVISOR,
);
const tx = testContract.toFixedUnsigned2.callAsync(n, d);
const tx = testContract.toFixedUnsigned2(n, d).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -795,7 +795,7 @@ blockchainTests('LibFixedMath unit tests', env => {
n.times(FIXED_POINT_DIVISOR),
d,
);
const tx = testContract.toFixedUnsigned2.callAsync(n, d);
const tx = testContract.toFixedUnsigned2(n, d).callAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@ -824,7 +824,7 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooSmall,
x,
);
const tx = testContract.ln.callAsync(x);
const tx = testContract.ln(x).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -834,7 +834,7 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooLarge,
x,
);
const tx = testContract.ln.callAsync(x);
const tx = testContract.ln(x).callAsync();
return expect(tx).to.revertWith(expectedError);
});
@ -844,37 +844,37 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooSmall,
x,
);
const tx = testContract.ln.callAsync(x);
const tx = testContract.ln(x).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('ln(x = 1) == 0', async () => {
const x = toFixed(1);
const r = await testContract.ln.callAsync(x);
const r = await testContract.ln(x).callAsync();
assertFixedEquals(r, 0);
});
it('ln(x < LN_MIN_VAL) == EXP_MIN_VAL', async () => {
const x = toFixed(MIN_LN_NUMBER).minus(1);
const r = await testContract.ln.callAsync(x);
const r = await testContract.ln(x).callAsync();
assertFixedEquals(r, MIN_EXP_NUMBER);
});
it('ln(x), where x is close to 0', async () => {
const x = new BigNumber('1e-27');
const r = await testContract.ln.callAsync(toFixed(x));
const r = await testContract.ln(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, ln(x), 12);
});
it('ln(x), where x is close to 1', async () => {
const x = new BigNumber(1).minus('1e-27');
const r = await testContract.ln.callAsync(toFixed(x));
const r = await testContract.ln(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, ln(x), LN_PRECISION);
});
it('ln(x = 0.85)', async () => {
const x = 0.85;
const r = await testContract.ln.callAsync(toFixed(x));
const r = await testContract.ln(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, ln(x), LN_PRECISION);
});
@ -882,7 +882,7 @@ blockchainTests('LibFixedMath unit tests', env => {
const inputs = _.times(FUZZ_COUNT, () => getRandomDecimal(0, 1));
for (const x of inputs) {
it(`ln(${x.toString(10)})`, async () => {
const r = await testContract.ln.callAsync(toFixed(x));
const r = await testContract.ln(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, ln(x), LN_PRECISION);
});
}
@ -902,7 +902,7 @@ blockchainTests('LibFixedMath unit tests', env => {
it('exp(x = 0) == 1', async () => {
const x = toFixed(0);
const r = await testContract.exp.callAsync(x);
const r = await testContract.exp(x).callAsync();
assertFixedEquals(r, 1);
});
@ -912,31 +912,31 @@ blockchainTests('LibFixedMath unit tests', env => {
FixedMathRevertErrors.ValueErrorCodes.TooLarge,
x,
);
const tx = testContract.exp.callAsync(x);
const tx = testContract.exp(x).callAsync();
return expect(tx).to.revertWith(expectedError);
});
it('exp(x < EXP_MIN_VAL) == 0', async () => {
const x = toFixed(MIN_EXP_NUMBER).minus(1);
const r = await testContract.exp.callAsync(x);
const r = await testContract.exp(x).callAsync();
assertFixedEquals(r, 0);
});
it('exp(x < 0), where x is close to 0', async () => {
const x = new BigNumber('-1e-18');
const r = await testContract.exp.callAsync(toFixed(x));
const r = await testContract.exp(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION);
});
it('exp(x), where x is close to EXP_MIN_VAL', async () => {
const x = MIN_EXP_NUMBER.plus('1e-18');
const r = await testContract.exp.callAsync(toFixed(x));
const r = await testContract.exp(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION);
});
it('exp(x = -0.85)', async () => {
const x = -0.85;
const r = await testContract.exp.callAsync(toFixed(x));
const r = await testContract.exp(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION);
});
@ -944,7 +944,7 @@ blockchainTests('LibFixedMath unit tests', env => {
const inputs = _.times(FUZZ_COUNT, () => getRandomDecimal(MIN_EXP_NUMBER, MAX_EXP_NUMBER));
for (const x of inputs) {
it(`exp(${x.toString(10)})`, async () => {
const r = await testContract.exp.callAsync(toFixed(x));
const r = await testContract.exp(toFixed(x)).callAsync();
assertFixedRoughlyEquals(r, exp(x), EXP_PRECISION);
});
}

View File

@ -22,7 +22,7 @@ blockchainTests('LibSafeDowncast unit tests', env => {
describe('downcastToUint96', () => {
async function verifyCorrectDowncastAsync(n: Numberish): Promise<void> {
const actual = await testContract.downcastToUint96.callAsync(new BigNumber(n));
const actual = await testContract.downcastToUint96(new BigNumber(n)).callAsync();
expect(actual).to.bignumber.eq(n);
}
function toDowncastError(n: Numberish): SafeMathRevertErrors.Uint256DowncastError {
@ -53,7 +53,7 @@ blockchainTests('LibSafeDowncast unit tests', env => {
describe('downcastToUint64', () => {
async function verifyCorrectDowncastAsync(n: Numberish): Promise<void> {
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 {

View File

@ -41,89 +41,79 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
// Create a test pool
const operatorShare = new BigNumber(1);
const addOperatorAsMaker = true;
const txReceipt = await testContract.createStakingPool.awaitTransactionSuccessAsync(
operatorShare,
addOperatorAsMaker,
);
const txReceipt = await testContract
.createStakingPool(operatorShare, addOperatorAsMaker)
.awaitTransactionSuccessAsync();
const createStakingPoolLog = txReceipt.logs[0];
testPoolId = (createStakingPoolLog as any).args.poolId;
});
describe('_isCumulativeRewardSet', () => {
it('Should return true iff denominator is non-zero', async () => {
const isSet = await testContract.isCumulativeRewardSet.callAsync({
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({
const isSet = await testContract
.isCumulativeRewardSet({
numerator: new BigNumber(1),
denominator: ZERO,
});
})
.callAsync();
expect(isSet).to.be.false();
});
});
describe('_addCumulativeReward', () => {
it('Should set value to `reward/stake` if this is the first cumulative reward', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]);
});
it('Should do nothing if a cumulative reward has already been recorded in the current epoch (`lastStoredEpoch == currentEpoch_`)', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
// this call should not overwrite existing value (testRewards[0])
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[1].numerator,
testRewards[1].denominator,
);
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[1].numerator, testRewards[1].denominator)
.awaitTransactionSuccessAsync();
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]);
});
it('Should set value to normalized sum of `reward/stake` plus most recent cumulative reward, given one exists', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
await testContract.incrementEpoch.awaitTransactionSuccessAsync();
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[1].numerator,
testRewards[1].denominator,
);
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
await testContract.incrementEpoch().awaitTransactionSuccessAsync();
await testContract
.addCumulativeReward(testPoolId, testRewards[1].numerator, testRewards[1].denominator)
.awaitTransactionSuccessAsync();
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(sumOfTestRewardsNormalized);
});
});
describe('_updateCumulativeReward', () => {
it('Should set current cumulative reward to most recent cumulative reward', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
await testContract.incrementEpoch.awaitTransactionSuccessAsync();
await testContract.updateCumulativeReward.awaitTransactionSuccessAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
await testContract.incrementEpoch().awaitTransactionSuccessAsync();
await testContract.updateCumulativeReward(testPoolId).awaitTransactionSuccessAsync();
const epoch = new BigNumber(2);
const mostRecentCumulativeReward = await testContract.getCumulativeRewardAtEpochRaw.callAsync(
testPoolId,
epoch,
);
const mostRecentCumulativeReward = await testContract
.getCumulativeRewardAtEpochRaw(testPoolId, epoch)
.callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]);
});
});
@ -137,22 +127,15 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
epochOfIntervalEnd: BigNumber,
): Promise<void> => {
// Simulate earning reward
await testContract.storeCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0],
epochOfFirstReward,
);
await testContract.storeCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
sumOfTestRewardsNormalized,
epochOfSecondReward,
);
const reward = await testContract.computeMemberRewardOverInterval.callAsync(
testPoolId,
amountToStake,
epochOfIntervalStart,
epochOfIntervalEnd,
);
await testContract
.storeCumulativeReward(testPoolId, testRewards[0], epochOfFirstReward)
.awaitTransactionSuccessAsync();
await testContract
.storeCumulativeReward(testPoolId, sumOfTestRewardsNormalized, epochOfSecondReward)
.awaitTransactionSuccessAsync();
const reward = await testContract
.computeMemberRewardOverInterval(testPoolId, amountToStake, epochOfIntervalStart, epochOfIntervalEnd)
.callAsync();
// Compute expected reward
const lhs = sumOfTestRewardsNormalized.numerator.dividedBy(sumOfTestRewardsNormalized.denominator);
const rhs = testRewards[0].numerator.dividedBy(testRewards[0].denominator);
@ -213,12 +196,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
const stake = toBaseUnitAmount(1);
const beginEpoch = new BigNumber(1);
const endEpoch = new BigNumber(2);
const reward = await testContract.computeMemberRewardOverInterval.callAsync(
testPoolId,
stake,
beginEpoch,
endEpoch,
);
const reward = await testContract
.computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch)
.callAsync();
expect(reward).to.bignumber.equal(ZERO);
});
@ -226,12 +206,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
const stake = toBaseUnitAmount(0);
const beginEpoch = new BigNumber(1);
const endEpoch = new BigNumber(2);
const reward = await testContract.computeMemberRewardOverInterval.callAsync(
testPoolId,
stake,
beginEpoch,
endEpoch,
);
const reward = await testContract
.computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch)
.callAsync();
expect(reward).to.bignumber.equal(ZERO);
});
@ -239,12 +216,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
const stake = toBaseUnitAmount(1);
const beginEpoch = new BigNumber(1);
const endEpoch = new BigNumber(1);
const reward = await testContract.computeMemberRewardOverInterval.callAsync(
testPoolId,
stake,
beginEpoch,
endEpoch,
);
const reward = await testContract
.computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch)
.callAsync();
expect(reward).to.bignumber.equal(ZERO);
});
@ -252,7 +226,9 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
const stake = toBaseUnitAmount(1);
const beginEpoch = new BigNumber(2);
const endEpoch = new BigNumber(1);
const tx = testContract.computeMemberRewardOverInterval.callAsync(testPoolId, stake, beginEpoch, endEpoch);
const tx = testContract
.computeMemberRewardOverInterval(testPoolId, stake, beginEpoch, endEpoch)
.callAsync();
return expect(tx).to.revertWith('CR_INTERVAL_INVALID');
});
});

View File

@ -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());
});
});

View File

@ -25,7 +25,7 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
env.txDefaults,
artifacts,
);
await testContract.setCurrentEpoch.awaitTransactionSuccessAsync(CURRENT_EPOCH);
await testContract.setCurrentEpoch(CURRENT_EPOCH).awaitTransactionSuccessAsync();
defaultUninitializedBalance = {
currentEpoch: constants.INITIAL_EPOCH,
currentEpochBalance: new BigNumber(0),
@ -49,7 +49,7 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
storedBalance.currentEpoch,
storedBalance.currentEpochBalance,
storedBalance.nextEpochBalance,
] = await testContract.testBalances.callAsync(new BigNumber(index));
] = await testContract.testBalances(new BigNumber(index)).callAsync();
return storedBalance as StoredBalance;
}
@ -59,9 +59,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
toBalance: StoredBalance,
amount: BigNumber,
): Promise<void> {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(fromBalance, INDEX_ZERO);
await testContract.setStoredBalance.awaitTransactionSuccessAsync(toBalance, INDEX_ONE);
await testContract.moveStake.awaitTransactionSuccessAsync(INDEX_ZERO, INDEX_ONE, amount);
await testContract.setStoredBalance(fromBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
await testContract.setStoredBalance(toBalance, INDEX_ONE).awaitTransactionSuccessAsync();
await testContract.moveStake(INDEX_ZERO, INDEX_ONE, amount).awaitTransactionSuccessAsync();
const actualBalances = await Promise.all([
getTestBalancesAsync(INDEX_ZERO),
@ -101,20 +101,18 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
);
});
it('Noop if pointers are equal', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
// If the pointers weren't equal, this would revert with InsufficientBalanceError
await testContract.moveStake.awaitTransactionSuccessAsync(
INDEX_ZERO,
INDEX_ZERO,
defaultSyncedBalance.nextEpochBalance.plus(1),
);
await testContract
.moveStake(INDEX_ZERO, INDEX_ZERO, defaultSyncedBalance.nextEpochBalance.plus(1))
.awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal(defaultSyncedBalance);
});
it("Reverts if attempting to move more than next epoch's balance", async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultSyncedBalance.nextEpochBalance.plus(1);
const tx = testContract.moveStake.awaitTransactionSuccessAsync(INDEX_ZERO, INDEX_ONE, amount);
const tx = testContract.moveStake(INDEX_ZERO, INDEX_ONE, amount).awaitTransactionSuccessAsync();
await expect(tx).to.revertWith(
new StakingRevertErrors.InsufficientBalanceError(amount, defaultSyncedBalance.nextEpochBalance),
);
@ -123,32 +121,32 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
describe('Load balance', () => {
it('Balance does not change state if balance was previously synced in the current epoch', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO);
const actualBalance = await testContract.loadCurrentBalance.callAsync(INDEX_ZERO);
await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const actualBalance = await testContract.loadCurrentBalance(INDEX_ZERO).callAsync();
expect(actualBalance).to.deep.equal(defaultSyncedBalance);
});
it('Balance updates current epoch fields if the balance has not yet been synced in the current epoch', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO);
const actualBalance = await testContract.loadCurrentBalance.callAsync(INDEX_ZERO);
await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const actualBalance = await testContract.loadCurrentBalance(INDEX_ZERO).callAsync();
expect(actualBalance).to.deep.equal(defaultSyncedBalance);
});
it('Balance loads unsynced balance from storage without changing fields', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO);
const actualBalance = await testContract.loadStaleBalance.callAsync(INDEX_ZERO);
await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const actualBalance = await testContract.loadStaleBalance(INDEX_ZERO).callAsync();
expect(actualBalance).to.deep.equal(defaultUnsyncedBalance);
});
it('Balance loads synced balance from storage without changing fields', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultSyncedBalance, INDEX_ZERO);
const actualBalance = await testContract.loadStaleBalance.callAsync(INDEX_ZERO);
await testContract.setStoredBalance(defaultSyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const actualBalance = await testContract.loadStaleBalance(INDEX_ZERO).callAsync();
expect(actualBalance).to.deep.equal(defaultSyncedBalance);
});
});
describe('Increase/decrease balance', () => {
it('_increaseCurrentAndNextBalance', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2);
await testContract.increaseCurrentAndNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount);
await testContract.increaseCurrentAndNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal({
...defaultSyncedBalance,
@ -157,16 +155,16 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
});
});
it('_increaseCurrentAndNextBalance (previously uninitialized)', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUninitializedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultUninitializedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultSyncedBalance.currentEpochBalance;
await testContract.increaseCurrentAndNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount);
await testContract.increaseCurrentAndNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal(defaultSyncedBalance);
});
it('_decreaseCurrentAndNextBalance', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2);
await testContract.decreaseCurrentAndNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount);
await testContract.decreaseCurrentAndNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal({
...defaultSyncedBalance,
@ -175,9 +173,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
});
});
it('_increaseNextBalance', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2);
await testContract.increaseNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount);
await testContract.increaseNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal({
...defaultSyncedBalance,
@ -185,9 +183,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
});
});
it('_increaseCurrentAndNextBalance (previously uninitialized)', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUninitializedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultUninitializedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultSyncedBalance.currentEpochBalance;
await testContract.increaseNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount);
await testContract.increaseNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal({
...defaultSyncedBalance,
@ -195,9 +193,9 @@ blockchainTests.resets('MixinStakeStorage unit tests', env => {
});
});
it('_decreaseNextBalance', async () => {
await testContract.setStoredBalance.awaitTransactionSuccessAsync(defaultUnsyncedBalance, INDEX_ZERO);
await testContract.setStoredBalance(defaultUnsyncedBalance, INDEX_ZERO).awaitTransactionSuccessAsync();
const amount = defaultUnsyncedBalance.currentEpochBalance.dividedToIntegerBy(2);
await testContract.decreaseNextBalance.awaitTransactionSuccessAsync(INDEX_ZERO, amount);
await testContract.decreaseNextBalance(INDEX_ZERO, amount).awaitTransactionSuccessAsync();
const actualBalance = await getTestBalancesAsync(INDEX_ZERO);
expect(actualBalance).to.deep.equal({
...defaultSyncedBalance,

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