Remove locking restake flag, throw error when node tries to commit twice in a row

pull/2518/head
vzotova 2021-01-27 15:04:12 +03:00
parent 61d8dc1ec0
commit 7c77aa65d0
24 changed files with 24 additions and 329 deletions

View File

@ -912,30 +912,6 @@ class Staker(NucypherTokenActor):
receipt = self._set_restaking(value=True)
return receipt
@only_me
@save_receipt
def enable_restaking_lock(self, release_period: int) -> TxReceipt:
current_period = self.staking_agent.get_current_period()
if release_period < current_period:
raise ValueError(f"Release period for re-staking lock must be in the future. "
f"Current period is {current_period}, got '{release_period}'.")
if self.is_contract:
receipt = self.preallocation_escrow_agent.lock_restaking(release_period=release_period)
else:
receipt = self.staking_agent.lock_restaking(staker_address=self.checksum_address,
release_period=release_period)
return receipt
@property
def restaking_lock_enabled(self) -> bool:
status = self.staking_agent.is_restaking_locked(staker_address=self.checksum_address)
return status
@property
def restake_unlock_period(self) -> int:
period = self.staking_agent.get_restake_unlock_period(staker_address=self.checksum_address)
return period
def disable_restaking(self) -> TxReceipt:
receipt = self._set_restaking(value=False)
return receipt

View File

