https://github.com/vechain/stargate-contracts/tree/jose/update-contracts-to-hayabusa
requestDelegationExit is called which call _updatePeriodEffectiveStake to decrease effective stakes.requestDeleagtionsExit decreasing effective stakesdelegateSince staker protocol is mocked wanted to get into some details on protocolstaker contract
First: Validators has multiple cases (Doesn't exist, statusQueued, StatusActive, went offline, SignaledExit, Moved to StatusExit)
Focusing on SingaledExit status in this status the validator will be marked as active until period ends, and you can know he has signaled exit by looking at validatorExitBlock it will reflect the block once requested to exit.
In stargate contract validators that signaled exit is treated as active so for the delegator to redelgate to another validator he should call requestDelegationExit function
once functino called it remove the delegation from validator effective stakes
File: Stargate.sol
523: function requestDelegationExit(
// CODE
567: // decrease the effective stake
568: _updatePeriodEffectiveStake($, delegation.validator, _tokenId, completedPeriods + 2, false);
Moving forward until period ends and that the delegator can withdraw from the validator or redelgate to another validator at this time
When the delegator choose to redelgate he will enter this block current validator is exited
File: Stargate.sol
338: function _delegate(StargateStorage storage $, uint256 _tokenId, address _validator) private {
// CODE
398: if (
399: currentValidatorStatus == VALIDATOR_STATUS_EXITED ||
400: status == DelegationStatus.PENDING
401: ) {
402: // get the completed periods of the previous validator
403: (, , , uint32 oldCompletedPeriods) = $
404: .protocolStakerContract
405: .getValidationPeriodDetails(currentValidator);
406: // decrease the effective stake of the previous validator
407:@> _updatePeriodEffectiveStake(
408: $,
409: currentValidator,
410: _tokenId,
411: oldCompletedPeriods + 2,
412: false // decrease
413: );
414: }
Decreasing the effective stakes twice
For the next delegators to unstake or to redelegate they will have their funds stuck due to underflow in claim rewards calculations which always called in
looking at implementation of _updateperiodeffectivestake
File: Stargate.sol
1044: function _updatePeriodEffectiveStake(
1045: StargateStorage storage $,
1046: address _validator,
1047: uint256 _tokenId,
1048: uint32 _period,
1049: bool _isIncrease
1050: ) private {
1051: // calculate the effective stake
1052: uint256 effectiveStake = _calculateEffectiveStake($, _tokenId);
1053:
1054: // get the current effective stake
1055: uint256 currentValue = $.delegatorsEffectiveStake[_validator].upperLookup(_period);
1056:
1057: // calculate the updated effective stake
1058:@> uint256 updatedValue = _isIncrease
1059: ? currentValue + effectiveStake
1060: : currentValue - effectiveStake;
1061:
1062: // push the updated effective stake
1063: $.delegatorsEffectiveStake[_validator].push(_period, SafeCast.toUint224(updatedValue));
1064: }
delegatorsEffectiveStake variable is updated to the latest value either adding or removing effective stakes (in our case removing)
This parameter is called in _claimableRewardsForPeriod called by_claimableRewards called by _claimRewards which always being called in
claim inside unstake claim inside delegate
decrease effective stakes in delegate decrease effective stakes in requestDelegationExit
[!NOTE] If you already have good understanding of thor staking protocol flow and its validator status you can skip this the next POC (they are just to confirm parts changed in protocolstakermock) the actual poc start under ## POC
1st you can check validator exit proccess explaining the change from active status to exit status
2nd as of that protocolstaker is a mock contract wanted to confirm to you the behavior that the delegationid will always be directing to the validator
you can download thor prtocol and add this test in delegation_test.go
func Test_Delegation_Mapping_Persistence(t *testing.T) {
// Copy pattern from existing working test
staker, validators := newDelegationStaker(t)
validator := validators[0]
stake := delegationStake()
// Step 1: Add delegation
id, err := staker.AddDelegation(validator.ID, stake, 255, 10)
assert.NoError(t, err)
del1, _, err := staker.GetDelegation(id)
assert.NoError(t, err)
t.Logf("INITIAL: Validator=%s, Stake=%d, LastIteration=%v",
del1.Validation.String(), del1.Stake, del1.LastIteration)
// Step 2: Activate delegation
_, err = staker.Housekeep(validator.Period)
assert.NoError(t, err)
// Step 3: Signal exit
err = staker.SignalDelegationExit(id, validator.Period)
assert.NoError(t, err)
del2, _, err := staker.GetDelegation(id)
assert.NoError(t, err)
t.Logf("AFTER SIGNAL: Validator=%s, Stake=%d, LastIteration=%v",
del2.Validation.String(), del2.Stake, del2.LastIteration)
// Step 4: Complete exit period
_, err = staker.Housekeep(validator.Period * 2)
assert.NoError(t, err)
// Step 5: Withdraw
amount, err := staker.WithdrawDelegation(id, validator.Period*2)
assert.NoError(t, err)
t.Logf("WITHDRAWN: %d VET", amount)
del3, _, err := staker.GetDelegation(id)
assert.NoError(t, err)
t.Logf("AFTER WITHDRAW: Validator=%s, Stake=%d, LastIteration=%v",
del3.Validation.String(), del3.Stake, del3.LastIteration)
// Verify mapping still exists
assert.NotNil(t, del3)
assert.Equal(t, validator.ID, del3.Validation)
assert.Equal(t, uint64(0), del3.Stake)
assert.NotNil(t, del3.LastIteration)
t.Logf("✅ MAPPING PERSISTS AFTER WITHDRAWAL")
}
Looking at the logs you can confirm that: delegationid won't be remove after exit and will direct to the data validator
=== RUN Test_Delegation_Mapping_Persistence
/vechain/thor/builtin/staker/delegations_test.go:765: INITIAL: Validator=0xd24bb0aa2640cca1255148c5e3a89f7ce87adc64, Stake=10000, LastIteration=<nil>
/vechain/thor/builtin/staker/delegations_test.go:778: AFTER SIGNAL: Validator=0xd24bb0aa2640cca1255148c5e3a89f7ce87adc64, Stake=10000, LastIteration=0xc000a0d0c0
/vechain/thor/builtin/staker/delegations_test.go:788: WITHDRAWN: 10000 VET
/vechain/thor/builtin/staker/delegations_test.go:792: AFTER WITHDRAW: Validator=0xd24bb0aa2640cca1255148c5e3a89f7ce87adc64, Stake=0, LastIteration=0xc000a0dba0
/vechain/thor/builtin/staker/delegations_test.go:800: ✅ MAPPING PERSISTS AFTER WITHDRAWAL
--- PASS: Test_Delegation_Mapping_Persistence (0.01s)
PASS
Also confirming that an exiting validator will still be in active state and will just have exitblock overwritten
add this test in delegation_test.go and run it
func Test_Validator_Exit_Status_Logging(t *testing.T) {
staker, validators := newDelegationStaker(t)
validator := validators[0]
stake := delegationStake()
// Add a delegation to the validator
id, err := staker.AddDelegation(validator.ID, stake, 255, 10)
assert.NoError(t, err)
// Activate the delegation via housekeeping
_, err = staker.Housekeep(validator.Period)
assert.NoError(t, err)
// Retrieve initial validator status (should be active)
validation, err := staker.GetValidation(validator.ID)
assert.NoError(t, err)
t.Logf("Initial validator status: %v", validation.Status)
// Signal the validator to exit
assert.NoError(t, staker.SignalExit(validator.ID, validator.Endorser, validator.Period))
// Log status during the exit period (after signaling but before exit completes)
validation, err = staker.GetValidation(validator.ID)
assert.NoError(t, err)
t.Logf("During exit period: Validator status: %v", validation.Status)
// Complete the exit through housekeeping
_, err = staker.Housekeep(validator.Period * 2)
assert.NoError(t, err)
// Log status after the exit period ends
validation, err = staker.GetValidation(validator.ID)
assert.NoError(t, err)
t.Logf("After exit period: Validator status: %v", validation.Status)
// Withdraw the delegation to clean up
amount, err := staker.WithdrawDelegation(id, validator.Period*2 + 10)
assert.NoError(t, err)
assert.Equal(t, stake, amount)
}
Logs:
=== RUN Test_Validator_Exit_Status_Logging
/vechain/thor/builtin/staker/delegations_test.go:820: Initial validator status: 2
/vechain/thor/builtin/staker/delegations_test.go:828: During exit period: Validator status: 2
/vechain/thor/builtin/staker/delegations_test.go:837: After exit period: Validator status: 3
--- PASS: Test_Validator_Exit_Status_Logging (0.01s)
Create a new local.ts inside pakcages/config/ with this data
import { AppConfig } from ".";
const config: AppConfig = {
environment: "local",
basePath: "http://localhost:3000",
ipfsPinningService: "https://api.gateway-proxy.vechain.org/api/v1/pinning/pinFileToIPFS",
ipfsFetchingService: "https://api.gateway-proxy.vechain.org/ipfs",
legacyNodesContractAddress: "0x45d5CA3f295ad8BCa291cC4ecd33382DE40E4FAc",
stargateNFTContractAddress: "0x45d5CA3f295ad8BCa291cC4ecd33382DE40E4FAc",
stargateDelegationContractAddress: "0x45d5CA3f295ad8BCa291cC4ecd33382DE40E4FAc",
nodeManagementContractAddress: "0x45d5CA3f295ad8BCa291cC4ecd33382DE40E4FAc",
stargateContractAddress: "0x00000000000000000000000000005374616B6572",
protocolStakerContractAddress: "0x00000000000000000000000000005374616B6572",
protocolParamsContractAddress: "0x0000000000000000000000000000506172616d73",
indexerUrl: "http://localhost:8080/api/v1",
nodeUrl: "http://localhost:8669",
network: {
id: "solo",
name: "solo",
type: "solo",
defaultNet: true,
urls: [
"http://localhost:8669"
],
explorerUrl: "https://explore-testnet.vechain.org",
blockTime: 10000,
genesis: {
id: "0x0000000089970f535c92d8f2151346f002755b4cf6f7fb4b731317fc6df8ee51"
}
},
cyclePeriods: [
{ value: 18, label: "3 minutes" },
{ value: 180, label: "30 minutes" },
{ value: 8640, label: "1 day" },
],
}
export default config;
Create a new file you can name it DelegationExitBug.test.ts
paste this
import { expect } from "chai";
import { ethers } from "hardhat";
import {
MyERC20,
MyERC20__factory,
ProtocolStakerMock,
ProtocolStakerMock__factory,
Stargate,
StargateNFTMock,
StargateNFTMock__factory,
TokenAuctionMock,
TokenAuctionMock__factory,
} from "../../typechain-types";
import { getOrDeployContracts } from "../../test/helpers/deploy";
import { createLocalConfig } from "@repo/config/contracts/envs/local";
import { ethers as hardhatEthers } from "hardhat";
import { HardhatEthersSigner } from "@nomicfoundation/hardhat-ethers/signers";
import { TransactionResponse } from "ethers";
import { log } from "../../scripts/helpers/log";
describe("Delegation Exit Bug POC", () => {
const VTHO_TOKEN_ADDRESS = "0x0000000000000000000000000000456E65726779";
let stargateContract: Stargate;
let stargateNFTMock: StargateNFTMock;
let protocolStakerMock: ProtocolStakerMock;
let legacyNodesMock: TokenAuctionMock;
let deployer: HardhatEthersSigner;
let user1: HardhatEthersSigner;
let user2: HardhatEthersSigner;
let user3: HardhatEthersSigner; // Second validator
let tx: TransactionResponse;
let vthoTokenContract: MyERC20;
const LEVEL_ID = 1;
const VALIDATOR_STATUS_UNKNOWN = 0;
const VALIDATOR_STATUS_QUEUED = 1;
const VALIDATOR_STATUS_ACTIVE = 2;
const VALIDATOR_STATUS_EXITED = 3;
const DELEGATION_STATUS_NONE = 0;
const DELEGATION_STATUS_PENDING = 1;
const DELEGATION_STATUS_ACTIVE = 2;
const DELEGATION_STATUS_EXITED = 3;
beforeEach(async () => {
const config = createLocalConfig();
[deployer] = await hardhatEthers.getSigners();
// Deploy protocol staker mock
const protocolStakerMockFactory = new ProtocolStakerMock__factory(deployer);
protocolStakerMock = await protocolStakerMockFactory.deploy();
await protocolStakerMock.waitForDeployment();
// Deploy stargateNFT mock
const stargateNFTMockFactory = new StargateNFTMock__factory(deployer);
stargateNFTMock = await stargateNFTMockFactory.deploy();
await stargateNFTMock.waitForDeployment();
// Deploy VTHO token to the energy address
const vthoTokenContractFactory = new MyERC20__factory(deployer);
const tokenContract = await vthoTokenContractFactory.deploy(
deployer.address,
deployer.address
);
await tokenContract.waitForDeployment();
const tokenContractBytecode = await ethers.provider.getCode(tokenContract);
await ethers.provider.send("hardhat_setCode", [VTHO_TOKEN_ADDRESS, tokenContractBytecode]);
// Deploy legacy nodes mock
const legacyNodesMockFactory = new TokenAuctionMock__factory(deployer);
legacyNodesMock = await legacyNodesMockFactory.deploy();
await legacyNodesMock.waitForDeployment();
// Deploy contracts
config.PROTOCOL_STAKER_CONTRACT_ADDRESS = await protocolStakerMock.getAddress();
config.STARGATE_NFT_CONTRACT_ADDRESS = await stargateNFTMock.getAddress();
const contracts = await getOrDeployContracts({ forceDeploy: true, config });
stargateContract = contracts.stargateCont
Attachments are hidden
This information is not publicly available.
Comments are hidden
This information is not publicly available.