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
198 changed files with 30021 additions and 38850 deletions

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({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: fiveDays.minus(1),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: fiveDays.minus(1),
})
.awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration,
);
return expect(tx).to.revertWith(expectedError);
});
it('reverts if epoch duration is > 30 days', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: thirtyDays.plus(1),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: thirtyDays.plus(1),
})
.awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration,
);
return expect(tx).to.revertWith(expectedError);
});
it('succeeds if epoch duration is 5 days', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: fiveDays,
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: fiveDays,
})
.awaitTransactionSuccessAsync();
return expect(tx).to.be.fulfilled('');
});
it('succeeds if epoch duration is 30 days', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: thirtyDays,
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
epochDurationInSeconds: thirtyDays,
})
.awaitTransactionSuccessAsync();
return expect(tx).to.be.fulfilled('');
});
it('reverts if alpha denominator is 0', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaDenominator: constants.ZERO_AMOUNT,
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaDenominator: constants.ZERO_AMOUNT,
})
.awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha,
);
return expect(tx).to.revertWith(expectedError);
});
it('reverts if alpha > 1', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaNumerator: new BigNumber(101),
cobbDouglasAlphaDenominator: new BigNumber(100),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaNumerator: new BigNumber(101),
cobbDouglasAlphaDenominator: new BigNumber(100),
})
.awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha,
);
return expect(tx).to.revertWith(expectedError);
});
it('succeeds if alpha == 1', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaNumerator: new BigNumber(1),
cobbDouglasAlphaDenominator: new BigNumber(1),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaNumerator: new BigNumber(1),
cobbDouglasAlphaDenominator: new BigNumber(1),
})
.awaitTransactionSuccessAsync();
return expect(tx).to.be.fulfilled('');
});
it('succeeds if alpha == 0', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaNumerator: constants.ZERO_AMOUNT,
cobbDouglasAlphaDenominator: new BigNumber(1),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
cobbDouglasAlphaNumerator: constants.ZERO_AMOUNT,
cobbDouglasAlphaDenominator: new BigNumber(1),
})
.awaitTransactionSuccessAsync();
return expect(tx).to.be.fulfilled('');
});
it('reverts if delegation weight is > 100%', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM).plus(1),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM).plus(1),
})
.awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight,
);
return expect(tx).to.revertWith(expectedError);
});
it('succeeds if delegation weight is 100%', async () => {
const tx = proxyContract.setAndAssertParams.awaitTransactionSuccessAsync({
...stakingConstants.DEFAULT_PARAMS,
rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM),
});
const tx = proxyContract
.setAndAssertParams({
...stakingConstants.DEFAULT_PARAMS,
rewardDelegatedStakeWeight: new BigNumber(stakingConstants.PPM),
})
.awaitTransactionSuccessAsync();
return expect(tx).to.be.fulfilled('');
});
});

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(
_opts.poolId,
_opts.operator,
new BigNumber(_opts.operatorReward),
new BigNumber(_opts.membersReward),
new BigNumber(_opts.membersStake),
);
await testContract
.syncPoolRewards(
_opts.poolId,
_opts.operator,
new BigNumber(_opts.operatorReward),
new BigNumber(_opts.membersReward),
new BigNumber(_opts.membersStake),
)
.awaitTransactionSuccessAsync();
// Because the operator share is implicitly defined by the member and
// operator reward, and is stored as a uint32, there will be precision
// loss when the reward is combined then split again in the contracts.
@@ -86,13 +88,15 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
};
// Generate a deterministic operator address based on the poolId.
_opts.operator = poolIdToOperator(_opts.poolId);
await testContract.setUnfinalizedPoolReward.awaitTransactionSuccessAsync(
_opts.poolId,
_opts.operator,
new BigNumber(_opts.operatorReward),
new BigNumber(_opts.membersReward),
new BigNumber(_opts.membersStake),
);
await testContract
.setUnfinalizedPoolReward(
_opts.poolId,
_opts.operator,
new BigNumber(_opts.operatorReward),
new BigNumber(_opts.membersReward),
new BigNumber(_opts.membersStake),
)
.awaitTransactionSuccessAsync();
// Because the operator share is implicitly defined by the member and
// operator reward, and is stored as a uint32, there will be precision
// loss when the reward is combined then split again in the contracts.
@@ -148,8 +152,10 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
stake: getRandomInteger(1, toBaseUnitAmount(10)),
...opts,
};
const fn = now ? testContract.delegateStakeNow : testContract.delegateStake;
const receipt = await fn.awaitTransactionSuccessAsync(_opts.delegator, poolId, new BigNumber(_opts.stake));
const fn = now
? testContract.delegateStakeNow.bind(testContract)
: testContract.delegateStake.bind(testContract);
const receipt = await fn(_opts.delegator, poolId, new BigNumber(_opts.stake)).awaitTransactionSuccessAsync();
const delegatorTransfers = getTransfersFromLogs(receipt.logs, _opts.delegator);
return {
..._opts,
@@ -164,9 +170,9 @@ blockchainTests.resets('Delegator rewards unit tests', env => {
): Promise<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(
_opts.poolId,
new BigNumber(_opts.operatorShare * constants.PPM_DENOMINATOR).integerValue(),
new BigNumber(_opts.feesCollected),
new BigNumber(_opts.membersStake),
new BigNumber(_opts.weightedStake),
);
await testContract
.addActivePool(
_opts.poolId,
new BigNumber(_opts.operatorShare * constants.PPM_DENOMINATOR).integerValue(),
new BigNumber(_opts.feesCollected),
new BigNumber(_opts.membersStake),
new BigNumber(_opts.weightedStake),
)
.awaitTransactionSuccessAsync();
return _opts;
}
@@ -95,13 +97,13 @@ blockchainTests.resets('Finalizer unit tests', env => {
}
async function getUnfinalizedStateAsync(): Promise<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(
new BigNumber(rewardsAvailable),
new BigNumber(feesCollected),
new BigNumber(totalFees),
new BigNumber(pool.weightedStake),
new BigNumber(totalStake),
);
poolRewards[i] = await testContract
.cobbDouglas(
new BigNumber(rewardsAvailable),
new BigNumber(feesCollected),
new BigNumber(totalFees),
new BigNumber(pool.weightedStake),
new BigNumber(totalStake),
)
.callAsync();
}
return poolRewards;
}
@@ -257,7 +261,7 @@ blockchainTests.resets('Finalizer unit tests', env => {
}
async function getCurrentEpochAsync(): Promise<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,18 +56,19 @@ blockchainTests('LibCobbDouglas unit tests', env => {
...DEFAULT_COBB_DOUGLAS_PARAMS,
...params,
};
return testContract.cobbDouglas.callAsync(
new BigNumber(_params.totalRewards),
new BigNumber(_params.ownerFees),
new BigNumber(_params.totalFees),
new BigNumber(_params.ownerStake),
new BigNumber(_params.totalStake),
new BigNumber(_params.alphaNumerator),
new BigNumber(_params.alphaDenominator),
{
return testContract
.cobbDouglas(
new BigNumber(_params.totalRewards),
new BigNumber(_params.ownerFees),
new BigNumber(_params.totalFees),
new BigNumber(_params.ownerStake),
new BigNumber(_params.totalStake),
new BigNumber(_params.alphaNumerator),
new BigNumber(_params.alphaDenominator),
)
.callAsync({
gas: TX_GAS_FEE + (_params.gas === undefined ? MAX_COBB_DOUGLAS_GAS : _params.gas),
},
);
});
}
function cobbDouglas(params?: Partial<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({
numerator: ZERO,
denominator: new BigNumber(1),
});
const isSet = await testContract
.isCumulativeRewardSet({
numerator: ZERO,
denominator: new BigNumber(1),
})
.callAsync();
expect(isSet).to.be.true();
});
it('Should return false iff denominator is zero', async () => {
const isSet = await testContract.isCumulativeRewardSet.callAsync({
numerator: new BigNumber(1),
denominator: ZERO,
});
const isSet = await testContract
.isCumulativeRewardSet({
numerator: new BigNumber(1),
denominator: ZERO,
})
.callAsync();
expect(isSet).to.be.false();
});
});
describe('_addCumulativeReward', () => {
it('Should set value to `reward/stake` if this is the first cumulative reward', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]);
});
it('Should do nothing if a cumulative reward has already been recorded in the current epoch (`lastStoredEpoch == currentEpoch_`)', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
// this call should not overwrite existing value (testRewards[0])
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[1].numerator,
testRewards[1].denominator,
);
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[1].numerator, testRewards[1].denominator)
.awaitTransactionSuccessAsync();
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]);
});
it('Should set value to normalized sum of `reward/stake` plus most recent cumulative reward, given one exists', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
await testContract.incrementEpoch.awaitTransactionSuccessAsync();
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[1].numerator,
testRewards[1].denominator,
);
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward.callAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
await testContract.incrementEpoch().awaitTransactionSuccessAsync();
await testContract
.addCumulativeReward(testPoolId, testRewards[1].numerator, testRewards[1].denominator)
.awaitTransactionSuccessAsync();
const mostRecentCumulativeReward = await testContract.getMostRecentCumulativeReward(testPoolId).callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(sumOfTestRewardsNormalized);
});
});
describe('_updateCumulativeReward', () => {
it('Should set current cumulative reward to most recent cumulative reward', async () => {
await testContract.addCumulativeReward.awaitTransactionSuccessAsync(
testPoolId,
testRewards[0].numerator,
testRewards[0].denominator,
);
await testContract.incrementEpoch.awaitTransactionSuccessAsync();
await testContract.updateCumulativeReward.awaitTransactionSuccessAsync(testPoolId);
await testContract
.addCumulativeReward(testPoolId, testRewards[0].numerator, testRewards[0].denominator)
.awaitTransactionSuccessAsync();
await testContract.incrementEpoch().awaitTransactionSuccessAsync();
await testContract.updateCumulativeReward(testPoolId).awaitTransactionSuccessAsync();
const epoch = new BigNumber(2);
const mostRecentCumulativeReward = await testContract.getCumulativeRewardAtEpochRaw.callAsync(
testPoolId,
epoch,
);
const mostRecentCumulativeReward = await testContract
.getCumulativeRewardAtEpochRaw(testPoolId, epoch)
.callAsync();
expect(mostRecentCumulativeReward).to.deep.equal(testRewards[0]);
});
});
@@ -137,22 +127,15 @@ blockchainTests.resets('MixinCumulativeRewards unit tests', env => {
epochOfIntervalEnd: BigNumber,
): Promise<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,

View File

@@ -8,7 +8,6 @@ import {
hexRandom,
Numberish,
randomAddress,
TransactionHelper,
verifyEventsFromLogs,
} from '@0x/contracts-test-utils';
import { BigNumber } from '@0x/utils';
@@ -21,7 +20,6 @@ import { TestMixinStakingPoolRewardsContract, TestMixinStakingPoolRewardsEvents
blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
let testContract: TestMixinStakingPoolRewardsContract;
let txHelper: TransactionHelper;
const POOL_ID = hexRandom();
const OPERATOR = randomAddress();
@@ -35,12 +33,13 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
env.txDefaults,
artifacts,
);
await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, {
operator: OPERATOR,
operatorShare: OPERATOR_SHARE,
});
await testContract
.setPool(POOL_ID, {
operator: OPERATOR,
operatorShare: OPERATOR_SHARE,
})
.awaitTransactionSuccessAsync();
[caller] = await env.getAccountAddressesAsync();
txHelper = new TransactionHelper(env.web3Wrapper, artifacts);
});
async function setUnfinalizedPoolRewardsAsync(
@@ -48,11 +47,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
reward: Numberish,
membersStake: Numberish,
): Promise<void> {
await testContract.setUnfinalizedPoolRewards.awaitTransactionSuccessAsync(
poolId,
new BigNumber(reward),
new BigNumber(membersStake),
);
await testContract
.setUnfinalizedPoolRewards(poolId, new BigNumber(reward), new BigNumber(membersStake))
.awaitTransactionSuccessAsync();
}
// Set the delegated stake of a delegator in a pool.
@@ -68,11 +65,13 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
nextEpochBalance: getRandomInteger(1, 1e18),
...stake,
};
await testContract.setDelegatedStakeToPoolByOwner.awaitTransactionSuccessAsync(delegator, poolId, {
currentEpoch: _stake.currentEpoch,
currentEpochBalance: _stake.currentEpochBalance,
nextEpochBalance: _stake.nextEpochBalance,
});
await testContract
.setDelegatedStakeToPoolByOwner(delegator, poolId, {
currentEpoch: _stake.currentEpoch,
currentEpochBalance: _stake.currentEpochBalance,
nextEpochBalance: _stake.nextEpochBalance,
})
.awaitTransactionSuccessAsync();
return _stake;
}
@@ -83,25 +82,29 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
delegator: string,
finalizedReward?: Numberish,
): Promise<BigNumber> {
const stake = await testContract.delegatedStakeToPoolByOwner.callAsync(delegator, poolId);
const stake = await testContract.delegatedStakeToPoolByOwner(delegator, poolId).callAsync();
// Split the rewards up across the two calls to `_computeMemberRewardOverInterval()`
const reward = finalizedReward === undefined ? getRandomInteger(1, 1e18) : new BigNumber(finalizedReward);
const oldRewards = getRandomPortion(reward);
await testContract.setMemberRewardsOverInterval.awaitTransactionSuccessAsync(
poolId,
stake.currentEpochBalance,
stake.currentEpoch,
stake.currentEpoch.plus(1),
oldRewards,
);
await testContract
.setMemberRewardsOverInterval(
poolId,
stake.currentEpochBalance,
stake.currentEpoch,
stake.currentEpoch.plus(1),
oldRewards,
)
.awaitTransactionSuccessAsync();
const newRewards = reward.minus(oldRewards);
await testContract.setMemberRewardsOverInterval.awaitTransactionSuccessAsync(
poolId,
stake.nextEpochBalance,
stake.currentEpoch.plus(1),
await testContract.currentEpoch.callAsync(),
newRewards,
);
await testContract
.setMemberRewardsOverInterval(
poolId,
stake.nextEpochBalance,
stake.currentEpoch.plus(1),
await testContract.currentEpoch().callAsync(),
newRewards,
)
.awaitTransactionSuccessAsync();
return reward;
}
@@ -119,7 +122,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
describe('withdrawDelegatorRewards()', () => {
it('calls `_withdrawAndSyncDelegatorRewards()` with the sender as the member', async () => {
const { logs } = await testContract.withdrawDelegatorRewards.awaitTransactionSuccessAsync(POOL_ID);
const { logs } = await testContract.withdrawDelegatorRewards(POOL_ID).awaitTransactionSuccessAsync();
verifyEventsFromLogs(
logs,
[{ poolId: POOL_ID, delegator: caller }],
@@ -136,14 +139,14 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
before(async () => {
stake = await setStakeAsync(POOL_ID, DELEGATOR);
await testContract.setPoolRewards.awaitTransactionSuccessAsync(POOL_ID, POOL_REWARD);
await testContract.setWethReservedForPoolRewards.awaitTransactionSuccessAsync(
WETH_RESERVED_FOR_POOL_REWARDS,
);
await testContract.setPoolRewards(POOL_ID, POOL_REWARD).awaitTransactionSuccessAsync();
await testContract
.setWethReservedForPoolRewards(WETH_RESERVED_FOR_POOL_REWARDS)
.awaitTransactionSuccessAsync();
});
async function withdrawAndSyncDelegatorRewardsAsync(): Promise<TransactionReceiptWithDecodedLogs> {
return testContract.withdrawAndSyncDelegatorRewards.awaitTransactionSuccessAsync(POOL_ID, DELEGATOR);
return testContract.withdrawAndSyncDelegatorRewards(POOL_ID, DELEGATOR).awaitTransactionSuccessAsync();
}
it('reverts if the pool is not finalized', async () => {
@@ -169,20 +172,20 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const finalizedReward = getRandomPortion(POOL_REWARD);
await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, finalizedReward);
await withdrawAndSyncDelegatorRewardsAsync();
const poolReward = await testContract.rewardsByPoolId.callAsync(POOL_ID);
const poolReward = await testContract.rewardsByPoolId(POOL_ID).callAsync();
expect(poolReward).to.bignumber.eq(POOL_REWARD.minus(finalizedReward));
});
it('reduces `wethReservedForPoolRewards` for the pool', async () => {
const finalizedReward = getRandomPortion(POOL_REWARD);
await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, finalizedReward);
await withdrawAndSyncDelegatorRewardsAsync();
const wethReserved = await testContract.wethReservedForPoolRewards.callAsync();
const wethReserved = await testContract.wethReservedForPoolRewards().callAsync();
expect(wethReserved).to.bignumber.eq(WETH_RESERVED_FOR_POOL_REWARDS.minus(finalizedReward));
});
it('syncs `_delegatedStakeToPoolByOwner`', async () => {
await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, getRandomPortion(POOL_REWARD));
await withdrawAndSyncDelegatorRewardsAsync();
const stakeAfter = await testContract.delegatedStakeToPoolByOwner.callAsync(DELEGATOR, POOL_ID);
const stakeAfter = await testContract.delegatedStakeToPoolByOwner(DELEGATOR, POOL_ID).callAsync();
// `_loadCurrentBalance` is overridden to just increment `currentEpoch`.
expect(stakeAfter).to.deep.eq({
currentEpoch: stake.currentEpoch.plus(1),
@@ -198,7 +201,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
it('no rewards if the delegated stake epoch == current epoch', async () => {
// Set some finalized rewards that should be ignored.
await setComputeDelegatorRewardStateAsync(POOL_ID, DELEGATOR, getRandomInteger(1, POOL_REWARD));
await testContract.setCurrentEpoch.awaitTransactionSuccessAsync(stake.currentEpoch);
await testContract.setCurrentEpoch(stake.currentEpoch).awaitTransactionSuccessAsync();
const { logs } = await withdrawAndSyncDelegatorRewardsAsync();
// There will be no Transfer events if computed rewards are zero.
verifyEventsFromLogs(logs, [], Events.Transfer);
@@ -207,7 +210,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
describe('computeRewardBalanceOfOperator()', () => {
async function computeRewardBalanceOfOperatorAsync(): Promise<BigNumber> {
return testContract.computeRewardBalanceOfOperator.callAsync(POOL_ID);
return testContract.computeRewardBalanceOfOperator(POOL_ID).callAsync();
}
it('returns only unfinalized rewards', async () => {
@@ -239,19 +242,23 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
expect(reward).to.bignumber.eq(unfinalizedReward);
});
it('returns no reward if operator share is zero', async () => {
await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, {
operator: OPERATOR,
operatorShare: constants.ZERO_AMOUNT,
});
await testContract
.setPool(POOL_ID, {
operator: OPERATOR,
operatorShare: constants.ZERO_AMOUNT,
})
.awaitTransactionSuccessAsync();
await setUnfinalizedPoolRewardsAsync(POOL_ID, getRandomInteger(1, 1e18), getRandomInteger(1, 1e18));
const reward = await computeRewardBalanceOfOperatorAsync();
expect(reward).to.bignumber.eq(0);
});
it('returns all unfinalized reward if operator share is 100%', async () => {
await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, {
operator: OPERATOR,
operatorShare: constants.PPM_100_PERCENT,
});
await testContract
.setPool(POOL_ID, {
operator: OPERATOR,
operatorShare: constants.PPM_100_PERCENT,
})
.awaitTransactionSuccessAsync();
const unfinalizedReward = getRandomInteger(1, 1e18);
await setUnfinalizedPoolRewardsAsync(POOL_ID, unfinalizedReward, getRandomInteger(1, 1e18));
const reward = await computeRewardBalanceOfOperatorAsync();
@@ -265,12 +272,12 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
let stake: StoredBalance;
before(async () => {
currentEpoch = await testContract.currentEpoch.callAsync();
currentEpoch = await testContract.currentEpoch().callAsync();
stake = await setStakeAsync(POOL_ID, DELEGATOR);
});
async function computeRewardBalanceOfDelegatorAsync(): Promise<BigNumber> {
return testContract.computeRewardBalanceOfDelegator.callAsync(POOL_ID, DELEGATOR);
return testContract.computeRewardBalanceOfDelegator(POOL_ID, DELEGATOR).callAsync();
}
function getDelegatorPortionOfUnfinalizedReward(
@@ -316,7 +323,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
currentEpoch: new BigNumber(epoch - 2),
nextEpochBalance: constants.ZERO_AMOUNT,
});
await testContract.setCurrentEpoch.awaitTransactionSuccessAsync(new BigNumber(epoch));
await testContract.setCurrentEpoch(new BigNumber(epoch)).awaitTransactionSuccessAsync();
await setUnfinalizedPoolRewardsAsync(POOL_ID, getRandomInteger(1, 1e18), getRandomInteger(1, 1e18));
const reward = await computeRewardBalanceOfDelegatorAsync();
expect(reward).to.bignumber.eq(0);
@@ -348,23 +355,24 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const WETH_RESERVED_FOR_POOL_REWARDS = POOL_REWARD.plus(getRandomInteger(1, 100e18));
before(async () => {
await testContract.setPoolRewards.awaitTransactionSuccessAsync(POOL_ID, POOL_REWARD);
await testContract.setWethReservedForPoolRewards.awaitTransactionSuccessAsync(
WETH_RESERVED_FOR_POOL_REWARDS,
);
await testContract.setPoolRewards(POOL_ID, POOL_REWARD).awaitTransactionSuccessAsync();
await testContract
.setWethReservedForPoolRewards(WETH_RESERVED_FOR_POOL_REWARDS)
.awaitTransactionSuccessAsync();
});
async function syncPoolRewardsAsync(
reward: Numberish,
membersStake: Numberish,
): Promise<[[BigNumber, BigNumber], LogEntry[]]> {
const [result, receipt] = await txHelper.getResultAndReceiptAsync(
testContract.syncPoolRewards,
const contractFn = testContract.syncPoolRewards(
POOL_ID,
new BigNumber(reward),
new BigNumber(membersStake),
);
return [result, receipt.logs];
const result = await contractFn.callAsync();
const { logs } = await contractFn.awaitTransactionSuccessAsync();
return [result, logs];
}
it("transfers operator's portion of the reward to the operator", async () => {
@@ -383,7 +391,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const membersStake = getRandomInteger(1, 1e18);
await syncPoolRewardsAsync(totalReward, membersStake);
const expectedMembersReward = toMembersPortion(OPERATOR_SHARE, totalReward);
const poolReward = await testContract.rewardsByPoolId.callAsync(POOL_ID);
const poolReward = await testContract.rewardsByPoolId(POOL_ID).callAsync();
expect(poolReward).to.bignumber.eq(POOL_REWARD.plus(expectedMembersReward));
});
it("increases `wethReservedForPoolRewards` with members' portion of rewards", async () => {
@@ -391,7 +399,7 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const membersStake = getRandomInteger(1, 1e18);
await syncPoolRewardsAsync(totalReward, membersStake);
const expectedMembersReward = toMembersPortion(OPERATOR_SHARE, totalReward);
const wethReserved = await testContract.wethReservedForPoolRewards.callAsync();
const wethReserved = await testContract.wethReservedForPoolRewards().callAsync();
expect(wethReserved).to.bignumber.eq(WETH_RESERVED_FOR_POOL_REWARDS.plus(expectedMembersReward));
});
it("returns operator and members' portion of the reward", async () => {
@@ -416,10 +424,12 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
});
it("gives all rewards to members if operator's share is zero", async () => {
const totalReward = getRandomInteger(1, 1e18);
await testContract.setPool.awaitTransactionSuccessAsync(POOL_ID, {
operator: OPERATOR,
operatorShare: constants.ZERO_AMOUNT,
});
await testContract
.setPool(POOL_ID, {
operator: OPERATOR,
operatorShare: constants.ZERO_AMOUNT,
})
.awaitTransactionSuccessAsync();
const [[operatorReward, membersReward], logs] = await syncPoolRewardsAsync(
totalReward,
getRandomInteger(1, 1e18),
@@ -436,11 +446,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const operatorShare = getRandomPortion(constants.PPM_100_PERCENT);
const totalReward = getRandomInteger(1, 1e18);
const membersStake = constants.ZERO_AMOUNT;
const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync(
operatorShare,
totalReward,
membersStake,
);
const [operatorReward, membersReward] = await testContract
.computePoolRewardsSplit(operatorShare, totalReward, membersStake)
.callAsync();
expect(operatorReward).to.bignumber.eq(totalReward);
expect(membersReward).to.bignumber.eq(0);
});
@@ -448,11 +456,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const operatorShare = constants.ZERO_AMOUNT;
const totalReward = getRandomInteger(1, 1e18);
const membersStake = constants.ZERO_AMOUNT;
const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync(
operatorShare,
totalReward,
membersStake,
);
const [operatorReward, membersReward] = await testContract
.computePoolRewardsSplit(operatorShare, totalReward, membersStake)
.callAsync();
expect(operatorReward).to.bignumber.eq(totalReward);
expect(membersReward).to.bignumber.eq(0);
});
@@ -460,11 +466,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const operatorShare = constants.PPM_100_PERCENT;
const totalReward = getRandomInteger(1, 1e18);
const membersStake = getRandomInteger(1, 1e18);
const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync(
operatorShare,
totalReward,
membersStake,
);
const [operatorReward, membersReward] = await testContract
.computePoolRewardsSplit(operatorShare, totalReward, membersStake)
.callAsync();
expect(operatorReward).to.bignumber.eq(totalReward);
expect(membersReward).to.bignumber.eq(0);
});
@@ -472,11 +476,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const operatorShare = constants.ZERO_AMOUNT;
const totalReward = getRandomInteger(1, 1e18);
const membersStake = getRandomInteger(1, 1e18);
const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync(
operatorShare,
totalReward,
membersStake,
);
const [operatorReward, membersReward] = await testContract
.computePoolRewardsSplit(operatorShare, totalReward, membersStake)
.callAsync();
expect(operatorReward).to.bignumber.eq(0);
expect(membersReward).to.bignumber.eq(totalReward);
});
@@ -484,11 +486,9 @@ blockchainTests.resets('MixinStakingPoolRewards unit tests', env => {
const operatorShare = getRandomPortion(constants.PPM_100_PERCENT);
const totalReward = getRandomInteger(1, 1e18);
const membersStake = getRandomInteger(1, 1e18);
const [operatorReward, membersReward] = await testContract.computePoolRewardsSplit.callAsync(
operatorShare,
totalReward,
membersStake,
);
const [operatorReward, membersReward] = await testContract
.computePoolRewardsSplit(operatorShare, totalReward, membersStake)
.callAsync();
expect(operatorReward).to.bignumber.eq(toOperatorPortion(operatorShare, totalReward));
expect(membersReward).to.bignumber.eq(toMembersPortion(operatorShare, totalReward));
});

View File

@@ -22,7 +22,7 @@ blockchainTests('Configurable Parameters unit tests', env => {
env.txDefaults,
artifacts,
);
await testContract.addAuthorizedAddress.awaitTransactionSuccessAsync(authorizedAddress);
await testContract.addAuthorizedAddress(authorizedAddress).awaitTransactionSuccessAsync();
});
blockchainTests.resets('setParams()', () => {
@@ -34,14 +34,15 @@ blockchainTests('Configurable Parameters unit tests', env => {
...stakingConstants.DEFAULT_PARAMS,
...params,
};
const receipt = await testContract.setParams.awaitTransactionSuccessAsync(
new BigNumber(_params.epochDurationInSeconds),
new BigNumber(_params.rewardDelegatedStakeWeight),
new BigNumber(_params.minimumPoolStake),
new BigNumber(_params.cobbDouglasAlphaNumerator),
new BigNumber(_params.cobbDouglasAlphaDenominator),
{ from },
);
const receipt = await testContract
.setParams(
new BigNumber(_params.epochDurationInSeconds),
new BigNumber(_params.rewardDelegatedStakeWeight),
new BigNumber(_params.minimumPoolStake),
new BigNumber(_params.cobbDouglasAlphaNumerator),
new BigNumber(_params.cobbDouglasAlphaDenominator),
)
.awaitTransactionSuccessAsync({ from });
// Assert event.
const events = filterLogsToArguments<IStakingEventsParamsSetEventArgs>(receipt.logs, 'ParamsSet');
expect(events.length).to.eq(1);
@@ -52,7 +53,7 @@ blockchainTests('Configurable Parameters unit tests', env => {
expect(event.cobbDouglasAlphaNumerator).to.bignumber.eq(_params.cobbDouglasAlphaNumerator);
expect(event.cobbDouglasAlphaDenominator).to.bignumber.eq(_params.cobbDouglasAlphaDenominator);
// Assert `getParams()`.
const actual = await testContract.getParams.callAsync();
const actual = await testContract.getParams().callAsync();
expect(actual[0]).to.bignumber.eq(_params.epochDurationInSeconds);
expect(actual[1]).to.bignumber.eq(_params.rewardDelegatedStakeWeight);
expect(actual[2]).to.bignumber.eq(_params.minimumPoolStake);
@@ -68,7 +69,7 @@ blockchainTests('Configurable Parameters unit tests', env => {
});
it('throws if `assertValidStorageParams()` throws`', async () => {
await testContract.setShouldFailAssertValidStorageParams.awaitTransactionSuccessAsync(true);
await testContract.setShouldFailAssertValidStorageParams(true).awaitTransactionSuccessAsync();
const tx = setParamsAndAssertAsync({});
return expect(tx).to.revertWith('ASSERT_VALID_STORAGE_PARAMS_FAILED');
});

View File

@@ -45,7 +45,7 @@ blockchainTests('Protocol Fees unit tests', env => {
exchangeAddress,
);
minimumStake = (await testContract.getParams.callAsync())[2];
minimumStake = (await testContract.getParams().callAsync())[2];
});
interface CreateTestPoolOpts {
@@ -63,12 +63,14 @@ blockchainTests('Protocol Fees unit tests', env => {
makers: _.times(2, () => randomAddress()),
...opts,
};
await testContract.createTestPool.awaitTransactionSuccessAsync(
_opts.poolId,
new BigNumber(_opts.operatorStake),
new BigNumber(_opts.membersStake),
_opts.makers,
);
await testContract
.createTestPool(
_opts.poolId,
new BigNumber(_opts.operatorStake),
new BigNumber(_opts.membersStake),
_opts.makers,
)
.awaitTransactionSuccessAsync();
return _opts;
}
@@ -80,23 +82,17 @@ blockchainTests('Protocol Fees unit tests', env => {
describe('forbidden actions', () => {
it('should revert if called by a non-exchange', async () => {
const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: notExchangeAddress },
);
const tx = testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: notExchangeAddress });
const expectedError = new StakingRevertErrors.OnlyCallableByExchangeError(notExchangeAddress);
return expect(tx).to.revertWith(expectedError);
});
it('should revert if `protocolFee` is zero with non-zero value sent', async () => {
const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
ZERO_AMOUNT,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
const tx = testContract
.payProtocolFee(makerAddress, payerAddress, ZERO_AMOUNT)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
const expectedError = new StakingRevertErrors.InvalidProtocolFeePaymentError(
ZERO_AMOUNT,
DEFAULT_PROTOCOL_FEE_PAID,
@@ -105,12 +101,9 @@ blockchainTests('Protocol Fees unit tests', env => {
});
it('should revert if `protocolFee` is < than the provided message value', async () => {
const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.minus(1) },
);
const tx = testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.minus(1) });
const expectedError = new StakingRevertErrors.InvalidProtocolFeePaymentError(
DEFAULT_PROTOCOL_FEE_PAID,
DEFAULT_PROTOCOL_FEE_PAID.minus(1),
@@ -119,12 +112,9 @@ blockchainTests('Protocol Fees unit tests', env => {
});
it('should revert if `protocolFee` is > than the provided message value', async () => {
const tx = testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.plus(1) },
);
const tx = testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID.plus(1) });
const expectedError = new StakingRevertErrors.InvalidProtocolFeePaymentError(
DEFAULT_PROTOCOL_FEE_PAID,
DEFAULT_PROTOCOL_FEE_PAID.plus(1),
@@ -134,7 +124,7 @@ blockchainTests('Protocol Fees unit tests', env => {
});
async function getProtocolFeesAsync(poolId: string): Promise<BigNumber> {
return (await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId)).feesCollected;
return (await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync()).feesCollected;
}
describe('ETH fees', () => {
@@ -148,23 +138,17 @@ blockchainTests('Protocol Fees unit tests', env => {
it('should not transfer WETH if value is sent', async () => {
await createTestPoolAsync({ operatorStake: minimumStake });
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
assertNoWETHTransferLogs(receipt.logs);
});
it('should credit pool if the maker is in a pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] });
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
assertNoWETHTransferLogs(receipt.logs);
const poolFees = await getProtocolFeesAsync(poolId);
@@ -173,12 +157,9 @@ blockchainTests('Protocol Fees unit tests', env => {
it('should not credit the pool if maker is not in a pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake });
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
assertNoWETHTransferLogs(receipt.logs);
const poolFees = await getProtocolFeesAsync(poolId);
expect(poolFees).to.bignumber.eq(ZERO_AMOUNT);
@@ -187,12 +168,9 @@ blockchainTests('Protocol Fees unit tests', env => {
it('fees paid to the same maker should go to the same pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] });
const payAsync = async () => {
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
assertNoWETHTransferLogs(receipt.logs);
};
await payAsync();
@@ -219,23 +197,17 @@ blockchainTests('Protocol Fees unit tests', env => {
it('should transfer WETH if no value is sent and the maker is not in a pool', async () => {
await createTestPoolAsync({ operatorStake: minimumStake });
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: ZERO_AMOUNT },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT });
assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID);
});
it('should update `protocolFeesThisEpochByPool` if the maker is in a pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] });
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: ZERO_AMOUNT },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT });
assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID);
const poolFees = await getProtocolFeesAsync(poolId);
expect(poolFees).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
@@ -243,12 +215,9 @@ blockchainTests('Protocol Fees unit tests', env => {
it('should not update `protocolFeesThisEpochByPool` if maker is not in a pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake });
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: ZERO_AMOUNT },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT });
assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID);
const poolFees = await getProtocolFeesAsync(poolId);
expect(poolFees).to.bignumber.eq(ZERO_AMOUNT);
@@ -257,12 +226,9 @@ blockchainTests('Protocol Fees unit tests', env => {
it('fees paid to the same maker should go to the same pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] });
const payAsync = async () => {
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: ZERO_AMOUNT },
);
const receipt = await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: ZERO_AMOUNT });
assertWETHTransferLogs(receipt.logs, payerAddress, DEFAULT_PROTOCOL_FEE_PAID);
};
await payAsync();
@@ -275,15 +241,12 @@ blockchainTests('Protocol Fees unit tests', env => {
it('fees paid to the same maker in WETH then ETH should go to the same pool', async () => {
const { poolId } = await createTestPoolAsync({ operatorStake: minimumStake, makers: [makerAddress] });
const payAsync = async (inWETH: boolean) => {
await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
payerAddress,
DEFAULT_PROTOCOL_FEE_PAID,
{
await testContract
.payProtocolFee(makerAddress, payerAddress, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({
from: exchangeAddress,
value: inWETH ? ZERO_AMOUNT : DEFAULT_PROTOCOL_FEE_PAID,
},
);
});
};
await payAsync(true);
await payAsync(false);
@@ -300,12 +263,9 @@ blockchainTests('Protocol Fees unit tests', env => {
membersStake: 0,
makers: [makerAddress],
});
await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
constants.NULL_ADDRESS,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
await testContract
.payProtocolFee(makerAddress, constants.NULL_ADDRESS, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
const feesCredited = await getProtocolFeesAsync(poolId);
expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
});
@@ -316,12 +276,9 @@ blockchainTests('Protocol Fees unit tests', env => {
membersStake: 0,
makers: [makerAddress],
});
await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
constants.NULL_ADDRESS,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
await testContract
.payProtocolFee(makerAddress, constants.NULL_ADDRESS, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
const feesCredited = await getProtocolFeesAsync(poolId);
expect(feesCredited).to.bignumber.eq(DEFAULT_PROTOCOL_FEE_PAID);
});
@@ -332,12 +289,9 @@ blockchainTests('Protocol Fees unit tests', env => {
membersStake: 0,
makers: [makerAddress],
});
await testContract.payProtocolFee.awaitTransactionSuccessAsync(
makerAddress,
constants.NULL_ADDRESS,
DEFAULT_PROTOCOL_FEE_PAID,
{ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID },
);
await testContract
.payProtocolFee(makerAddress, constants.NULL_ADDRESS, DEFAULT_PROTOCOL_FEE_PAID)
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: DEFAULT_PROTOCOL_FEE_PAID });
const feesCredited = await getProtocolFeesAsync(poolId);
expect(feesCredited).to.bignumber.eq(0);
});
@@ -347,7 +301,7 @@ blockchainTests('Protocol Fees unit tests', env => {
let membersStakeWeight: number;
before(async () => {
membersStakeWeight = (await testContract.getParams.callAsync())[1];
membersStakeWeight = (await testContract.getParams().callAsync())[1];
});
interface FinalizationState {
@@ -357,7 +311,7 @@ blockchainTests('Protocol Fees unit tests', env => {
}
async function getFinalizationStateAsync(): Promise<FinalizationState> {
const aggregatedStats = await testContract.getAggregatedStatsForCurrentEpoch.callAsync();
const aggregatedStats = await testContract.getAggregatedStatsForCurrentEpoch().callAsync();
return {
numPoolsToFinalize: aggregatedStats.numPoolsToFinalize,
totalFeesCollected: aggregatedStats.totalFeesCollected,
@@ -372,12 +326,9 @@ blockchainTests('Protocol Fees unit tests', env => {
async function payToMakerAsync(poolMaker: string, fee?: Numberish): Promise<PayToMakerResult> {
const _fee = fee === undefined ? getRandomInteger(1, '1e18') : fee;
const receipt = await testContract.payProtocolFee.awaitTransactionSuccessAsync(
poolMaker,
payerAddress,
new BigNumber(_fee),
{ from: exchangeAddress, value: _fee },
);
const receipt = await testContract
.payProtocolFee(poolMaker, payerAddress, new BigNumber(_fee))
.awaitTransactionSuccessAsync({ from: exchangeAddress, value: _fee });
const events = filterLogsToArguments<IStakingEventsStakingPoolEarnedRewardsInEpochEventArgs>(
receipt.logs,
IStakingEventsEvents.StakingPoolEarnedRewardsInEpoch,
@@ -404,7 +355,7 @@ blockchainTests('Protocol Fees unit tests', env => {
it('pool is not registered to start', async () => {
const { poolId } = await createTestPoolAsync();
const pool = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId);
const pool = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync();
expect(pool.feesCollected).to.bignumber.eq(0);
expect(pool.membersStake).to.bignumber.eq(0);
expect(pool.weightedStake).to.bignumber.eq(0);
@@ -419,7 +370,7 @@ blockchainTests('Protocol Fees unit tests', env => {
const { fee, poolEarnedRewardsEvents } = await payToMakerAsync(poolMaker);
expect(poolEarnedRewardsEvents.length).to.eq(1);
expect(poolEarnedRewardsEvents[0].poolId).to.eq(poolId);
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId);
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync();
const expectedWeightedStake = toWeightedStake(pool.operatorStake, pool.membersStake);
expect(actualPoolStats.feesCollected).to.bignumber.eq(fee);
expect(actualPoolStats.membersStake).to.bignumber.eq(pool.membersStake);
@@ -439,7 +390,7 @@ blockchainTests('Protocol Fees unit tests', env => {
const { fee: fee1 } = await payToMakerAsync(poolMaker);
const { fee: fee2, poolEarnedRewardsEvents } = await payToMakerAsync(poolMaker);
expect(poolEarnedRewardsEvents).to.deep.eq([]);
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId);
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync();
const expectedWeightedStake = toWeightedStake(pool.operatorStake, pool.membersStake);
const fees = BigNumber.sum(fee1, fee2);
expect(actualPoolStats.feesCollected).to.bignumber.eq(fees);
@@ -463,7 +414,7 @@ blockchainTests('Protocol Fees unit tests', env => {
const { fee, poolEarnedRewardsEvents } = await payToMakerAsync(poolMaker);
expect(poolEarnedRewardsEvents.length).to.eq(1);
expect(poolEarnedRewardsEvents[0].poolId).to.eq(poolId);
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId);
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync();
const expectedWeightedStake = toWeightedStake(pool.operatorStake, pool.membersStake);
expect(actualPoolStats.feesCollected).to.bignumber.eq(fee);
expect(actualPoolStats.membersStake).to.bignumber.eq(pool.membersStake);
@@ -484,8 +435,8 @@ blockchainTests('Protocol Fees unit tests', env => {
makers: [poolMaker],
} = pool;
await payToMakerAsync(poolMaker);
await testContract.advanceEpoch.awaitTransactionSuccessAsync();
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch.callAsync(poolId);
await testContract.advanceEpoch().awaitTransactionSuccessAsync();
const actualPoolStats = await testContract.getStakingPoolStatsThisEpoch(poolId).callAsync();
expect(actualPoolStats.feesCollected).to.bignumber.eq(0);
expect(actualPoolStats.membersStake).to.bignumber.eq(0);
expect(actualPoolStats.weightedStake).to.bignumber.eq(0);

View File

@@ -61,11 +61,10 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
);
before(async () => {
await testContract.setGlobalStakeByStatus.awaitTransactionSuccessAsync(
StakeStatus.Delegated,
delegatedBalance,
);
await testContract.setBalanceOfZrxVault.awaitTransactionSuccessAsync(zrxVaultBalance);
await testContract
.setGlobalStakeByStatus(StakeStatus.Delegated, delegatedBalance)
.awaitTransactionSuccessAsync();
await testContract.setBalanceOfZrxVault(zrxVaultBalance).awaitTransactionSuccessAsync();
});
it('undelegated stake is the difference between zrx vault balance and global delegated stake', async () => {
@@ -74,12 +73,12 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
currentEpochBalance: zrxVaultBalance.minus(delegatedBalance.currentEpochBalance),
nextEpochBalance: zrxVaultBalance.minus(delegatedBalance.nextEpochBalance),
};
const actualBalance = await testContract.getGlobalStakeByStatus.callAsync(StakeStatus.Undelegated);
const actualBalance = await testContract.getGlobalStakeByStatus(StakeStatus.Undelegated).callAsync();
expect(actualBalance).to.deep.eq(expectedBalance);
});
it('delegated stake is the global delegated stake', async () => {
const actualBalance = await testContract.getGlobalStakeByStatus.callAsync(StakeStatus.Delegated);
const actualBalance = await testContract.getGlobalStakeByStatus(StakeStatus.Delegated).callAsync();
expect(actualBalance).to.deep.eq(toCurrentBalance(delegatedBalance));
});
@@ -88,8 +87,8 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
delegatedBalance.currentEpochBalance,
delegatedBalance.nextEpochBalance,
).minus(1);
await testContract.setBalanceOfZrxVault.awaitTransactionSuccessAsync(_zrxVaultBalance);
const tx = testContract.getGlobalStakeByStatus.callAsync(StakeStatus.Undelegated);
await testContract.setBalanceOfZrxVault(_zrxVaultBalance).awaitTransactionSuccessAsync();
const tx = testContract.getGlobalStakeByStatus(StakeStatus.Undelegated).callAsync();
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.SubtractionUnderflow,
_zrxVaultBalance,
@@ -101,7 +100,7 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
});
it('throws if unknown stake status is passed in', async () => {
const tx = testContract.getGlobalStakeByStatus.callAsync(2);
const tx = testContract.getGlobalStakeByStatus(2).callAsync();
return expect(tx).to.be.rejected();
});
});
@@ -113,40 +112,36 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
const undelegatedStake = randomStoredBalance();
before(async () => {
await testContract.setOwnerStakeByStatus.awaitTransactionSuccessAsync(
staker,
StakeStatus.Delegated,
delegatedStake,
);
await testContract.setOwnerStakeByStatus.awaitTransactionSuccessAsync(
staker,
StakeStatus.Undelegated,
undelegatedStake,
);
await testContract
.setOwnerStakeByStatus(staker, StakeStatus.Delegated, delegatedStake)
.awaitTransactionSuccessAsync();
await testContract
.setOwnerStakeByStatus(staker, StakeStatus.Undelegated, undelegatedStake)
.awaitTransactionSuccessAsync();
});
it('throws if unknown stake status is passed in', async () => {
const tx = testContract.getOwnerStakeByStatus.callAsync(staker, 2);
const tx = testContract.getOwnerStakeByStatus(staker, 2).callAsync();
return expect(tx).to.be.rejected();
});
it('returns empty delegated stake for an unstaked owner', async () => {
const balance = await testContract.getOwnerStakeByStatus.callAsync(notStaker, StakeStatus.Delegated);
const balance = await testContract.getOwnerStakeByStatus(notStaker, StakeStatus.Delegated).callAsync();
expect(balance).to.deep.eq(EMPTY_BALANCE);
});
it('returns empty undelegated stake for an unstaked owner', async () => {
const balance = await testContract.getOwnerStakeByStatus.callAsync(notStaker, StakeStatus.Undelegated);
const balance = await testContract.getOwnerStakeByStatus(notStaker, StakeStatus.Undelegated).callAsync();
expect(balance).to.deep.eq(EMPTY_BALANCE);
});
it('returns undelegated stake for a staked owner', async () => {
const balance = await testContract.getOwnerStakeByStatus.callAsync(staker, StakeStatus.Undelegated);
const balance = await testContract.getOwnerStakeByStatus(staker, StakeStatus.Undelegated).callAsync();
expect(balance).to.deep.eq(toCurrentBalance(undelegatedStake));
});
it('returns delegated stake for a staked owner', async () => {
const balance = await testContract.getOwnerStakeByStatus.callAsync(staker, StakeStatus.Delegated);
const balance = await testContract.getOwnerStakeByStatus(staker, StakeStatus.Delegated).callAsync();
expect(balance).to.deep.eq(toCurrentBalance(delegatedStake));
});
});
@@ -157,16 +152,16 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
const stakerAmount = randomAmount();
before(async () => {
await testContract.setZrxBalanceOf.awaitTransactionSuccessAsync(staker, stakerAmount);
await testContract.setZrxBalanceOf(staker, stakerAmount).awaitTransactionSuccessAsync();
});
it('returns empty for unstaked owner', async () => {
const amount = await testContract.getTotalStake.callAsync(notStaker);
const amount = await testContract.getTotalStake(notStaker).callAsync();
expect(amount).to.bignumber.eq(0);
});
it('returns stake for staked owner', async () => {
const amount = await testContract.getTotalStake.callAsync(staker);
const amount = await testContract.getTotalStake(staker).callAsync();
expect(amount).to.bignumber.eq(stakerAmount);
});
});
@@ -179,25 +174,23 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
const delegatedBalance = randomStoredBalance();
before(async () => {
await testContract.setDelegatedStakeToPoolByOwner.awaitTransactionSuccessAsync(
staker,
poolId,
delegatedBalance,
);
await testContract
.setDelegatedStakeToPoolByOwner(staker, poolId, delegatedBalance)
.awaitTransactionSuccessAsync();
});
it('returns empty for unstaked owner', async () => {
const balance = await testContract.getStakeDelegatedToPoolByOwner.callAsync(notStaker, poolId);
const balance = await testContract.getStakeDelegatedToPoolByOwner(notStaker, poolId).callAsync();
expect(balance).to.deep.eq(EMPTY_BALANCE);
});
it('returns empty for empty pool', async () => {
const balance = await testContract.getStakeDelegatedToPoolByOwner.callAsync(staker, notPoolId);
const balance = await testContract.getStakeDelegatedToPoolByOwner(staker, notPoolId).callAsync();
expect(balance).to.deep.eq(EMPTY_BALANCE);
});
it('returns stake for staked owner in their pool', async () => {
const balance = await testContract.getStakeDelegatedToPoolByOwner.callAsync(staker, poolId);
const balance = await testContract.getStakeDelegatedToPoolByOwner(staker, poolId).callAsync();
expect(balance).to.deep.eq(toCurrentBalance(delegatedBalance));
});
});
@@ -208,16 +201,16 @@ blockchainTests.resets('MixinStakeBalances unit tests', env => {
const delegatedBalance = randomStoredBalance();
before(async () => {
await testContract.setDelegatedStakeByPoolId.awaitTransactionSuccessAsync(poolId, delegatedBalance);
await testContract.setDelegatedStakeByPoolId(poolId, delegatedBalance).awaitTransactionSuccessAsync();
});
it('returns empty for empty pool', async () => {
const balance = await testContract.getTotalStakeDelegatedToPool.callAsync(notPoolId);
const balance = await testContract.getTotalStakeDelegatedToPool(notPoolId).callAsync();
expect(balance).to.deep.eq(EMPTY_BALANCE);
});
it('returns stake for staked pool', async () => {
const balance = await testContract.getTotalStakeDelegatedToPool.callAsync(poolId);
const balance = await testContract.getTotalStakeDelegatedToPool(poolId).callAsync();
expect(balance).to.deep.eq(toCurrentBalance(delegatedBalance));
});
});

View File

@@ -46,17 +46,16 @@ blockchainTests.resets('MixinStake unit tests', env => {
env.txDefaults,
artifacts,
);
currentEpoch = await testContract.currentEpoch.callAsync();
stakerUndelegatedStakeSlot = await testContract.getOwnerStakeByStatusSlot.callAsync(
staker,
StakeStatus.Undelegated,
);
currentEpoch = await testContract.currentEpoch().callAsync();
stakerUndelegatedStakeSlot = await testContract
.getOwnerStakeByStatusSlot(staker, StakeStatus.Undelegated)
.callAsync();
});
describe('stake()', () => {
it('deposits funds into the ZRX vault', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.stake.awaitTransactionSuccessAsync(amount);
const { logs } = await testContract.stake(amount).awaitTransactionSuccessAsync();
const events = filterLogsToArguments<ZrxVaultDepositFromEventArgs>(logs, StakeEvents.ZrxVaultDepositFrom);
expect(events).to.be.length(1);
expect(events[0].staker).to.eq(staker);
@@ -65,7 +64,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('increases current and next undelegated stake balance', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.stake.awaitTransactionSuccessAsync(amount);
const { logs } = await testContract.stake(amount).awaitTransactionSuccessAsync();
const events = filterLogsToArguments<IncreaseCurrentAndNextBalanceEventArgs>(
logs,
StakeEvents.IncreaseCurrentAndNextBalance,
@@ -77,7 +76,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('raises a `Stake` event', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.stake.awaitTransactionSuccessAsync(amount);
const { logs } = await testContract.stake(amount).awaitTransactionSuccessAsync();
const events = filterLogsToArguments<StakeEventArgs>(logs, StakeEvents.Stake);
expect(events).to.be.length(1);
expect(events[0].staker).to.eq(staker);
@@ -90,17 +89,19 @@ blockchainTests.resets('MixinStake unit tests', env => {
currentEpochBalance: Numberish,
nextEpochBalance: Numberish,
): Promise<void> {
await testContract.setOwnerStakeByStatus.awaitTransactionSuccessAsync(staker, StakeStatus.Undelegated, {
currentEpoch,
currentEpochBalance: new BigNumber(currentEpochBalance),
nextEpochBalance: new BigNumber(nextEpochBalance),
});
await testContract
.setOwnerStakeByStatus(staker, StakeStatus.Undelegated, {
currentEpoch,
currentEpochBalance: new BigNumber(currentEpochBalance),
nextEpochBalance: new BigNumber(nextEpochBalance),
})
.awaitTransactionSuccessAsync();
}
it('throws if not enough undelegated stake in the current epoch', async () => {
const amount = getRandomInteger(0, 100e18);
await setUndelegatedStakeAsync(amount.minus(1), amount);
const tx = testContract.unstake.awaitTransactionSuccessAsync(amount);
const tx = testContract.unstake(amount).awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InsufficientBalanceError(amount, amount.minus(1));
return expect(tx).to.revertWith(expectedError);
});
@@ -108,7 +109,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('throws if not enough undelegated stake in the next epoch', async () => {
const amount = getRandomInteger(0, 100e18);
await setUndelegatedStakeAsync(amount, amount.minus(1));
const tx = testContract.unstake.awaitTransactionSuccessAsync(amount);
const tx = testContract.unstake(amount).awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InsufficientBalanceError(amount, amount.minus(1));
return expect(tx).to.revertWith(expectedError);
});
@@ -116,7 +117,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('throws if not enough undelegated stake in both epochs', async () => {
const amount = getRandomInteger(0, 100e18);
await setUndelegatedStakeAsync(amount.minus(1), amount.minus(1));
const tx = testContract.unstake.awaitTransactionSuccessAsync(amount);
const tx = testContract.unstake(amount).awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.InsufficientBalanceError(amount, amount.minus(1));
return expect(tx).to.revertWith(expectedError);
});
@@ -124,7 +125,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('decreases current and next undelegated stake balance', async () => {
const amount = getRandomInteger(0, 100e18);
await setUndelegatedStakeAsync(amount, amount);
const { logs } = await testContract.unstake.awaitTransactionSuccessAsync(amount);
const { logs } = await testContract.unstake(amount).awaitTransactionSuccessAsync();
const events = filterLogsToArguments<DecreaseCurrentAndNextBalanceEventArgs>(
logs,
StakeEvents.DecreaseCurrentAndNextBalance,
@@ -137,7 +138,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('withdraws funds from the ZRX vault', async () => {
const amount = getRandomInteger(0, 100e18);
await setUndelegatedStakeAsync(amount, amount);
const { logs } = await testContract.unstake.awaitTransactionSuccessAsync(amount);
const { logs } = await testContract.unstake(amount).awaitTransactionSuccessAsync();
const events = filterLogsToArguments<ZrxVaultWithdrawFromEventArgs>(logs, StakeEvents.ZrxVaultWithdrawFrom);
expect(events).to.be.length(1);
expect(events[0].staker).to.eq(staker);
@@ -147,7 +148,7 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('emits an `Unstake` event', async () => {
const amount = getRandomInteger(0, 100e18);
await setUndelegatedStakeAsync(amount, amount);
const { logs } = await testContract.unstake.awaitTransactionSuccessAsync(amount);
const { logs } = await testContract.unstake(amount).awaitTransactionSuccessAsync();
const events = filterLogsToArguments<UnstakeEventArgs>(logs, StakeEvents.Unstake);
expect(events).to.be.length(1);
expect(events[0].staker).to.eq(staker);
@@ -167,52 +168,59 @@ blockchainTests.resets('MixinStake unit tests', env => {
before(async () => {
delegatedStakeToPoolByOwnerSlots = await Promise.all(
VALID_POOL_IDS.map(async poolId =>
testContract.getDelegatedStakeToPoolByOwnerSlot.callAsync(poolId, staker),
testContract.getDelegatedStakeToPoolByOwnerSlot(poolId, staker).callAsync(),
),
);
delegatedStakeByPoolIdSlots = await Promise.all(
VALID_POOL_IDS.map(async poolId => testContract.getDelegatedStakeByPoolIdSlot.callAsync(poolId)),
);
globalDelegatedStakeSlot = await testContract.getGlobalStakeByStatusSlot.callAsync(StakeStatus.Delegated);
stakerDelegatedStakeSlot = await testContract.getOwnerStakeByStatusSlot.callAsync(
staker,
StakeStatus.Delegated,
VALID_POOL_IDS.map(async poolId => testContract.getDelegatedStakeByPoolIdSlot(poolId).callAsync()),
);
globalDelegatedStakeSlot = await testContract.getGlobalStakeByStatusSlot(StakeStatus.Delegated).callAsync();
stakerDelegatedStakeSlot = await testContract
.getOwnerStakeByStatusSlot(staker, StakeStatus.Delegated)
.callAsync();
});
it('throws if the "from" pool is invalid', async () => {
const tx = testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
getRandomInteger(0, 100e18),
);
const tx = testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(INVALID_POOL_ERROR);
});
it('throws if the "to" pool is invalid', async () => {
const tx = testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
getRandomInteger(0, 100e18),
);
const tx = testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(INVALID_POOL_ERROR);
});
it('throws if the "from" and "to" pools are invalid', async () => {
const tx = testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
getRandomInteger(0, 100e18),
);
const tx = testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
{ status: StakeStatus.Delegated, poolId: INVALID_POOL_ID },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
return expect(tx).to.revertWith(INVALID_POOL_ERROR);
});
it('withdraws delegator rewards when "from" stake is delegated', async () => {
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<WithdrawAndSyncDelegatorRewardsEventArgs>(
logs,
StakeEvents.WithdrawAndSyncDelegatorRewards,
@@ -223,11 +231,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
});
it('withdraws delegator rewards when "to" stake is delegated', async () => {
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<WithdrawAndSyncDelegatorRewardsEventArgs>(
logs,
StakeEvents.WithdrawAndSyncDelegatorRewards,
@@ -238,11 +248,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
});
it('withdraws delegator rewards when both stakes are both delegated', async () => {
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<WithdrawAndSyncDelegatorRewardsEventArgs>(
logs,
StakeEvents.WithdrawAndSyncDelegatorRewards,
@@ -255,11 +267,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
});
it('does not withdraw delegator rewards when both stakes are both undelegated', async () => {
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
getRandomInteger(0, 100e18),
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<WithdrawAndSyncDelegatorRewardsEventArgs>(
logs,
StakeEvents.WithdrawAndSyncDelegatorRewards,
@@ -269,11 +283,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('decreases pool and global delegated stake counters when "from" stake is delegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const decreaseNextBalanceEvents = filterLogsToArguments<DecreaseNextBalanceEventArgs>(
logs,
StakeEvents.DecreaseNextBalance,
@@ -292,11 +308,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('increases pool and global delegated stake counters when "to" stake is delegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const increaseNextBalanceEvents = filterLogsToArguments<IncreaseNextBalanceEventArgs>(
logs,
StakeEvents.IncreaseNextBalance,
@@ -315,11 +333,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('decreases then increases pool and global delegated stake counters when both stakes are delegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const decreaseNextBalanceEvents = filterLogs<DecreaseNextBalanceEventArgs>(
logs,
StakeEvents.DecreaseNextBalance,
@@ -356,11 +376,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('does not change pool and global delegated stake counters when both stakes are undelegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const decreaseNextBalanceEvents = filterLogsToArguments<DecreaseNextBalanceEventArgs>(
logs,
StakeEvents.DecreaseNextBalance,
@@ -375,33 +397,39 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('does nothing when moving the owner stake from undelegated to undelegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<MoveStakeStorageEventArgs>(logs, StakeEvents.MoveStakeStorage);
expect(events).to.be.length(0);
});
it('does nothing when moving zero stake', async () => {
const amount = new BigNumber(0);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<MoveStakeStorageEventArgs>(logs, StakeEvents.MoveStakeStorage);
expect(events).to.be.length(0);
});
it('moves the owner stake between the same pointer when both are delegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<MoveStakeStorageEventArgs>(logs, StakeEvents.MoveStakeStorage);
expect(events).to.be.length(1);
expect(events[0].fromBalanceSlot).to.eq(stakerDelegatedStakeSlot);
@@ -411,11 +439,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('moves the owner stake between different pointers when "from" is undelegated and "to" is delegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<MoveStakeStorageEventArgs>(logs, StakeEvents.MoveStakeStorage);
expect(events).to.be.length(1);
expect(events[0].fromBalanceSlot).to.eq(stakerUndelegatedStakeSlot);
@@ -425,11 +455,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('moves the owner stake between different pointers when "from" is delegated and "to" is undelegated', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<MoveStakeStorageEventArgs>(logs, StakeEvents.MoveStakeStorage);
expect(events).to.be.length(1);
expect(events[0].fromBalanceSlot).to.eq(stakerDelegatedStakeSlot);
@@ -439,11 +471,13 @@ blockchainTests.resets('MixinStake unit tests', env => {
it('emits a `MoveStake` event', async () => {
const amount = getRandomInteger(0, 100e18);
const { logs } = await testContract.moveStake.awaitTransactionSuccessAsync(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
);
const { logs } = await testContract
.moveStake(
{ status: StakeStatus.Undelegated, poolId: VALID_POOL_IDS[0] },
{ status: StakeStatus.Delegated, poolId: VALID_POOL_IDS[1] },
amount,
)
.awaitTransactionSuccessAsync();
const events = filterLogsToArguments<MoveStakeEventArgs>(logs, StakeEvents.MoveStake);
expect(events).to.be.length(1);
expect(events[0].staker).to.eq(staker);

View File

@@ -56,34 +56,36 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
operatorShare: randomOperatorShare(),
...opts,
};
await testContract.setPoolById.awaitTransactionSuccessAsync(_opts.poolId, {
operator: _opts.operator,
operatorShare: _opts.operatorShare,
});
await testContract
.setPoolById(_opts.poolId, {
operator: _opts.operator,
operatorShare: _opts.operatorShare,
})
.awaitTransactionSuccessAsync();
return _opts;
}
async function addMakerToPoolAsync(poolId: string, _maker: string): Promise<void> {
await testContract.setPoolIdByMaker.awaitTransactionSuccessAsync(poolId, _maker);
await testContract.setPoolIdByMaker(poolId, _maker).awaitTransactionSuccessAsync();
}
describe('onlyStakingPoolOperator modifier', () => {
it('fails if not called by the pool operator', async () => {
const { poolId } = await createPoolAsync();
const tx = testContract.testOnlyStakingPoolOperatorModifier.callAsync(poolId, { from: notOperatorOrMaker });
const tx = testContract.testOnlyStakingPoolOperatorModifier(poolId).callAsync({ from: notOperatorOrMaker });
const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(notOperatorOrMaker, poolId);
return expect(tx).to.revertWith(expectedError);
});
it('fails if called by a pool maker', async () => {
const { poolId } = await createPoolAsync();
await addMakerToPoolAsync(poolId, maker);
const tx = testContract.testOnlyStakingPoolOperatorModifier.callAsync(poolId, { from: maker });
const tx = testContract.testOnlyStakingPoolOperatorModifier(poolId).callAsync({ from: maker });
const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(maker, poolId);
return expect(tx).to.revertWith(expectedError);
});
it('succeeds if called by the pool operator', async () => {
const { poolId } = await createPoolAsync();
await testContract.testOnlyStakingPoolOperatorModifier.callAsync(poolId, { from: operator });
await testContract.testOnlyStakingPoolOperatorModifier(poolId).callAsync({ from: operator });
});
});
@@ -91,12 +93,12 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
let nextPoolId: string;
before(async () => {
nextPoolId = toNextPoolId(await testContract.lastPoolId.callAsync());
nextPoolId = toNextPoolId(await testContract.lastPoolId().callAsync());
});
it('fails if the next pool ID overflows', async () => {
await testContract.setLastPoolId.awaitTransactionSuccessAsync(toHex(constants.MAX_UINT256));
const tx = testContract.createStakingPool.awaitTransactionSuccessAsync(randomOperatorShare(), false);
await testContract.setLastPoolId(toHex(constants.MAX_UINT256)).awaitTransactionSuccessAsync();
const tx = testContract.createStakingPool(randomOperatorShare(), false).awaitTransactionSuccessAsync();
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
SafeMathRevertErrors.BinOpErrorCodes.AdditionOverflow,
constants.MAX_UINT256,
@@ -106,7 +108,7 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
});
it('fails if the operator share is invalid', async () => {
const operatorShare = constants.PPM_100_PERCENT + 1;
const tx = testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false);
const tx = testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync();
const expectedError = new StakingRevertErrors.OperatorShareError(
StakingRevertErrors.OperatorShareErrorCodes.OperatorShareTooLarge,
nextPoolId,
@@ -115,14 +117,12 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
return expect(tx).to.revertWith(expectedError);
});
it('operator can create and own multiple pools', async () => {
const { logs: logs1 } = await testContract.createStakingPool.awaitTransactionSuccessAsync(
randomOperatorShare(),
false,
);
const { logs: logs2 } = await testContract.createStakingPool.awaitTransactionSuccessAsync(
randomOperatorShare(),
false,
);
const { logs: logs1 } = await testContract
.createStakingPool(randomOperatorShare(), false)
.awaitTransactionSuccessAsync();
const { logs: logs2 } = await testContract
.createStakingPool(randomOperatorShare(), false)
.awaitTransactionSuccessAsync();
const createEvents = filterLogsToArguments<StakingPoolCreated>(
[...logs1, ...logs2],
TestMixinStakingPoolEvents.StakingPoolCreated,
@@ -130,27 +130,27 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
expect(createEvents).to.be.length(2);
const poolIds = createEvents.map(e => e.poolId);
expect(poolIds[0]).to.not.eq(poolIds[1]);
const pools = await Promise.all(poolIds.map(async poolId => testContract.getStakingPool.callAsync(poolId)));
const pools = await Promise.all(
poolIds.map(async poolId => testContract.getStakingPool(poolId).callAsync()),
);
expect(pools[0].operator).to.eq(pools[1].operator);
});
it('operator can only be maker of one pool', async () => {
await testContract.createStakingPool.awaitTransactionSuccessAsync(randomOperatorShare(), true);
const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync(
randomOperatorShare(),
true,
);
await testContract.createStakingPool(randomOperatorShare(), true).awaitTransactionSuccessAsync();
const { logs } = await testContract
.createStakingPool(randomOperatorShare(), true)
.awaitTransactionSuccessAsync();
const createEvents = filterLogsToArguments<StakingPoolCreated>(
logs,
TestMixinStakingPoolEvents.StakingPoolCreated,
);
const makerPool = await testContract.poolIdByMaker.callAsync(operator);
const makerPool = await testContract.poolIdByMaker(operator).callAsync();
expect(makerPool).to.eq(createEvents[0].poolId);
});
it('computes correct next pool ID', async () => {
const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync(
randomOperatorShare(),
false,
);
const { logs } = await testContract
.createStakingPool(randomOperatorShare(), false)
.awaitTransactionSuccessAsync();
const createEvents = filterLogsToArguments<StakingPoolCreated>(
logs,
TestMixinStakingPoolEvents.StakingPoolCreated,
@@ -159,46 +159,46 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
expect(poolId).to.eq(nextPoolId);
});
it('increments last pool ID counter', async () => {
await testContract.createStakingPool.awaitTransactionSuccessAsync(randomOperatorShare(), false);
const lastPoolIdAfter = await testContract.lastPoolId.callAsync();
await testContract.createStakingPool(randomOperatorShare(), false).awaitTransactionSuccessAsync();
const lastPoolIdAfter = await testContract.lastPoolId().callAsync();
expect(lastPoolIdAfter).to.eq(nextPoolId);
});
it('records pool details', async () => {
const operatorShare = randomOperatorShare();
await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { from: operator });
const pool = await testContract.getStakingPool.callAsync(nextPoolId);
await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator });
const pool = await testContract.getStakingPool(nextPoolId).callAsync();
expect(pool.operator).to.eq(operator);
expect(pool.operatorShare).to.bignumber.eq(operatorShare);
});
it('records pool details when operator share is 100%', async () => {
const operatorShare = constants.PPM_100_PERCENT;
await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { from: operator });
const pool = await testContract.getStakingPool.callAsync(nextPoolId);
await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator });
const pool = await testContract.getStakingPool(nextPoolId).callAsync();
expect(pool.operator).to.eq(operator);
expect(pool.operatorShare).to.bignumber.eq(operatorShare);
});
it('records pool details when operator share is 0%', async () => {
const operatorShare = constants.ZERO_AMOUNT;
await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, { from: operator });
const pool = await testContract.getStakingPool.callAsync(nextPoolId);
await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({ from: operator });
const pool = await testContract.getStakingPool(nextPoolId).callAsync();
expect(pool.operator).to.eq(operator);
expect(pool.operatorShare).to.bignumber.eq(operatorShare);
});
it('returns the next pool ID', async () => {
const poolId = await testContract.createStakingPool.callAsync(randomOperatorShare(), false, {
const poolId = await testContract.createStakingPool(randomOperatorShare(), false).callAsync({
from: operator,
});
expect(poolId).to.eq(nextPoolId);
});
it('can add operator as a maker', async () => {
const operatorShare = randomOperatorShare();
await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, true, { from: operator });
const makerPoolId = await testContract.poolIdByMaker.callAsync(operator);
await testContract.createStakingPool(operatorShare, true).awaitTransactionSuccessAsync({ from: operator });
const makerPoolId = await testContract.poolIdByMaker(operator).callAsync();
expect(makerPoolId).to.eq(nextPoolId);
});
it('emits a `StakingPoolCreated` event', async () => {
const operatorShare = randomOperatorShare();
const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, false, {
const { logs } = await testContract.createStakingPool(operatorShare, false).awaitTransactionSuccessAsync({
from: operator,
});
verifyEventsFromLogs(
@@ -215,7 +215,7 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
});
it('emits a `MakerStakingPoolSet` event when also joining as a maker', async () => {
const operatorShare = randomOperatorShare();
const { logs } = await testContract.createStakingPool.awaitTransactionSuccessAsync(operatorShare, true, {
const { logs } = await testContract.createStakingPool(operatorShare, true).awaitTransactionSuccessAsync({
from: operator,
});
verifyEventsFromLogs(
@@ -234,32 +234,26 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
describe('decreaseStakingPoolOperatorShare()', () => {
it('fails if not called by operator', async () => {
const { poolId, operatorShare } = await createPoolAsync();
const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
operatorShare - 1,
{ from: notOperatorOrMaker },
);
const tx = testContract
.decreaseStakingPoolOperatorShare(poolId, operatorShare - 1)
.awaitTransactionSuccessAsync({ from: notOperatorOrMaker });
const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(notOperatorOrMaker, poolId);
return expect(tx).to.revertWith(expectedError);
});
it('fails if called by maker', async () => {
const { poolId, operatorShare } = await createPoolAsync();
await addMakerToPoolAsync(poolId, maker);
const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
operatorShare - 1,
{ from: maker },
);
const tx = testContract
.decreaseStakingPoolOperatorShare(poolId, operatorShare - 1)
.awaitTransactionSuccessAsync({ from: maker });
const expectedError = new StakingRevertErrors.OnlyCallableByPoolOperatorError(maker, poolId);
return expect(tx).to.revertWith(expectedError);
});
it('fails if operator share is greater than current', async () => {
const { poolId, operatorShare } = await createPoolAsync();
const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
operatorShare + 1,
{ from: operator },
);
const tx = testContract
.decreaseStakingPoolOperatorShare(poolId, operatorShare + 1)
.awaitTransactionSuccessAsync({ from: operator });
const expectedError = new StakingRevertErrors.OperatorShareError(
StakingRevertErrors.OperatorShareErrorCodes.CanOnlyDecreaseOperatorShare,
poolId,
@@ -269,11 +263,9 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
});
it('fails if operator share is greater than PPM_100_PERCENT', async () => {
const { poolId } = await createPoolAsync();
const tx = testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
constants.PPM_100_PERCENT + 1,
{ from: operator },
);
const tx = testContract
.decreaseStakingPoolOperatorShare(poolId, constants.PPM_100_PERCENT + 1)
.awaitTransactionSuccessAsync({ from: operator });
const expectedError = new StakingRevertErrors.OperatorShareError(
StakingRevertErrors.OperatorShareErrorCodes.OperatorShareTooLarge,
poolId,
@@ -283,39 +275,33 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
});
it('records new operator share', async () => {
const { poolId, operatorShare } = await createPoolAsync();
await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
operatorShare - 1,
{ from: operator },
);
const pool = await testContract.getStakingPool.callAsync(poolId);
await testContract
.decreaseStakingPoolOperatorShare(poolId, operatorShare - 1)
.awaitTransactionSuccessAsync({ from: operator });
const pool = await testContract.getStakingPool(poolId).callAsync();
expect(pool.operatorShare).to.bignumber.eq(operatorShare - 1);
});
it('does not modify operator share if equal to current', async () => {
const { poolId, operatorShare } = await createPoolAsync();
await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(poolId, operatorShare, {
await testContract.decreaseStakingPoolOperatorShare(poolId, operatorShare).awaitTransactionSuccessAsync({
from: operator,
});
const pool = await testContract.getStakingPool.callAsync(poolId);
const pool = await testContract.getStakingPool(poolId).callAsync();
expect(pool.operatorShare).to.bignumber.eq(operatorShare);
});
it('does not modify operator', async () => {
const { poolId, operatorShare } = await createPoolAsync();
await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
operatorShare - 1,
{ from: operator },
);
const pool = await testContract.getStakingPool.callAsync(poolId);
await testContract
.decreaseStakingPoolOperatorShare(poolId, operatorShare - 1)
.awaitTransactionSuccessAsync({ from: operator });
const pool = await testContract.getStakingPool(poolId).callAsync();
expect(pool.operator).to.eq(operator);
});
it('emits an `OperatorShareDecreased` event', async () => {
const { poolId, operatorShare } = await createPoolAsync();
const { logs } = await testContract.decreaseStakingPoolOperatorShare.awaitTransactionSuccessAsync(
poolId,
operatorShare - 1,
{ from: operator },
);
const { logs } = await testContract
.decreaseStakingPoolOperatorShare(poolId, operatorShare - 1)
.awaitTransactionSuccessAsync({ from: operator });
verifyEventsFromLogs(
logs,
[
@@ -333,36 +319,36 @@ blockchainTests.resets('MixinStakingPool unit tests', env => {
describe('joinStakingPoolAsMaker()', () => {
it('records sender as maker for the pool', async () => {
const { poolId } = await createPoolAsync();
await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: maker });
const makerPoolId = await testContract.poolIdByMaker.callAsync(maker);
await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker });
const makerPoolId = await testContract.poolIdByMaker(maker).callAsync();
expect(makerPoolId).to.eq(poolId);
});
it('operator can join as maker for the pool', async () => {
const { poolId } = await createPoolAsync();
await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: operator });
const makerPoolId = await testContract.poolIdByMaker.callAsync(operator);
await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: operator });
const makerPoolId = await testContract.poolIdByMaker(operator).callAsync();
expect(makerPoolId).to.eq(poolId);
});
it('can join the same pool as a maker twice', async () => {
const { poolId } = await createPoolAsync();
await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: maker });
await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, { from: maker });
const makerPoolId = await testContract.poolIdByMaker.callAsync(maker);
await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker });
await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({ from: maker });
const makerPoolId = await testContract.poolIdByMaker(maker).callAsync();
expect(makerPoolId).to.eq(poolId);
});
it('can only be a maker in one pool at a time', async () => {
const { poolId: poolId1 } = await createPoolAsync();
const { poolId: poolId2 } = await createPoolAsync();
await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId1, { from: maker });
let makerPoolId = await testContract.poolIdByMaker.callAsync(maker);
await testContract.joinStakingPoolAsMaker(poolId1).awaitTransactionSuccessAsync({ from: maker });
let makerPoolId = await testContract.poolIdByMaker(maker).callAsync();
expect(makerPoolId).to.eq(poolId1);
await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId2, { from: maker });
makerPoolId = await testContract.poolIdByMaker.callAsync(maker);
await testContract.joinStakingPoolAsMaker(poolId2).awaitTransactionSuccessAsync({ from: maker });
makerPoolId = await testContract.poolIdByMaker(maker).callAsync();
expect(makerPoolId).to.eq(poolId2);
});
it('emits a `MakerStakingPoolSet` event', async () => {
const { poolId } = await createPoolAsync();
const { logs } = await testContract.joinStakingPoolAsMaker.awaitTransactionSuccessAsync(poolId, {
const { logs } = await testContract.joinStakingPoolAsMaker(poolId).awaitTransactionSuccessAsync({
from: maker,
});
verifyEventsFromLogs(

View File

@@ -59,23 +59,23 @@ blockchainTests.resets('StakingProxy unit tests', env => {
);
// Add authorized address to Staking Proxy
await testProxyContract.addAuthorizedAddress.sendTransactionAsync(authorizedAddress, { from: owner });
await testProxyContract.addAuthorizedAddress(authorizedAddress).sendTransactionAsync({ from: owner });
});
describe('Fallback function', () => {
it('should pass back the return value of the destination contract', async () => {
const returnValue = await testContractViaProxy.echo.callAsync(testString);
const returnValue = await testContractViaProxy.echo(testString).callAsync();
expect(returnValue).to.equal(testString);
});
it('should revert with correct value when destination reverts', async () => {
return expect(testContractViaProxy.die.callAsync()).to.revertWith(testRevertString);
return expect(testContractViaProxy.die().callAsync()).to.revertWith(testRevertString);
});
it('should revert if no staking contract is attached', async () => {
await testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({ from: authorizedAddress });
await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress });
const expectedError = new StakingRevertErrors.ProxyDestinationCannotBeNilError();
const tx = testContractViaProxy.echo.callAsync(testString);
const tx = testContractViaProxy.echo(testString).callAsync();
return expect(tx).to.revertWith(expectedError);
});
});
@@ -83,11 +83,10 @@ blockchainTests.resets('StakingProxy unit tests', env => {
describe('attachStakingContract', () => {
it('should successfully attaching a new staking contract', async () => {
// Cache existing staking contract and attach a new one
const initStakingContractAddress = await testProxyContract.stakingContract.callAsync();
const txReceipt = await testProxyContract.attachStakingContract.awaitTransactionSuccessAsync(
testContract2.address,
{ from: authorizedAddress },
);
const initStakingContractAddress = await testProxyContract.stakingContract().callAsync();
const txReceipt = await testProxyContract
.attachStakingContract(testContract2.address)
.awaitTransactionSuccessAsync({ from: authorizedAddress });
// Validate `ContractAttachedToProxy` event
verifyEventsFromLogs(
@@ -112,14 +111,14 @@ blockchainTests.resets('StakingProxy unit tests', env => {
);
// Validate new staking contract address
const finalStakingContractAddress = await testProxyContract.stakingContract.callAsync();
const finalStakingContractAddress = await testProxyContract.stakingContract().callAsync();
expect(finalStakingContractAddress).to.be.equal(testContract2.address);
expect(finalStakingContractAddress).to.not.equal(initStakingContractAddress);
});
it('should revert if call to `init` on new staking contract fails', async () => {
await testProxyContract.setInitFailFlag.awaitTransactionSuccessAsync();
const tx = testProxyContract.attachStakingContract.awaitTransactionSuccessAsync(testContract2.address, {
await testProxyContract.setInitFailFlag().awaitTransactionSuccessAsync();
const tx = testProxyContract.attachStakingContract(testContract2.address).awaitTransactionSuccessAsync({
from: authorizedAddress,
});
const expectedError = 'INIT_FAIL_FLAG_SET';
@@ -127,7 +126,7 @@ blockchainTests.resets('StakingProxy unit tests', env => {
});
it('should revert if called by unauthorized address', async () => {
const tx = testProxyContract.attachStakingContract.awaitTransactionSuccessAsync(testContract2.address, {
const tx = testProxyContract.attachStakingContract(testContract2.address).awaitTransactionSuccessAsync({
from: notAuthorizedAddresses[0],
});
const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddresses[0]);
@@ -138,8 +137,8 @@ blockchainTests.resets('StakingProxy unit tests', env => {
describe('detachStakingContract', () => {
it('should detach staking contract', async () => {
// Cache existing staking contract and attach a new one
const initStakingContractAddress = await testProxyContract.stakingContract.callAsync();
const txReceipt = await testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({
const initStakingContractAddress = await testProxyContract.stakingContract().callAsync();
const txReceipt = await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({
from: authorizedAddress,
});
@@ -147,13 +146,13 @@ blockchainTests.resets('StakingProxy unit tests', env => {
verifyEventsFromLogs(txReceipt.logs, [{}], StakingProxyEvents.StakingContractDetachedFromProxy);
// Validate staking contract address was unset
const finalStakingContractAddress = await testProxyContract.stakingContract.callAsync();
const finalStakingContractAddress = await testProxyContract.stakingContract().callAsync();
expect(finalStakingContractAddress).to.be.equal(stakingConstants.NIL_ADDRESS);
expect(finalStakingContractAddress).to.not.equal(initStakingContractAddress);
});
it('should revert if called by unauthorized address', async () => {
const tx = testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({
const tx = testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({
from: notAuthorizedAddresses[0],
});
const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorizedAddresses[0]);
@@ -163,27 +162,27 @@ blockchainTests.resets('StakingProxy unit tests', env => {
describe('batchExecute', () => {
it('should execute no-op if no calls to make', async () => {
await testProxyContract.batchExecute.awaitTransactionSuccessAsync([]);
await testProxyContract.batchExecute([]).awaitTransactionSuccessAsync();
});
it('should call one function and return the output', async () => {
const calls = [testContract.echo.getABIEncodedTransactionData(testString)];
const rawResults = await testProxyContract.batchExecute.callAsync(calls);
const calls = [testContract.echo(testString).getABIEncodedTransactionData()];
const rawResults = await testProxyContract.batchExecute(calls).callAsync();
expect(rawResults.length).to.equal(1);
const returnValues = [testContract.echo.getABIDecodedReturnData(rawResults[0])];
const returnValues = [testContract.getABIDecodedReturnData<{}>('echo', rawResults[0])];
expect(returnValues[0]).to.equal(testString);
});
it('should call multiple functions and return their outputs', async () => {
const calls = [
testContract.echo.getABIEncodedTransactionData(testString),
testContract.doMath.getABIEncodedTransactionData(new BigNumber(2), new BigNumber(1)),
testContract.echo(testString).getABIEncodedTransactionData(),
testContract.doMath(new BigNumber(2), new BigNumber(1)).getABIEncodedTransactionData(),
];
const rawResults = await testProxyContract.batchExecute.callAsync(calls);
const rawResults = await testProxyContract.batchExecute(calls).callAsync();
expect(rawResults.length).to.equal(2);
const returnValues = [
testContract.echo.getABIDecodedReturnData(rawResults[0]),
testContract.doMath.getABIDecodedReturnData(rawResults[1]),
testContract.getABIDecodedReturnData<string>('echo', rawResults[0]),
testContract.getABIDecodedReturnData<BigNumber[]>('doMath', rawResults[1]),
];
expect(returnValues[0]).to.equal(testString);
expect(returnValues[1][0]).to.bignumber.equal(new BigNumber(3));
@@ -192,20 +191,20 @@ blockchainTests.resets('StakingProxy unit tests', env => {
it('should revert if a call reverts', async () => {
const calls = [
testContract.echo.getABIEncodedTransactionData(testString),
testContract.die.getABIEncodedTransactionData(),
testContract.doMath.getABIEncodedTransactionData(new BigNumber(2), new BigNumber(1)),
testContract.echo(testString).getABIEncodedTransactionData(),
testContract.die().getABIEncodedTransactionData(),
testContract.doMath(new BigNumber(2), new BigNumber(1)).getABIEncodedTransactionData(),
];
const tx = testProxyContract.batchExecute.callAsync(calls);
const tx = testProxyContract.batchExecute(calls).callAsync();
const expectedError = testRevertString;
return expect(tx).to.revertWith(expectedError);
});
it('should revert if no staking contract is attached', async () => {
await testProxyContract.detachStakingContract.awaitTransactionSuccessAsync({ from: authorizedAddress });
const calls = [testContract.echo.getABIEncodedTransactionData(testString)];
await testProxyContract.detachStakingContract().awaitTransactionSuccessAsync({ from: authorizedAddress });
const calls = [testContract.echo(testString).getABIEncodedTransactionData()];
const tx = testProxyContract.batchExecute.callAsync(calls);
const tx = testProxyContract.batchExecute(calls).callAsync();
const expectedError = new StakingRevertErrors.ProxyDestinationCannotBeNilError();
return expect(tx).to.revertWith(expectedError);
});
@@ -220,16 +219,16 @@ blockchainTests.resets('StakingProxy unit tests', env => {
minimumPoolStake: new BigNumber(100),
};
it('should not revert if all storage params are valid', async () => {
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(validStorageParams);
await testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(validStorageParams).awaitTransactionSuccessAsync();
await testProxyContract.assertValidStorageParams().callAsync();
});
it('should revert if `epochDurationInSeconds` is less than 5 days', async () => {
const invalidStorageParams = {
...validStorageParams,
epochDurationInSeconds: new BigNumber(0),
};
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams);
const tx = testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync();
const tx = testProxyContract.assertValidStorageParams().callAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration,
);
@@ -240,8 +239,8 @@ blockchainTests.resets('StakingProxy unit tests', env => {
...validStorageParams,
epochDurationInSeconds: new BigNumber(stakingConstants.ONE_DAY_IN_SECONDS * 31),
};
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams);
const tx = testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync();
const tx = testProxyContract.assertValidStorageParams().callAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidEpochDuration,
);
@@ -253,8 +252,8 @@ blockchainTests.resets('StakingProxy unit tests', env => {
cobbDouglasAlphaNumerator: new BigNumber(2),
cobbDouglasAlphaDenominator: new BigNumber(1),
};
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams);
const tx = testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync();
const tx = testProxyContract.assertValidStorageParams().callAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha,
);
@@ -265,8 +264,8 @@ blockchainTests.resets('StakingProxy unit tests', env => {
...validStorageParams,
cobbDouglasAlphaDenominator: new BigNumber(0),
};
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams);
const tx = testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync();
const tx = testProxyContract.assertValidStorageParams().callAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidCobbDouglasAlpha,
);
@@ -277,8 +276,8 @@ blockchainTests.resets('StakingProxy unit tests', env => {
...validStorageParams,
rewardDelegatedStakeWeight: new BigNumber(constants.PPM_DENOMINATOR + 1),
};
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams);
const tx = testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync();
const tx = testProxyContract.assertValidStorageParams().callAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidRewardDelegatedStakeWeight,
);
@@ -289,8 +288,8 @@ blockchainTests.resets('StakingProxy unit tests', env => {
...validStorageParams,
minimumPoolStake: new BigNumber(1),
};
await testProxyContract.setTestStorageParams.awaitTransactionSuccessAsync(invalidStorageParams);
const tx = testProxyContract.assertValidStorageParams.callAsync();
await testProxyContract.setTestStorageParams(invalidStorageParams).awaitTransactionSuccessAsync();
const tx = testProxyContract.assertValidStorageParams().callAsync();
const expectedError = new StakingRevertErrors.InvalidParamValueError(
StakingRevertErrors.InvalidParamValueErrorCodes.InvalidMinimumPoolStake,
);

View File

@@ -48,7 +48,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
zrxProxyAddress = erc20ProxyContract.address;
// deploy zrx token
const [zrxTokenContract] = await erc20Wrapper.deployDummyTokensAsync(1, constants.DUMMY_TOKEN_DECIMALS);
zrxAssetData = await devUtils.encodeERC20AssetData.callAsync(zrxTokenContract.address);
zrxAssetData = await devUtils.encodeERC20AssetData(zrxTokenContract.address).callAsync();
await erc20Wrapper.setBalancesAndAllowancesAsync();
@@ -61,10 +61,10 @@ blockchainTests.resets('ZrxVault unit tests', env => {
zrxTokenContract.address,
);
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(owner);
await zrxVault.addAuthorizedAddress(owner).awaitTransactionSuccessAsync();
// configure erc20 proxy to accept calls from zrx vault
await erc20ProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(zrxVault.address);
await erc20ProxyContract.addAuthorizedAddress(zrxVault.address).awaitTransactionSuccessAsync();
});
enum ZrxTransfer {
@@ -88,7 +88,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
expect(eventArgs[0].staker).to.equal(staker);
expect(eventArgs[0].amount).to.bignumber.equal(amount);
const newVaultBalance = await zrxVault.balanceOf.callAsync(staker);
const newVaultBalance = await zrxVault.balanceOf(staker).callAsync();
const newTokenBalance = await erc20Wrapper.getBalanceAsync(staker, zrxAssetData);
const [expectedVaultBalance, expectedTokenBalance] =
transferType === ZrxTransfer.Deposit
@@ -110,13 +110,13 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
expect(eventArgs.length).to.equal(1);
expect(eventArgs[0].stakingProxyAddress).to.equal(newProxy);
const actualAddress = await zrxVault.stakingProxyAddress.callAsync();
const actualAddress = await zrxVault.stakingProxyAddress().callAsync();
expect(actualAddress).to.equal(newProxy);
}
it('Owner can set the ZRX proxy', async () => {
const newProxy = nonOwnerAddresses[0];
const receipt = await zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, {
const receipt = await zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({
from: owner,
});
const eventArgs = filterLogsToArguments<ZrxVaultZrxProxySetEventArgs>(receipt.logs, 'ZrxProxySet');
@@ -125,8 +125,8 @@ blockchainTests.resets('ZrxVault unit tests', env => {
});
it('Authorized address can set the ZRX proxy', async () => {
const [authorized, newProxy] = nonOwnerAddresses;
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner });
const receipt = await zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, {
await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
const receipt = await zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({
from: authorized,
});
const eventArgs = filterLogsToArguments<ZrxVaultZrxProxySetEventArgs>(receipt.logs, 'ZrxProxySet');
@@ -135,7 +135,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
});
it('Non-authorized address cannot set the ZRX proxy', async () => {
const [notAuthorized, newProxy] = nonOwnerAddresses;
const tx = zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, {
const tx = zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({
from: notAuthorized,
});
const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorized);
@@ -143,27 +143,27 @@ blockchainTests.resets('ZrxVault unit tests', env => {
});
it('Owner can set the staking proxy', async () => {
const newProxy = nonOwnerAddresses[0];
const receipt = await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(newProxy, {
const receipt = await zrxVault.setStakingProxy(newProxy).awaitTransactionSuccessAsync({
from: owner,
});
await verifyStakingProxySetAsync(receipt, newProxy);
});
it('Authorized address can set the staking proxy', async () => {
const [authorized, newProxy] = nonOwnerAddresses;
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner });
const receipt = await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(newProxy, {
await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
const receipt = await zrxVault.setStakingProxy(newProxy).awaitTransactionSuccessAsync({
from: authorized,
});
await verifyStakingProxySetAsync(receipt, newProxy);
});
it('Non-authorized address cannot set the staking proxy', async () => {
const [notAuthorized, newProxy] = nonOwnerAddresses;
const tx = zrxVault.setStakingProxy.awaitTransactionSuccessAsync(newProxy, {
const tx = zrxVault.setStakingProxy(newProxy).awaitTransactionSuccessAsync({
from: notAuthorized,
});
const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorized);
expect(tx).to.revertWith(expectedError);
const actualAddress = await zrxVault.stakingProxyAddress.callAsync();
const actualAddress = await zrxVault.stakingProxyAddress().callAsync();
expect(actualAddress).to.equal(stakingConstants.NIL_ADDRESS);
});
});
@@ -175,26 +175,24 @@ blockchainTests.resets('ZrxVault unit tests', env => {
before(async () => {
[staker, stakingProxy] = nonOwnerAddresses;
await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy, { from: owner });
await zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(10), {
await zrxVault.setStakingProxy(stakingProxy).awaitTransactionSuccessAsync({ from: owner });
await zrxVault.depositFrom(staker, new BigNumber(10)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
});
beforeEach(async () => {
initialVaultBalance = await zrxVault.balanceOf.callAsync(staker);
initialVaultBalance = await zrxVault.balanceOf(staker).callAsync();
initialTokenBalance = await erc20Wrapper.getBalanceAsync(staker, zrxAssetData);
});
describe('Deposit', () => {
it('Staking proxy can deposit zero amount on behalf of staker', async () => {
const receipt = await zrxVault.depositFrom.awaitTransactionSuccessAsync(
staker,
constants.ZERO_AMOUNT,
{
const receipt = await zrxVault
.depositFrom(staker, constants.ZERO_AMOUNT)
.awaitTransactionSuccessAsync({
from: stakingProxy,
},
);
});
await verifyTransferPostconditionsAsync(
ZrxTransfer.Deposit,
staker,
@@ -205,7 +203,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it('Staking proxy can deposit nonzero amount on behalf of staker', async () => {
const receipt = await zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), {
const receipt = await zrxVault.depositFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
await verifyTransferPostconditionsAsync(
@@ -218,13 +216,11 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it('Staking proxy can deposit entire ZRX balance on behalf of staker', async () => {
const receipt = await zrxVault.depositFrom.awaitTransactionSuccessAsync(
staker,
initialTokenBalance,
{
const receipt = await zrxVault
.depositFrom(staker, initialTokenBalance)
.awaitTransactionSuccessAsync({
from: stakingProxy,
},
);
});
await verifyTransferPostconditionsAsync(
ZrxTransfer.Deposit,
staker,
@@ -235,7 +231,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it("Reverts if attempting to deposit more than staker's ZRX balance", async () => {
const tx = zrxVault.depositFrom.sendTransactionAsync(staker, initialTokenBalance.plus(1), {
const tx = zrxVault.depositFrom(staker, initialTokenBalance.plus(1)).sendTransactionAsync({
from: stakingProxy,
});
expectTransactionFailedAsync(tx, RevertReason.TransferFailed);
@@ -243,13 +239,11 @@ blockchainTests.resets('ZrxVault unit tests', env => {
});
describe('Withdrawal', () => {
it('Staking proxy can withdraw zero amount on behalf of staker', async () => {
const receipt = await zrxVault.withdrawFrom.awaitTransactionSuccessAsync(
staker,
constants.ZERO_AMOUNT,
{
const receipt = await zrxVault
.withdrawFrom(staker, constants.ZERO_AMOUNT)
.awaitTransactionSuccessAsync({
from: stakingProxy,
},
);
});
await verifyTransferPostconditionsAsync(
ZrxTransfer.Withdrawal,
staker,
@@ -260,7 +254,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it('Staking proxy can withdraw nonzero amount on behalf of staker', async () => {
const receipt = await zrxVault.withdrawFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), {
const receipt = await zrxVault.withdrawFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
await verifyTransferPostconditionsAsync(
@@ -273,13 +267,11 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it('Staking proxy can withdraw entire vault balance on behalf of staker', async () => {
const receipt = await zrxVault.withdrawFrom.awaitTransactionSuccessAsync(
staker,
initialVaultBalance,
{
const receipt = await zrxVault
.withdrawFrom(staker, initialVaultBalance)
.awaitTransactionSuccessAsync({
from: stakingProxy,
},
);
});
await verifyTransferPostconditionsAsync(
ZrxTransfer.Withdrawal,
staker,
@@ -290,7 +282,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it("Reverts if attempting to withdraw more than staker's vault balance", async () => {
const tx = zrxVault.withdrawFrom.awaitTransactionSuccessAsync(staker, initialVaultBalance.plus(1), {
const tx = zrxVault.withdrawFrom(staker, initialVaultBalance.plus(1)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
const expectedError = new SafeMathRevertErrors.Uint256BinOpError(
@@ -316,38 +308,38 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
expect(eventArgs.length).to.equal(1);
expect(eventArgs[0].sender).to.equal(sender);
expect(await zrxVault.isInCatastrophicFailure.callAsync()).to.be.true();
expect(await zrxVault.isInCatastrophicFailure().callAsync()).to.be.true();
}
it('Owner can turn on Catastrophic Failure Mode', async () => {
const receipt = await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ from: owner });
const receipt = await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: owner });
await verifyCatastrophicFailureModeAsync(owner, receipt);
});
it('Authorized address can turn on Catastrophic Failure Mode', async () => {
const authorized = nonOwnerAddresses[0];
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner });
const receipt = await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({
await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
const receipt = await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({
from: authorized,
});
await verifyCatastrophicFailureModeAsync(authorized, receipt);
});
it('Non-authorized address cannot turn on Catastrophic Failure Mode', async () => {
const notAuthorized = nonOwnerAddresses[0];
const tx = zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({
const tx = zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({
from: notAuthorized,
});
const expectedError = new AuthorizableRevertErrors.SenderNotAuthorizedError(notAuthorized);
expect(tx).to.revertWith(expectedError);
expect(await zrxVault.isInCatastrophicFailure.callAsync()).to.be.false();
expect(await zrxVault.isInCatastrophicFailure().callAsync()).to.be.false();
});
it('Catastrophic Failure Mode can only be turned on once', async () => {
const authorized = nonOwnerAddresses[0];
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner });
await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({
await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({
from: authorized,
});
const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError();
return expect(zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync()).to.revertWith(
return expect(zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync()).to.revertWith(
expectedError,
);
});
@@ -361,41 +353,41 @@ blockchainTests.resets('ZrxVault unit tests', env => {
before(async () => {
[staker, stakingProxy, ...nonOwnerAddresses] = nonOwnerAddresses;
await zrxVault.setStakingProxy.awaitTransactionSuccessAsync(stakingProxy, { from: owner });
await zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(10), {
await zrxVault.setStakingProxy(stakingProxy).awaitTransactionSuccessAsync({ from: owner });
await zrxVault.depositFrom(staker, new BigNumber(10)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
await zrxVault.enterCatastrophicFailure.awaitTransactionSuccessAsync({ from: owner });
await zrxVault.enterCatastrophicFailure().awaitTransactionSuccessAsync({ from: owner });
});
beforeEach(async () => {
initialVaultBalance = await zrxVault.balanceOf.callAsync(staker);
initialVaultBalance = await zrxVault.balanceOf(staker).callAsync();
initialTokenBalance = await erc20Wrapper.getBalanceAsync(staker, zrxAssetData);
});
it('Owner cannot set the ZRX proxy', async () => {
const newProxy = nonOwnerAddresses[0];
const tx = zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, {
const tx = zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({
from: owner,
});
const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError();
expect(tx).to.revertWith(expectedError);
const actualAddress = await zrxVault.zrxAssetProxy.callAsync();
const actualAddress = await zrxVault.zrxAssetProxy().callAsync();
expect(actualAddress).to.equal(zrxProxyAddress);
});
it('Authorized address cannot set the ZRX proxy', async () => {
const [authorized, newProxy] = nonOwnerAddresses;
await zrxVault.addAuthorizedAddress.awaitTransactionSuccessAsync(authorized, { from: owner });
const tx = zrxVault.setZrxProxy.awaitTransactionSuccessAsync(newProxy, {
await zrxVault.addAuthorizedAddress(authorized).awaitTransactionSuccessAsync({ from: owner });
const tx = zrxVault.setZrxProxy(newProxy).awaitTransactionSuccessAsync({
from: authorized,
});
const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError();
expect(tx).to.revertWith(expectedError);
const actualAddress = await zrxVault.zrxAssetProxy.callAsync();
const actualAddress = await zrxVault.zrxAssetProxy().callAsync();
expect(actualAddress).to.equal(zrxProxyAddress);
});
it('Staking proxy cannot deposit ZRX', async () => {
const tx = zrxVault.depositFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), {
const tx = zrxVault.depositFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError();
@@ -404,14 +396,14 @@ blockchainTests.resets('ZrxVault unit tests', env => {
describe('Withdrawal', () => {
it('Staking proxy cannot call `withdrawFrom`', async () => {
const tx = zrxVault.withdrawFrom.awaitTransactionSuccessAsync(staker, new BigNumber(1), {
const tx = zrxVault.withdrawFrom(staker, new BigNumber(1)).awaitTransactionSuccessAsync({
from: stakingProxy,
});
const expectedError = new StakingRevertErrors.OnlyCallableIfNotInCatastrophicFailureError();
expect(tx).to.revertWith(expectedError);
});
it('Staker can withdraw all their ZRX', async () => {
const receipt = await zrxVault.withdrawAllFrom.awaitTransactionSuccessAsync(staker, {
const receipt = await zrxVault.withdrawAllFrom(staker).awaitTransactionSuccessAsync({
from: staker,
});
await verifyTransferPostconditionsAsync(
@@ -424,7 +416,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it('Owner can withdraw ZRX on behalf of a staker', async () => {
const receipt = await zrxVault.withdrawAllFrom.awaitTransactionSuccessAsync(staker, {
const receipt = await zrxVault.withdrawAllFrom(staker).awaitTransactionSuccessAsync({
from: owner,
});
await verifyTransferPostconditionsAsync(
@@ -437,7 +429,7 @@ blockchainTests.resets('ZrxVault unit tests', env => {
);
});
it('Non-owner address can withdraw ZRX on behalf of a staker', async () => {
const receipt = await zrxVault.withdrawAllFrom.awaitTransactionSuccessAsync(staker, {
const receipt = await zrxVault.withdrawAllFrom(staker).awaitTransactionSuccessAsync({
from: nonOwnerAddresses[0],
});
await verifyTransferPostconditionsAsync(

View File

@@ -36,7 +36,7 @@ export class StakingApiWrapper {
fastForwardToNextEpochAsync: async (): Promise<void> => {
// increase timestamp of next block by how many seconds we need to
// get to the next epoch.
const epochEndTime = await this.stakingContract.getCurrentEpochEarliestEndTimeInSeconds.callAsync();
const epochEndTime = await this.stakingContract.getCurrentEpochEarliestEndTimeInSeconds().callAsync();
const lastBlockTime = await this._web3Wrapper.getBlockTimestampAsync('latest');
const dt = Math.max(0, epochEndTime.minus(lastBlockTime).toNumber());
await this._web3Wrapper.increaseTimeAsync(dt);
@@ -49,7 +49,7 @@ export class StakingApiWrapper {
const endOfEpochInfo = await this.utils.endEpochAsync();
const allLogs = [] as DecodedLogs;
for (const poolId of endOfEpochInfo.activePoolIds) {
const receipt = await this.stakingContract.finalizePool.awaitTransactionSuccessAsync(poolId);
const receipt = await this.stakingContract.finalizePool(poolId).awaitTransactionSuccessAsync();
allLogs.splice(allLogs.length, 0, ...(receipt.logs as DecodedLogs));
}
return allLogs;
@@ -57,7 +57,7 @@ export class StakingApiWrapper {
endEpochAsync: async (): Promise<EndOfEpochInfo> => {
const activePoolIds = await this.utils.findActivePoolIdsAsync();
const receipt = await this.stakingContract.endEpoch.awaitTransactionSuccessAsync();
const receipt = await this.stakingContract.endEpoch().awaitTransactionSuccessAsync();
const [epochEndedEvent] = filterLogsToArguments<IStakingEventsEpochEndedEventArgs>(
receipt.logs,
TestStakingEvents.EpochEnded,
@@ -72,7 +72,7 @@ export class StakingApiWrapper {
},
findActivePoolIdsAsync: async (epoch?: number): Promise<string[]> => {
const _epoch = epoch !== undefined ? epoch : await this.stakingContract.currentEpoch.callAsync();
const _epoch = epoch !== undefined ? epoch : await this.stakingContract.currentEpoch().callAsync();
const events = filterLogsToArguments<IStakingEventsStakingPoolEarnedRewardsInEpochEventArgs>(
await this.stakingContract.getLogsAsync(
TestStakingEvents.StakingPoolEarnedRewardsInEpoch,
@@ -90,18 +90,16 @@ export class StakingApiWrapper {
operatorShare: number,
addOperatorAsMaker: boolean,
): Promise<string> => {
const txReceipt = await this.stakingContract.createStakingPool.awaitTransactionSuccessAsync(
operatorShare,
addOperatorAsMaker,
{ from: operatorAddress },
);
const txReceipt = await this.stakingContract
.createStakingPool(operatorShare, addOperatorAsMaker)
.awaitTransactionSuccessAsync({ from: operatorAddress });
const createStakingPoolLog = txReceipt.logs[0];
const poolId = (createStakingPoolLog as any).args.poolId;
return poolId;
},
getZrxTokenBalanceOfZrxVaultAsync: async (): Promise<BigNumber> => {
return this.zrxTokenContract.balanceOf.callAsync(this.zrxVaultContract.address);
return this.zrxTokenContract.balanceOf(this.zrxVaultContract.address).callAsync();
},
setParamsAsync: async (params: Partial<StakingParams>): Promise<TransactionReceiptWithDecodedLogs> => {
@@ -109,20 +107,22 @@ export class StakingApiWrapper {
...stakingConstants.DEFAULT_PARAMS,
...params,
};
return this.stakingContract.setParams.awaitTransactionSuccessAsync(
new BigNumber(_params.epochDurationInSeconds),
new BigNumber(_params.rewardDelegatedStakeWeight),
new BigNumber(_params.minimumPoolStake),
new BigNumber(_params.cobbDouglasAlphaNumerator),
new BigNumber(_params.cobbDouglasAlphaDenominator),
);
return this.stakingContract
.setParams(
new BigNumber(_params.epochDurationInSeconds),
new BigNumber(_params.rewardDelegatedStakeWeight),
new BigNumber(_params.minimumPoolStake),
new BigNumber(_params.cobbDouglasAlphaNumerator),
new BigNumber(_params.cobbDouglasAlphaDenominator),
)
.awaitTransactionSuccessAsync();
},
getAvailableRewardsBalanceAsync: async (): Promise<BigNumber> => {
const [ethBalance, wethBalance, reservedRewards] = await Promise.all([
this._web3Wrapper.getBalanceInWeiAsync(this.stakingProxyContract.address),
this.wethContract.balanceOf.callAsync(this.stakingProxyContract.address),
this.stakingContract.wethReservedForPoolRewards.callAsync(),
this.wethContract.balanceOf(this.stakingProxyContract.address).callAsync(),
this.stakingContract.wethReservedForPoolRewards().callAsync(),
]);
return BigNumber.sum(ethBalance, wethBalance).minus(reservedRewards);
},
@@ -138,7 +138,7 @@ export class StakingApiWrapper {
'wethProxyAddress',
'zrxVaultAddress',
],
await this.stakingContract.getParams.callAsync(),
await this.stakingContract.getParams().callAsync(),
) as any) as StakingParams;
},
@@ -150,15 +150,17 @@ export class StakingApiWrapper {
totalStake: BigNumber,
): Promise<BigNumber> => {
const { cobbDouglasAlphaNumerator, cobbDouglasAlphaDenominator } = await this.utils.getParamsAsync();
return this.cobbDouglasContract.cobbDouglas.callAsync(
totalRewards,
ownerFees,
totalFees,
ownerStake,
totalStake,
new BigNumber(cobbDouglasAlphaNumerator),
new BigNumber(cobbDouglasAlphaDenominator),
);
return this.cobbDouglasContract
.cobbDouglas(
totalRewards,
ownerFees,
totalFees,
ownerStake,
totalStake,
new BigNumber(cobbDouglasAlphaNumerator),
new BigNumber(cobbDouglasAlphaDenominator),
)
.callAsync();
},
};
@@ -232,7 +234,7 @@ export async function deployAndConfigureContractsAsync(
zrxTokenContract.address,
);
await zrxVaultContract.addAuthorizedAddress.awaitTransactionSuccessAsync(ownerAddress);
await zrxVaultContract.addAuthorizedAddress(ownerAddress).awaitTransactionSuccessAsync();
// deploy staking contract
const stakingContract = await TestStakingContract.deployFrom0xArtifactAsync(
@@ -253,7 +255,7 @@ export async function deployAndConfigureContractsAsync(
stakingContract.address,
);
await stakingProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(ownerAddress);
await stakingProxyContract.addAuthorizedAddress(ownerAddress).awaitTransactionSuccessAsync();
// deploy cobb douglas contract
const cobbDouglasContract = await TestCobbDouglasContract.deployFrom0xArtifactAsync(
@@ -264,9 +266,9 @@ export async function deployAndConfigureContractsAsync(
);
// configure erc20 proxy to accept calls from zrx vault
await erc20ProxyContract.addAuthorizedAddress.awaitTransactionSuccessAsync(zrxVaultContract.address);
await erc20ProxyContract.addAuthorizedAddress(zrxVaultContract.address).awaitTransactionSuccessAsync();
// set staking proxy contract in zrx vault
await zrxVaultContract.setStakingProxy.awaitTransactionSuccessAsync(stakingProxyContract.address);
await zrxVaultContract.setStakingProxy(stakingProxyContract.address).awaitTransactionSuccessAsync();
return new StakingApiWrapper(
env,
ownerAddress,

View File

@@ -74,9 +74,9 @@ export class CumulativeRewardTrackingSimulation {
public async deployAndConfigureTestContractsAsync(env: BlockchainTestsEnvironment): Promise<void> {
// set exchange address
await this._stakingApiWrapper.stakingContract.addExchangeAddress.awaitTransactionSuccessAsync(
this._exchangeAddress,
);
await this._stakingApiWrapper.stakingContract
.addExchangeAddress(this._exchangeAddress)
.awaitTransactionSuccessAsync();
this._testCumulativeRewardTrackingContract = await TestCumulativeRewardTrackingContract.deployFrom0xArtifactAsync(
artifacts.TestCumulativeRewardTracking,
env.provider,
@@ -100,9 +100,9 @@ export class CumulativeRewardTrackingSimulation {
expectedTestLogs: TestLog[],
): Promise<void> {
await this._executeActionsAsync(initActions);
await this._stakingApiWrapper.stakingProxyContract.attachStakingContract.awaitTransactionSuccessAsync(
this.getTestCumulativeRewardTrackingContract().address,
);
await this._stakingApiWrapper.stakingProxyContract
.attachStakingContract(this.getTestCumulativeRewardTrackingContract().address)
.awaitTransactionSuccessAsync();
const testLogs = await this._executeActionsAsync(testActions);
CumulativeRewardTrackingSimulation._assertTestLogs(expectedTestLogs, testLogs);
}
@@ -118,41 +118,38 @@ export class CumulativeRewardTrackingSimulation {
break;
case TestAction.Delegate:
await this._stakingApiWrapper.stakingContract.stake.sendTransactionAsync(this._amountToStake, {
await this._stakingApiWrapper.stakingContract.stake(this._amountToStake).sendTransactionAsync({
from: this._staker,
});
receipt = await this._stakingApiWrapper.stakingContract.moveStake.awaitTransactionSuccessAsync(
new StakeInfo(StakeStatus.Undelegated),
new StakeInfo(StakeStatus.Delegated, this._poolId),
this._amountToStake,
{ from: this._staker },
);
receipt = await this._stakingApiWrapper.stakingContract
.moveStake(
new StakeInfo(StakeStatus.Undelegated),
new StakeInfo(StakeStatus.Delegated, this._poolId),
this._amountToStake,
)
.awaitTransactionSuccessAsync({ from: this._staker });
break;
case TestAction.Undelegate:
receipt = await this._stakingApiWrapper.stakingContract.moveStake.awaitTransactionSuccessAsync(
new StakeInfo(StakeStatus.Delegated, this._poolId),
new StakeInfo(StakeStatus.Undelegated),
this._amountToStake,
{ from: this._staker },
);
receipt = await this._stakingApiWrapper.stakingContract
.moveStake(
new StakeInfo(StakeStatus.Delegated, this._poolId),
new StakeInfo(StakeStatus.Undelegated),
this._amountToStake,
)
.awaitTransactionSuccessAsync({ from: this._staker });
break;
case TestAction.PayProtocolFee:
receipt = await this._stakingApiWrapper.stakingContract.payProtocolFee.awaitTransactionSuccessAsync(
this._poolOperator,
this._takerAddress,
this._protocolFee,
{ from: this._exchangeAddress, value: this._protocolFee },
);
receipt = await this._stakingApiWrapper.stakingContract
.payProtocolFee(this._poolOperator, this._takerAddress, this._protocolFee)
.awaitTransactionSuccessAsync({ from: this._exchangeAddress, value: this._protocolFee });
break;
case TestAction.CreatePool:
receipt = await this._stakingApiWrapper.stakingContract.createStakingPool.awaitTransactionSuccessAsync(
0,
true,
{ from: this._poolOperator },
);
receipt = await this._stakingApiWrapper.stakingContract
.createStakingPool(0, true)
.awaitTransactionSuccessAsync({ from: this._poolOperator });
const createStakingPoolLog = receipt.logs[0];
// tslint:disable-next-line no-unnecessary-type-assertion
this._poolId = (createStakingPoolLog as DecodedLogEntry<any>).args.poolId;