@ -593,10 +593,6 @@ class StakingEscrowAgent(EthereumContractAgent):
flags = self.get_flags(staker_address)
return flags.restake_flag
@contract_api(CONTRACT_CALL)
def is_restaking_locked(self, staker_address: ChecksumAddress) -> bool:
return self.contract.functions.isReStakeLocked(staker_address).call()
@contract_api(TRANSACTION)
def set_restaking(self, staker_address: ChecksumAddress, value: bool) -> TxReceipt:
"""
@ -609,20 +605,6 @@ class StakingEscrowAgent(EthereumContractAgent):
# TODO: Handle ReStakeSet event (see #1193)
return receipt
@contract_api(TRANSACTION)
def lock_restaking(self, staker_address: ChecksumAddress, release_period: Period) -> TxReceipt:
contract_function: ContractFunction = self.contract.functions.lockReStake(release_period)
receipt: TxReceipt = self.blockchain.send_transaction(contract_function=contract_function,
sender_address=staker_address)
# TODO: Handle ReStakeLocked event (see #1193)
return receipt
@contract_api(CONTRACT_CALL)
def get_restake_unlock_period(self, staker_address: ChecksumAddress) -> Period:
staker_info: StakerInfo = self.get_staker_info(staker_address)
restake_unlock_period: int = int(staker_info.lock_restake_until_period)
return Period(restake_unlock_period)
@contract_api(CONTRACT_CALL)
def is_winding_down(self, staker_address: ChecksumAddress) -> bool:
flags = self.get_flags(staker_address)

View File

@ -351,7 +351,7 @@ class BlockchainInterface:
if not provider_uri and not provider:
raise self.NoProvider("No URI or provider instances supplied.")
if provider_uri and not provider:
if provider_uri and (provider is None or provider is NO_BLOCKCHAIN_CONNECTION):
uri_breakdown = urlparse(provider_uri)
if uri_breakdown.scheme == 'tester':

View File

@ -54,7 +54,7 @@ def __execute(compiler_version: VersionString, input_config: Dict, allow_paths:
errors = compiler_output.get('errors')
if errors:
formatted = '\n'.join([error['formattedMessage'] for error in errors])
SOLC_LOGGER.warn(f"Errors during compilation: \n{formatted}")
print(f"Errors during compilation: \n{formatted}")
SOLC_LOGGER.info(f"Successfully compiled {len(compiler_output)} sources with {OPTIMIZER_RUNS} optimization runs")
return compiler_output

View File

@ -125,7 +125,6 @@ contract StakingEscrow is Issuer, IERC900History {
event Minted(address indexed staker, uint16 indexed period, uint256 value);
event Slashed(address indexed staker, uint256 penalty, address indexed investigator, uint256 reward);
event ReStakeSet(address indexed staker, bool reStake);
event ReStakeLocked(address indexed staker, uint16 lockUntilPeriod);
event WorkerBonded(address indexed staker, address indexed worker, uint16 indexed startPeriod);
event WorkMeasurementSet(address indexed staker, bool measureWork);
event WindDownSet(address indexed staker, bool windDown);
@ -154,7 +153,7 @@ contract StakingEscrow is Issuer, IERC900History {
uint16 currentCommittedPeriod;
uint16 nextCommittedPeriod;
uint16 lastCommittedPeriod;
uint16 lockReStakeUntilPeriod;
uint16 stub1; // former slot for lockReStakeUntilPeriod
uint256 completedWork;
uint16 workerStartPeriod; // period when worker was bonded
address worker;
@ -453,14 +452,6 @@ contract StakingEscrow is Issuer, IERC900History {
}
}
/**
* @notice Checks if `reStake` parameter is available for changing
* @param _staker Staker
*/
function isReStakeLocked(address _staker) public view returns (bool) {
return getCurrentPeriod() < stakerInfo[_staker].lockReStakeUntilPeriod;
}
/**
* @notice Get worker using staker's address
*/
@ -541,11 +532,9 @@ contract StakingEscrow is Issuer, IERC900History {
/**
* @notice Set `reStake` parameter. If true then all staking rewards will be added to locked stake
* Only if this parameter is not locked
* @param _reStake Value for parameter
*/
function setReStake(bool _reStake) external {
require(!isReStakeLocked(msg.sender));
StakerInfo storage info = stakerInfo[msg.sender];
if (info.flags.bitSet(RE_STAKE_DISABLED_INDEX) == !_reStake) {
return;
@ -554,17 +543,6 @@ contract StakingEscrow is Issuer, IERC900History {
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Lock `reStake` parameter. Only if this parameter is not locked
* @param _lockReStakeUntilPeriod Can't change `reStake` value until this period
*/
function lockReStake(uint16 _lockReStakeUntilPeriod) external {
require(!isReStakeLocked(msg.sender) &&
_lockReStakeUntilPeriod > getCurrentPeriod());
stakerInfo[msg.sender].lockReStakeUntilPeriod = _lockReStakeUntilPeriod;
emit ReStakeLocked(msg.sender, _lockReStakeUntilPeriod);
}
/**
* @notice Deposit tokens from WorkLock contract
* @param _staker Staker address
@ -1088,15 +1066,13 @@ contract StakingEscrow is Issuer, IERC900History {
// Only worker with real address can make a commitment
require(msg.sender == tx.origin);
uint16 lastCommittedPeriod = getLastCommittedPeriod(staker);
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker);
uint16 currentPeriod = getCurrentPeriod();
uint16 nextPeriod = currentPeriod + 1;
// the period has already been committed
if (info.nextCommittedPeriod == nextPeriod) {
return;
}
require(info.nextCommittedPeriod != nextPeriod);
uint16 lastCommittedPeriod = getLastCommittedPeriod(staker);
(uint16 processedPeriod1, uint16 processedPeriod2) = mint(staker);
uint256 lockedTokens = getLockedTokens(info, currentPeriod, nextPeriod);
require(lockedTokens > 0);
@ -1622,7 +1598,6 @@ contract StakingEscrow is Issuer, IERC900History {
infoToCheck.currentCommittedPeriod == info.currentCommittedPeriod &&
infoToCheck.nextCommittedPeriod == info.nextCommittedPeriod &&
infoToCheck.flags == info.flags &&
infoToCheck.lockReStakeUntilPeriod == info.lockReStakeUntilPeriod &&
infoToCheck.lastCommittedPeriod == info.lastCommittedPeriod &&
infoToCheck.completedWork == info.completedWork &&
infoToCheck.worker == info.worker &&

View File

@ -70,7 +70,7 @@ contract BaseStakingInterface {
/**
* @notice Interface for accessing main contracts from a staking contract
* @dev All methods must be stateless because this code will be executed by delegatecall call, use immutable fields.
* @dev |v1.6.1|
* @dev |v1.7.1|
*/
contract StakingInterface is BaseStakingInterface {
@ -85,7 +85,6 @@ contract StakingInterface is BaseStakingInterface {
event PolicyFeeWithdrawn(address indexed sender, uint256 value);
event MinFeeRateSet(address indexed sender, uint256 value);
event ReStakeSet(address indexed sender, bool reStake);
event ReStakeLocked(address indexed sender, uint16 lockUntilPeriod);
event WorkerBonded(address indexed sender, address worker);
event Prolonged(address indexed sender, uint256 index, uint16 periods);
event WindDownSet(address indexed sender, bool windDown);
@ -131,15 +130,6 @@ contract StakingInterface is BaseStakingInterface {
emit ReStakeSet(msg.sender, _reStake);
}
/**
* @notice Lock `reStake` parameter in the staking escrow
* @param _lockReStakeUntilPeriod Can't change `reStake` value until this period
*/
function lockReStake(uint16 _lockReStakeUntilPeriod) public onlyDelegateCall {
escrow.lockReStake(_lockReStakeUntilPeriod);
emit ReStakeLocked(msg.sender, _lockReStakeUntilPeriod);
}
/**
* @notice Deposit tokens to the staking escrow
* @param _value Amount of token to deposit

View File

@ -33,10 +33,8 @@ from nucypher.cli.literature import (
CONFIRM_ENABLE_WINDING_DOWN,
CONFIRM_LARGE_STAKE_DURATION,
CONFIRM_LARGE_STAKE_VALUE,
CONFIRM_RESTAKING_LOCK,
CONFIRM_STAGED_STAKE,
RESTAKING_AGREEMENT,
RESTAKING_LOCK_AGREEMENT,
WINDING_DOWN_AGREEMENT,
SNAPSHOTS_DISABLING_AGREEMENT,
CONFIRM_DISABLE_SNAPSHOTS
@ -61,13 +59,6 @@ def confirm_deployment(emitter: StdoutEmitter, deployer_interface: BlockchainDep
return True
def confirm_enable_restaking_lock(emitter: StdoutEmitter, staking_address: str, release_period: int) -> bool:
"""Interactively confirm enabling of the staking lock with user agreements."""
emitter.message(RESTAKING_LOCK_AGREEMENT.format(staking_address=staking_address, release_period=release_period))
click.confirm(CONFIRM_RESTAKING_LOCK.format(staking_address=staking_address, release_period=release_period), abort=True)
return True
def confirm_enable_restaking(emitter: StdoutEmitter, staking_address: str) -> bool:
"""Interactively confirm enabling of the restaking with user agreements."""
emitter.message(RESTAKING_AGREEMENT.format(staking_address=staking_address))

View File

@ -34,7 +34,6 @@ from nucypher.cli.actions.auth import get_client_password
from nucypher.cli.actions.configure import get_or_update_configuration, handle_missing_configuration_file
from nucypher.cli.actions.confirm import (
confirm_enable_restaking,
confirm_enable_restaking_lock,
confirm_enable_winding_down,
confirm_large_stake,
confirm_staged_stake,
@ -63,7 +62,6 @@ from nucypher.cli.literature import (
PROMPT_WORKER_ADDRESS,
SUCCESSFUL_DETACH_WORKER,
SUCCESSFUL_DISABLE_RESTAKING, SUCCESSFUL_DISABLE_WIND_DOWN,
SUCCESSFUL_ENABLE_RESTAKE_LOCK,
SUCCESSFUL_ENABLE_RESTAKING,
SUCCESSFUL_ENABLE_WIND_DOWN,
SUCCESSFUL_NEW_STAKEHOLDER_CONFIG,
@ -696,12 +694,11 @@ def increase(general_config: GroupGeneralConfig,
@group_transacting_staker_options
@option_config_file
@click.option('--enable/--disable', help="Used to enable and disable re-staking", is_flag=True, default=True)
@click.option('--lock-until', help="Period to release re-staking lock", type=click.IntRange(min=0))
@option_force
@group_general_config
def restake(general_config: GroupGeneralConfig,
transacting_staker_options: TransactingStakerOptions,
config_file, enable, lock_until, force):
config_file, enable, force):
"""Manage re-staking with --enable or --disable."""
# Setup
@ -717,21 +714,7 @@ def restake(general_config: GroupGeneralConfig,
force=force)
# Inner Exclusive Switch
if lock_until:
if not force:
confirm_enable_restaking_lock(emitter, staking_address=staking_address, release_period=lock_until)
# Authenticate and Execute
password = get_password(stakeholder=STAKEHOLDER,
blockchain=blockchain,
client_account=client_account,
hw_wallet=transacting_staker_options.hw_wallet)
STAKEHOLDER.assimilate(password=password)
receipt = STAKEHOLDER.enable_restaking_lock(release_period=lock_until)
emitter.echo(SUCCESSFUL_ENABLE_RESTAKE_LOCK.format(staking_address=staking_address, lock_until=lock_until),
color='green', verbosity=1)
elif enable:
if enable:
if not force:
confirm_enable_restaking(emitter, staking_address=staking_address)

View File

@ -169,15 +169,6 @@ SUCCESSFUL_DISABLE_WIND_DOWN = 'Successfully disabled winding down for {staking_
# Restaking
#
RESTAKING_LOCK_AGREEMENT = """
By enabling the re-staking lock for {staking_address}, you are committing to automatically
re-stake all rewards until a future period. You will not be able to disable re-staking until {release_period}.
"""
CONFIRM_RESTAKING_LOCK = "Confirm enable re-staking lock for staker {staking_address} until {release_period}?"
SUCCESSFUL_ENABLE_RESTAKE_LOCK = 'Successfully enabled re-staking lock for {staking_address} until {lock_until}'
RESTAKING_AGREEMENT = """
By enabling the re-staking for {staking_address}, all staking rewards will be automatically added to your existing stake.
"""

View File

@ -72,8 +72,7 @@ def paint_stakes(emitter: StdoutEmitter,
missing_info = f'Missing {missing} commitments{"s" if missing > 1 else ""}' if missing else f'Committed #{last_committed}'
staker_data = [missing_info,
f'{"Yes" if staker.is_restaking else "No"} '
f'({"Locked" if staker.restaking_lock_enabled else "Unlocked"})',
"Yes" if staker.is_restaking else "No",
"Yes" if bool(staker.is_winding_down) else "No",
"Yes" if bool(staker.is_taking_snapshots) else "No",
pretty_fees,

View File

@ -172,11 +172,7 @@ def paint_stakers(emitter, stakers: List[str], registry: BaseContractRegistry) -
emitter.echo(f"{tab} Staked in current period: {current_locked_tokens}")
emitter.echo(f"{tab} Staked in next period: {next_locked_tokens}")
if is_restaking:
if staker.restaking_lock_enabled:
unlock_period = staker.restake_unlock_period
emitter.echo(f"{tab} {'Re-staking:':10} Yes (Locked until period: {unlock_period})")
else:
emitter.echo(f"{tab} {'Re-staking:':10} Yes (Unlocked)")
emitter.echo(f"{tab} {'Re-staking:':10} Yes")
else:
emitter.echo(f"{tab} {'Re-staking:':10} No")
emitter.echo(f"{tab} {'Winding down:':10} {'Yes' if is_winding_down else 'No'}")

View File

@ -242,24 +242,8 @@ def test_staker_manages_restaking(testerchain, test_registry, staker):
receipt = staker.enable_restaking()
assert receipt['status'] == 1
# Enable Restaking Lock
staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=test_registry)
current_period = staking_agent.get_current_period()
terminal_period = current_period + 2
assert not staker.restaking_lock_enabled
receipt = staker.enable_restaking_lock(release_period=terminal_period)
assert receipt['status'] == 1
assert staker.restaking_lock_enabled
with pytest.raises((TransactionFailed, ValueError)):
staker.disable_restaking()
# Wait until terminal period
testerchain.time_travel(periods=2)
receipt = staker.disable_restaking()
assert receipt['status'] == 1
assert not staker.restaking_lock_enabled
def test_staker_collects_staking_reward(testerchain,

View File

@ -263,22 +263,6 @@ def test_deposit_and_increase(agency, testerchain, test_registry, token_economic
assert staking_agent.get_locked_tokens(staker_account, 1) == locked_tokens + amount
def test_lock_restaking(agency, testerchain, test_registry):
staker_account, worker_account, *other = testerchain.unassigned_accounts
staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=test_registry)
current_period = staking_agent.get_current_period()
terminal_period = current_period + 2
assert staking_agent.is_restaking(staker_account)
assert not staking_agent.is_restaking_locked(staker_account)
receipt = staking_agent.lock_restaking(staker_account, release_period=terminal_period)
assert receipt['status'] == 1, "Transaction Rejected"
assert staking_agent.is_restaking_locked(staker_account)
testerchain.time_travel(periods=2) # Wait for re-staking lock to be released.
assert not staking_agent.is_restaking_locked(staker_account)
def test_disable_restaking(agency, testerchain, test_registry):
staker_account, worker_account, *other = testerchain.unassigned_accounts
staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=test_registry)
@ -295,6 +279,7 @@ def test_collect_staking_reward(agency, testerchain, mock_transacting_power_acti
staker_account, worker_account, *other = testerchain.unassigned_accounts
# Commit to next period
testerchain.time_travel(periods=1)
staking_agent.commit_to_next_period(worker_address=worker_account)
testerchain.time_travel(periods=2)

View File

@ -244,6 +244,7 @@ def test_refund(click_runner, testerchain, agency_local_registry, token_economic
transacting_power.activate(password=INSECURE_DEVELOPMENT_PASSWORD)
# Do some work
testerchain.time_travel(periods=1)
for i in range(3):
txhash = worker.commit_to_next_period()
testerchain.wait_for_receipt(txhash)

View File

@ -312,34 +312,6 @@ def test_stake_restake(click_runner,
assert not staker.is_restaking
assert "Successfully disabled" in result.output
staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=agency_local_registry)
current_period = staking_agent.get_current_period()
release_period = current_period + 1
lock_args = ('stake', 'restake',
'--lock-until', release_period,
'--config-file', stakeholder_configuration_file_location,
'--allocation-filepath', MOCK_INDIVIDUAL_ALLOCATION_FILEPATH,
'--force')
result = click_runner.invoke(nucypher_cli,
lock_args,
input=INSECURE_DEVELOPMENT_PASSWORD,
catch_exceptions=False)
assert result.exit_code == 0
# Still not staking and the lock is enabled
assert not staker.is_restaking
assert staker.restaking_lock_enabled
# CLI Output includes success message
assert "Successfully enabled" in result.output
assert str(release_period) in result.output
# Wait until release period
testerchain.time_travel(periods=1)
assert not staker.restaking_lock_enabled
assert not staker.is_restaking
disable_args = ('stake', 'restake',
'--enable',
'--config-file', stakeholder_configuration_file_location,
@ -353,6 +325,7 @@ def test_stake_restake(click_runner,
assert result.exit_code == 0
allocation_contract_address = preallocation_escrow_agent.principal_contract.address
staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=agency_local_registry)
assert staking_agent.is_restaking(allocation_contract_address)
staker = Staker(is_me=True,
@ -536,6 +509,7 @@ def test_collect_rewards_integration(click_runner,
mock_transacting_power_activation(account=worker_address, password=INSECURE_DEVELOPMENT_PASSWORD)
# Make a commitment for half the first stake duration
testerchain.time_travel(periods=1)
for _ in range(half_stake_time):
logger.debug(f">>>>>>>>>>> TEST PERIOD {current_period} <<<<<<<<<<<<<<<<")
ursula.commit_to_next_period()

View File

@ -424,34 +424,6 @@ def test_stake_restake(click_runner,
assert not staker.is_restaking
assert "Successfully disabled" in result.output
staking_agent = ContractAgency.get_agent(StakingEscrowAgent, registry=agency_local_registry)
current_period = staking_agent.get_current_period()
release_period = current_period + 1
lock_args = ('stake', 'restake',
'--lock-until', release_period,
'--config-file', stakeholder_configuration_file_location,
'--staking-address', manual_staker,
'--force')
result = click_runner.invoke(nucypher_cli,
lock_args,
input=INSECURE_DEVELOPMENT_PASSWORD,
catch_exceptions=False)
assert result.exit_code == 0
# Still not staking and the lock is enabled
assert not staker.is_restaking
assert staker.restaking_lock_enabled
# CLI Output includes success message
assert "Successfully enabled" in result.output
assert str(release_period) in result.output
# Wait until release period
testerchain.time_travel(periods=1)
assert not staker.restaking_lock_enabled
assert not staker.is_restaking
disable_args = ('stake', 'restake',
'--enable',
'--config-file', stakeholder_configuration_file_location,
@ -605,6 +577,7 @@ def test_collect_rewards_integration(click_runner,
mock_transacting_power_activation(account=worker_address, password=INSECURE_DEVELOPMENT_PASSWORD)
# Make a commitment for half the first stake duration
testerchain.time_travel(periods=1)
for _ in range(half_stake_time):
logger.debug(f">>>>>>>>>>> TEST PERIOD {current_period} <<<<<<<<<<<<<<<<")
ursula.commit_to_next_period()

View File

@ -20,7 +20,6 @@ contract StakingEscrowForStakingContractMock {
uint16 public periods;
uint256 public index;
bool public reStake;
uint16 public lockReStakeUntilPeriod;
address public worker;
bool public windDown;
bool public snapshots;
@ -77,10 +76,6 @@ contract StakingEscrowForStakingContractMock {
reStake = _reStake;
}
function lockReStake(uint16 _lockReStakeUntilPeriod) external {
lockReStakeUntilPeriod = _lockReStakeUntilPeriod;
}
function bondWorker(address _worker) external {
worker = _worker;
}

View File

@ -357,14 +357,6 @@ def test_staking_before_initialization(testerchain,
_wind_down, re_stake, _measure_work, _snapshots = escrow.functions.getFlags(preallocation_escrow_1.address).call()
assert re_stake
current_period = escrow.functions.getCurrentPeriod().call()
tx = preallocation_escrow_interface_1.functions.lockReStake(current_period + 25).transact({'from': staker3})
testerchain.wait_for_receipt(tx)
_wind_down, re_stake, _measure_work, _snapshots = escrow.functions.getFlags(preallocation_escrow_1.address).call()
assert re_stake
# Can't unlock re-stake parameter now
with pytest.raises((TransactionFailed, ValueError)):
tx = preallocation_escrow_interface_1.functions.setReStake(False).transact({'from': staker3})
testerchain.wait_for_receipt(tx)
# Deposit some tokens to the preallocation escrow and lock them
tx = token.functions.approve(preallocation_escrow_1.address, 10000).transact({'from': creator})
@ -598,7 +590,6 @@ def test_worklock_phases(testerchain,
execute_multisig_transaction(testerchain, multisig, [contracts_owners[0], contracts_owners[1]], tx)
pytest.escrow_supply += token_economics.erc20_reward_supply
assert not escrow.functions.isReStakeLocked(staker1).call()
tx = worklock.functions.claim().transact({'from': staker1, 'gas_price': 0})
testerchain.wait_for_receipt(tx)
assert worklock.functions.workInfo(staker1).call()[2]
@ -1223,11 +1214,6 @@ def test_withdraw(testerchain,
testerchain.wait_for_receipt(tx)
testerchain.time_travel(hours=1)
# Can't unlock re-stake parameter yet
with pytest.raises((TransactionFailed, ValueError)):
tx = preallocation_escrow_interface_1.functions.setReStake(False).transact({'from': staker3})
testerchain.wait_for_receipt(tx)
testerchain.time_travel(hours=1)
# Now can turn off re-stake
tx = preallocation_escrow_interface_1.functions.setReStake(False).transact({'from': staker3})

View File

@ -124,9 +124,6 @@ def test_staker(testerchain, token, escrow, staking_contract, staking_contract_i
with pytest.raises((TransactionFailed, ValueError)):
tx = staking_interface.functions.setReStake(True).transact({'from': owner})
testerchain.wait_for_receipt(tx)
with pytest.raises((TransactionFailed, ValueError)):
tx = staking_interface.functions.lockReStake(0).transact({'from': owner})
testerchain.wait_for_receipt(tx)
with pytest.raises((TransactionFailed, ValueError)):
tx = staking_interface.functions.bondWorker(owner).transact({'from': owner})
testerchain.wait_for_receipt(tx)
@ -147,7 +144,6 @@ def test_staker(testerchain, token, escrow, staking_contract, staking_contract_i
mints = staking_contract_interface.events.Minted.createFilter(fromBlock='latest')
staker_withdraws = staking_contract_interface.events.WithdrawnAsStaker.createFilter(fromBlock='latest')
re_stakes = staking_contract_interface.events.ReStakeSet.createFilter(fromBlock='latest')
re_stake_locks = staking_contract_interface.events.ReStakeLocked.createFilter(fromBlock='latest')
worker_logs = staking_contract_interface.events.WorkerBonded.createFilter(fromBlock='latest')
prolong_logs = staking_contract_interface.events.Prolonged.createFilter(fromBlock='latest')
wind_down_logs = staking_contract_interface.events.WindDownSet.createFilter(fromBlock='latest')
@ -206,9 +202,6 @@ def test_staker(testerchain, token, escrow, staking_contract, staking_contract_i
tx = staking_contract_interface.functions.setReStake(True).transact({'from': owner})
testerchain.wait_for_receipt(tx)
assert escrow.functions.reStake().call()
tx = staking_contract_interface.functions.lockReStake(123).transact({'from': owner})
testerchain.wait_for_receipt(tx)
assert 123 == escrow.functions.lockReStakeUntilPeriod().call()
# Test setting worker
tx = staking_contract_interface.functions.bondWorker(owner).transact({'from': owner})
@ -274,12 +267,6 @@ def test_staker(testerchain, token, escrow, staking_contract, staking_contract_i
assert owner == event_args['sender']
assert event_args['reStake']
events = re_stake_locks.get_all_entries()
assert 1 == len(events)
event_args = events[0]['args']
assert owner == event_args['sender']
assert 123 == event_args['lockUntilPeriod']
events = worker_logs.get_all_entries()
assert 1 == len(events)
event_args = events[0]['args']

View File

@ -150,9 +150,10 @@ def test_minting(testerchain, token, escrow_contract, token_economics):
assert policy_manager.functions.getPeriod(staker1, 5).call() == 0
assert policy_manager.functions.getPeriod(staker1, 6).call() == current_period + 1
# Checks that no error from repeated method call
tx = escrow.functions.commitToNextPeriod().transact({'from': staker1})
testerchain.wait_for_receipt(tx)
# Can't commit more than once
with pytest.raises((TransactionFailed, ValueError)):
tx = escrow.functions.commitToNextPeriod().transact({'from': staker1})
testerchain.wait_for_receipt(tx)
assert policy_manager.functions.getPeriodsLength(staker1).call() == 7
# Staker and Staker(2) mint tokens for last periods

View File

@ -23,7 +23,6 @@ from web3.contract import Contract
MAX_SUB_STAKES = 30
MAX_UINT16 = 65535
LOCK_RE_STAKE_UNTIL_PERIOD_FIELD = 4
def test_staking(testerchain, token, escrow_contract):

View File

@ -26,8 +26,6 @@ from nucypher.blockchain.eth.constants import NULL_ADDRESS
from nucypher.blockchain.eth.token import NU
from nucypher.utilities.ethereum import get_array_data_location, get_mapping_entry_location, to_bytes32
LOCK_RE_STAKE_UNTIL_PERIOD_FIELD = 4
def test_upgrading(testerchain, token, token_economics, deploy_contract):
creator = testerchain.client.accounts[0]
@ -102,8 +100,6 @@ def test_upgrading(testerchain, token, token_economics, deploy_contract):
testerchain.wait_for_receipt(tx)
tx = contract.functions.setReStake(True).transact({'from': staker})
testerchain.wait_for_receipt(tx)
tx = contract.functions.lockReStake(contract.functions.getCurrentPeriod().call() + 1).transact({'from': staker})
testerchain.wait_for_receipt(tx)
tx = worklock.functions.setWorkMeasurement(staker, True).transact()
testerchain.wait_for_receipt(tx)
tx = contract.functions.bondWorker(worker).transact({'from': staker})
@ -273,7 +269,6 @@ def test_re_stake(testerchain, token, escrow_contract):
staker2 = testerchain.client.accounts[2]
re_stake_log = escrow.events.ReStakeSet.createFilter(fromBlock='latest')
re_stake_lock_log = escrow.events.ReStakeLocked.createFilter(fromBlock='latest')
# Give Escrow tokens for reward and initialize contract
reward = 10 ** 9
@ -314,21 +309,6 @@ def test_re_stake(testerchain, token, escrow_contract):
assert staker == event_args['staker']
assert not event_args['reStake']
# Lock re-stake parameter during 1 period
period = escrow.functions.getCurrentPeriod().call()
tx = escrow.functions.lockReStake(period + 1).transact({'from': staker})
testerchain.wait_for_receipt(tx)
# Can't set re-stake parameter in the current period
with pytest.raises((TransactionFailed, ValueError)):
tx = escrow.functions.setReStake(True).transact({'from': staker})
testerchain.wait_for_receipt(tx)
events = re_stake_lock_log.get_all_entries()
assert 1 == len(events)
event_args = events[0]['args']
assert staker == event_args['staker']
assert period + 1 == event_args['lockUntilPeriod']
# Ursula deposits some tokens and makes a commitment
tx = token.functions.transfer(staker, 10000).transact({'from': creator})
testerchain.wait_for_receipt(tx)
@ -371,28 +351,11 @@ def test_re_stake(testerchain, token, escrow_contract):
testerchain.wait_for_receipt(tx)
assert sub_stake == escrow.functions.getAllTokens(staker).call()
# Set re-stake and lock parameter
# Set re-stake
tx = escrow.functions.setReStake(True).transact({'from': staker})
testerchain.wait_for_receipt(tx)
_wind_down, re_stake, _measure_work, _snapshots = escrow.functions.getFlags(staker).call()
assert re_stake
tx = escrow.functions.lockReStake(period + 6).transact({'from': staker})
testerchain.wait_for_receipt(tx)
# Can't set re-stake parameter during 6 periods
with pytest.raises((TransactionFailed, ValueError)):
tx = escrow.functions.setReStake(False).transact({'from': staker})
testerchain.wait_for_receipt(tx)
events = re_stake_log.get_all_entries()
assert 4 == len(events)
event_args = events[3]['args']
assert staker == event_args['staker']
assert event_args['reStake']
events = re_stake_lock_log.get_all_entries()
assert 2 == len(events)
event_args = events[1]['args']
assert staker == event_args['staker']
assert period + 6 == event_args['lockUntilPeriod']
# Make a commitment and try to mint with re-stake
tx = escrow.functions.commitToNextPeriod().transact({'from': staker})
@ -503,11 +466,6 @@ def test_re_stake(testerchain, token, escrow_contract):
assert 2 * stake + reward_for_first_period == escrow.functions.lockedPerPeriod(period - 1).call()
assert 0 == escrow.functions.lockedPerPeriod(period).call()
# Can't turn off re-stake parameter during one more period
with pytest.raises((TransactionFailed, ValueError)):
tx = escrow.functions.setReStake(False).transact({'from': staker})
testerchain.wait_for_receipt(tx)
# Make a commitment and try to mint without re-stake
tx = escrow.functions.commitToNextPeriod().transact({'from': staker})
testerchain.wait_for_receipt(tx)

View File

@ -20,9 +20,9 @@ import pytest
from nucypher.blockchain.eth.clients import EthereumTesterClient, PUBLIC_CHAINS
from nucypher.blockchain.eth.token import NU
from nucypher.cli.actions.confirm import (confirm_deployment, confirm_enable_restaking, confirm_enable_restaking_lock,
from nucypher.cli.actions.confirm import (confirm_deployment, confirm_enable_restaking,
confirm_enable_winding_down, confirm_large_stake, confirm_staged_stake)
from nucypher.cli.literature import (ABORT_DEPLOYMENT, RESTAKING_AGREEMENT, RESTAKING_LOCK_AGREEMENT,
from nucypher.cli.literature import (ABORT_DEPLOYMENT, RESTAKING_AGREEMENT,
WINDING_DOWN_AGREEMENT, CONFIRM_STAGED_STAKE,
CONFIRM_LARGE_STAKE_VALUE, CONFIRM_LARGE_STAKE_DURATION)
@ -83,36 +83,6 @@ def test_confirm_deployment_cli_action(mocker, mock_stdin, test_emitter, capsys,
assert f"Type '{llamanet.upper()}' to continue: " in captured.out
def test_confirm_enable_restaking_lock_cli_action(mock_stdin, test_emitter, capsys):
# Test data
staking_address, release_period = '0xdeadbeef', 1
# Positive Case
mock_stdin.line(YES)
result = confirm_enable_restaking_lock(emitter=test_emitter,
release_period=release_period,
staking_address=staking_address)
assert result
captured = capsys.readouterr()
assert mock_stdin.empty()
restake_agreement = RESTAKING_LOCK_AGREEMENT.format(staking_address=staking_address, release_period=release_period)
assert restake_agreement in captured.out
# Negative case
mock_stdin.line(NO)
with pytest.raises(click.Abort):
confirm_enable_restaking_lock(emitter=test_emitter,
release_period=release_period,
staking_address=staking_address)
captured = capsys.readouterr()
assert mock_stdin.empty()
restake_agreement = RESTAKING_LOCK_AGREEMENT.format(staking_address=staking_address,
release_period=release_period)
assert restake_agreement in captured.out
def test_confirm_enable_restaking_cli_action(test_emitter, mock_stdin, capsys):
# Positive Case

View File

@ -499,7 +499,6 @@ def estimate_gas(analyzer: AnalyzeGas = None) -> None:
#
# Slashing tests
#
transact(staker_functions.commitToNextPeriod(), {'from': staker1})
testerchain.time_travel(periods=1)
#