Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Split accounts test #258

Merged
merged 3 commits into from
Nov 8, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion staking/programs/staking/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,9 @@ pub enum ErrorCode {
SplitTooManyTokens,
#[msg("Sanity check failed")] // 6033
SanityCheckFailed,
#[msg("Other")] //6031
#[msg("Other")] //6034
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd just move Other to be the last error

Other,
#[msg("Can't split a token account with staking positions. Unstake your tokens first.")]
// 6035
SplitWithStake,
}
20 changes: 8 additions & 12 deletions staking/programs/staking/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -607,6 +607,14 @@ pub mod staking {
config.unlocking_duration,
)?;

// Check that there aren't any positions (i.e., staked tokens) in the source account.
// This check allows us to create an empty positions account on behalf of the recipient and
// not worry about moving positions from the source account to the new account.
require!(
source_stake_account_positions.num_positions()? == 0,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it's better to use source_stake_account_metadata.next_index == 0

ErrorCode::SplitWithStake
);

require!(split_request.amount > 0, ErrorCode::SplitZeroTokens);
require!(
split_request.amount < source_stake_account_custody.amount,
Expand All @@ -626,18 +634,6 @@ pub mod staking {
source_stake_account_metadata.set_lock(source_vesting_account);
new_stake_account_metadata.set_lock(new_vesting_account);

// Split positions
source_stake_account_positions.split(
new_stake_account_positions,
&mut source_stake_account_metadata.next_index,
&mut new_stake_account_metadata.next_index,
remaining_amount,
split_request.amount,
source_stake_account_custody.amount,
current_epoch,
config.unlocking_duration,
)?;


{
transfer(
Expand Down
90 changes: 6 additions & 84 deletions staking/programs/staking/src/state/positions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,92 +115,14 @@ impl PositionData {
Ok(exposure)
}

pub fn split(
&mut self,
dest_position_data: &mut PositionData,
src_next_index: &mut u8,
dest_next_index: &mut u8,
remaining_amount: u64,
transferred_amount: u64,
total_amount: u64,
current_epoch: u64,
unlocking_duration: u8,
) -> Result<()> {
require!(
transferred_amount
.checked_add(remaining_amount)
.ok_or(ErrorCode::Other)?
== total_amount,
ErrorCode::SanityCheckFailed
);
let governance_exposure =
self.get_target_exposure(&Target::VOTING, current_epoch, unlocking_duration)?;
require!(
governance_exposure <= total_amount,
ErrorCode::SanityCheckFailed
);

if remaining_amount < governance_exposure {
// We need to transfer some positions over to the new account
let mut excess_governance_exposure =
governance_exposure.saturating_sub(remaining_amount);

while excess_governance_exposure > 0 && *src_next_index > 0 {
let index = TryInto::<usize>::try_into(*src_next_index - 1)
.map_err(|_| ErrorCode::GenericOverflow)?;
match self.read_position(index)? {
Some(position) => {
match position.get_current_position(current_epoch, unlocking_duration)? {
PositionState::UNLOCKED => self.make_none(index, src_next_index)?,
PositionState::LOCKING
| PositionState::LOCKED
| PositionState::PREUNLOCKING
| PositionState::UNLOCKING => {
if excess_governance_exposure < position.amount {
// We need to split the position
self.write_position(
index,
&Position {
amount: position
.amount
.saturating_sub(excess_governance_exposure),
..position
},
)?;

let new_position = Position {
amount: excess_governance_exposure,
..position
};

let new_index =
dest_position_data.reserve_new_index(dest_next_index)?;
dest_position_data.write_position(new_index, &new_position)?;

excess_governance_exposure = 0;
} else {
// We need to transfer the whole position
let new_index =
dest_position_data.reserve_new_index(dest_next_index)?;
dest_position_data.write_position(new_index, &position)?;

self.make_none(index, src_next_index)?;
excess_governance_exposure =
excess_governance_exposure.saturating_sub(position.amount);
}
}
}
}
None => {
// This should never happen
return Err(error!(ErrorCode::SanityCheckFailed));
}
}
pub fn num_positions(&self) -> Result<usize> {
let mut count: usize = 0;
for i in 0..MAX_POSITIONS {
if let Some(_p) = self.read_position(i)? {
count += 1;
}
}


Ok(())
Ok(count)
}
}

Expand Down
157 changes: 155 additions & 2 deletions staking/programs/staking/src/state/vesting.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ use {
/// Represents how a given initial balance vests over time
/// It is unit-less, but units must be consistent
#[repr(u8)]
#[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone, Copy, BorshSchema)]
#[derive(AnchorSerialize, AnchorDeserialize, Debug, Clone, Copy, BorshSchema, PartialEq)]
pub enum VestingSchedule {
/// No vesting, i.e. balance is fully vested at all time
FullyVested,
Expand Down Expand Up @@ -247,6 +247,10 @@ impl VestingSchedule {
== total_amount,
ErrorCode::SanityCheckFailed
);
// Note that the arithmetic below may lose precision. The calculations round down
// the number of vesting tokens for both of the new accounts, which means that splitting
// may vest some dust (1 of the smallest decimal point) of PYTH for both the source and
// destination accounts.
match self {
VestingSchedule::FullyVested => {
Ok((VestingSchedule::FullyVested, VestingSchedule::FullyVested))
Expand Down Expand Up @@ -299,8 +303,14 @@ pub mod tests {
use {
crate::state::vesting::{
VestingEvent,
VestingSchedule,
VestingSchedule::{
self,
PeriodicVesting,
PeriodicVestingAfterListing,
},
},
quickcheck::TestResult,
quickcheck_macros::quickcheck,
std::convert::TryInto,
};

Expand Down Expand Up @@ -629,4 +639,147 @@ pub mod tests {
None
);
}

#[quickcheck]
fn test_split_with_args(transferred: u64, total: u64, initial_balance: u64) -> TestResult {
if transferred > total || total == 0 {
return TestResult::discard();
}

let schedule = VestingSchedule::FullyVested;
let (remaining_schedule, transferred_schedule) = schedule
.split_vesting_schedule(total - transferred, transferred, total)
.unwrap();

assert_eq!(remaining_schedule, VestingSchedule::FullyVested);
assert_eq!(transferred_schedule, VestingSchedule::FullyVested);

let schedule = PeriodicVesting {
initial_balance,
// all of these fields should be preserved in the result
start_date: 203,
period_duration: 100,
num_periods: 12,
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Perhaps use the parameters we're going to use in the real vesting schedules for this test

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I didn't do this one because it makes the invariant test below much more expensive. I don't think the length of the start_date or duration should matter for the splitting logic though, so i think it's better to have the invariant test and not have this.

};
let (remaining_schedule, transferred_schedule) = schedule
.split_vesting_schedule(total - transferred, transferred, total)
.unwrap();

match (remaining_schedule, transferred_schedule) {
(
PeriodicVesting {
initial_balance: r, ..
Copy link
Contributor

@guibescos guibescos Nov 8, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'd like to see a test that for an arbitrary t
if schedule.get_unvested_balance(t) <= total then
transfered_schedule.get_unvested_balance(t) <= transferred
and transfered_schedule.get_unvested_balance(t) <= total - transferred
This proves that the invariants are preserved by this transformation.

},
PeriodicVesting {
initial_balance: t, ..
},
) => {
let sum = r + t;
assert!(initial_balance.saturating_sub(2) <= sum && sum <= initial_balance);
}
_ => {
panic!("Test failed");
}
}

let schedule = PeriodicVestingAfterListing {
initial_balance,
// all of these fields should be preserved in the result
period_duration: 100,
num_periods: 12,
};
let (remaining_schedule, transferred_schedule) = schedule
.split_vesting_schedule(total - transferred, transferred, total)
.unwrap();

match (remaining_schedule, transferred_schedule) {
(
PeriodicVestingAfterListing {
initial_balance: r, ..
},
PeriodicVestingAfterListing {
initial_balance: t, ..
},
) => {
let sum = r + t;
assert!(initial_balance.saturating_sub(2) <= sum && sum <= initial_balance);
}
_ => {
panic!("Test failed");
}
}

TestResult::passed()
}

fn test_split_helper(
transferred: u64,
total: u64,
initial_balance: u64,
expected_remaining: u64,
expected_transferred: u64,
) {
let schedule = PeriodicVesting {
initial_balance,
// all of these fields should be preserved in the result
start_date: 203,
period_duration: 100,
num_periods: 12,
};
let (remaining_schedule, transferred_schedule) = schedule
.split_vesting_schedule(total - transferred, transferred, total)
.unwrap();

let t = PeriodicVesting {
initial_balance: expected_transferred,
start_date: 203,
period_duration: 100,
num_periods: 12,
};
let r = PeriodicVesting {
initial_balance: expected_remaining,
start_date: 203,
period_duration: 100,
num_periods: 12,
};

assert_eq!(remaining_schedule, r);
assert_eq!(transferred_schedule, t);

let schedule = PeriodicVestingAfterListing {
initial_balance,
period_duration: 100,
num_periods: 12,
};
let (remaining_schedule, transferred_schedule) = schedule
.split_vesting_schedule(total - transferred, transferred, total)
.unwrap();

let t = PeriodicVestingAfterListing {
initial_balance: expected_transferred,
period_duration: 100,
num_periods: 12,
};
let r = PeriodicVestingAfterListing {
initial_balance: expected_remaining,
period_duration: 100,
num_periods: 12,
};

assert_eq!(remaining_schedule, r);
assert_eq!(transferred_schedule, t);
}

#[test]
fn test_split() {
test_split_helper(10, 100, 100, 90, 10);
test_split_helper(10, 1000, 100, 99, 1);
test_split_helper(1, 1000, 100, 99, 0);

test_split_helper(10, 10, 1000, 0, 1000);
test_split_helper(9, 10, 1000, 100, 900);
test_split_helper(10, 100, 1000, 900, 100);

test_split_helper(1, 3, 1000, 666, 333);
}
}
5 changes: 5 additions & 0 deletions staking/target/idl/staking.json
Original file line number Diff line number Diff line change
Expand Up @@ -1916,6 +1916,11 @@
"code": 6034,
"name": "Other",
"msg": "Other"
},
{
"code": 6035,
"name": "SplitWithStake",
"msg": "Can't split a token account with staking positions. Unstake your tokens first."
}
]
}
10 changes: 10 additions & 0 deletions staking/target/types/staking.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1916,6 +1916,11 @@ export type Staking = {
"code": 6034,
"name": "Other",
"msg": "Other"
},
{
"code": 6035,
"name": "SplitWithStake",
"msg": "Can't split a token account with staking positions. Unstake your tokens first."
}
]
};
Expand Down Expand Up @@ -3838,6 +3843,11 @@ export const IDL: Staking = {
"code": 6034,
"name": "Other",
"msg": "Other"
},
{
"code": 6035,
"name": "SplitWithStake",
"msg": "Can't split a token account with staking positions. Unstake your tokens first."
}
]
};
Loading