Skip to main content

Module 0x3::staking_pool

use 0x1::option;
use 0x1::u64;
use 0x2::bag;
use 0x2::balance;
use 0x2::object;
use 0x2::sui;
use 0x2::table;
use 0x2::transfer;
use 0x2::tx_context;

Resource StakingPool

A staking pool embedded in each validator struct in the system state object.

struct StakingPool has store, key
Fields
id: object::UID
activation_epoch: option::Option<u64>
The epoch at which this pool became active. The value is None if the pool is pre-active and Some(<epoch_number>) if active or inactive.
deactivation_epoch: option::Option<u64>
The epoch at which this staking pool ceased to be active. None = {pre-active, active}, Some(<epoch_number>) if in-active, and it was de-activated at epoch <epoch_number>.
sui_balance: u64
The total number of SUI tokens in this pool, including the SUI in the rewards_pool, as well as in all the principal in the StakedSui object, updated at epoch boundaries.
rewards_pool: balance::Balance<sui::SUI>
The epoch stake rewards will be added here at the end of each epoch.
pool_token_balance: u64
Total number of pool tokens issued by the pool.
exchange_rates: table::Table<u64, staking_pool::PoolTokenExchangeRate>
Exchange rate history of previous epochs. Key is the epoch number. The entries start from the activation_epoch of this pool and contains exchange rates at the beginning of each epoch, i.e., right after the rewards for the previous epoch have been deposited into the pool.
pending_stake: u64
Pending stake amount for this epoch, emptied at epoch boundaries.
pending_total_sui_withdraw: u64
Pending stake withdrawn during the current epoch, emptied at epoch boundaries. This includes both the principal and rewards SUI withdrawn.
pending_pool_token_withdraw: u64
Pending pool token withdrawn during the current epoch, emptied at epoch boundaries.
extra_fields: bag::Bag
Any extra fields that's not defined statically.

Struct PoolTokenExchangeRate

Struct representing the exchange rate of the stake pool token to SUI.

struct PoolTokenExchangeRate has copy, drop, store
Fields
sui_amount: u64
pool_token_amount: u64

Resource StakedSui

A self-custodial object holding the staked SUI tokens.

struct StakedSui has store, key
Fields
id: object::UID
pool_id: object::ID
ID of the staking pool we are staking with.
stake_activation_epoch: u64
The epoch at which the stake becomes active.
principal: balance::Balance<sui::SUI>
The staked SUI tokens.

Constants

const EActivationOfInactivePool: u64 = 16;

const EDeactivationOfInactivePool: u64 = 11;

const EDelegationOfZeroSui: u64 = 17;

const EDelegationToInactivePool: u64 = 10;

const EDestroyNonzeroBalance: u64 = 5;

const EIncompatibleStakedSui: u64 = 12;

const EInsufficientPoolTokenBalance: u64 = 0;

const EInsufficientRewardsPoolBalance: u64 = 4;

const EInsufficientSuiTokenBalance: u64 = 3;

const EPendingDelegationDoesNotExist: u64 = 8;

const EPoolAlreadyActive: u64 = 14;

const EPoolNotPreactive: u64 = 15;

const EStakedSuiBelowThreshold: u64 = 18;

const ETokenBalancesDoNotMatchExchangeRate: u64 = 9;

const ETokenTimeLockIsSome: u64 = 6;

const EWithdrawAmountCannotBeZero: u64 = 2;

const EWithdrawalInSameEpoch: u64 = 13;

const EWrongDelegation: u64 = 7;

const EWrongPool: u64 = 1;

StakedSui objects cannot be split to below this amount.

const MIN_STAKING_THRESHOLD: u64 = 1000000000;

Function new

Create a new, empty staking pool.

public(friend) fun new(ctx: &mut tx_context::TxContext): staking_pool::StakingPool
Implementation
public(package) fun new(ctx: &mut TxContext) : StakingPool {
    let exchange_rates = table::new(ctx);
    StakingPool {
        id: object::new(ctx),
        activation_epoch: option::none(),
        deactivation_epoch: option::none(),
        sui_balance: 0,
        rewards_pool: balance::zero(),
        pool_token_balance: 0,
        exchange_rates,
        pending_stake: 0,
        pending_total_sui_withdraw: 0,
        pending_pool_token_withdraw: 0,
        extra_fields: bag::new(ctx),
    }
}

Function request_add_stake

Request to stake to a staking pool. The stake starts counting at the beginning of the next epoch,

public(friend) fun request_add_stake(pool: &mut staking_pool::StakingPool, stake: balance::Balance<sui::SUI>, stake_activation_epoch: u64, ctx: &mut tx_context::TxContext): staking_pool::StakedSui
Implementation
public(package) fun request_add_stake(
    pool: &mut StakingPool,
    stake: Balance<SUI>,
    stake_activation_epoch: u64,
    ctx: &mut TxContext
) : StakedSui {
    let sui_amount = stake.value();
    assert!(!is_inactive(pool), EDelegationToInactivePool);
    assert!(sui_amount > 0, EDelegationOfZeroSui);
    let staked_sui = StakedSui {
        id: object::new(ctx),
        pool_id: object::id(pool),
        stake_activation_epoch,
        principal: stake,
    };
    pool.pending_stake = pool.pending_stake + sui_amount;
    staked_sui
}

Function request_withdraw_stake

Request to withdraw the given stake plus rewards from a staking pool. Both the principal and corresponding rewards in SUI are withdrawn. A proportional amount of pool token withdraw is recorded and processed at epoch change time.

public(friend) fun request_withdraw_stake(pool: &mut staking_pool::StakingPool, staked_sui: staking_pool::StakedSui, ctx: &tx_context::TxContext): balance::Balance<sui::SUI>
Implementation
public(package) fun request_withdraw_stake(
    pool: &mut StakingPool,
    staked_sui: StakedSui,
    ctx: &TxContext
) : Balance<SUI> {
    let (pool_token_withdraw_amount, mut principal_withdraw) =
        withdraw_from_principal(pool, staked_sui);
    let principal_withdraw_amount = principal_withdraw.value();

    let rewards_withdraw = withdraw_rewards(
        pool, principal_withdraw_amount, pool_token_withdraw_amount, ctx.epoch()
    );
    let total_sui_withdraw_amount = principal_withdraw_amount + rewards_withdraw.value();

    pool.pending_total_sui_withdraw = pool.pending_total_sui_withdraw + total_sui_withdraw_amount;
    pool.pending_pool_token_withdraw = pool.pending_pool_token_withdraw + pool_token_withdraw_amount;

    // If the pool is inactive, we immediately process the withdrawal.
    if (is_inactive(pool)) process_pending_stake_withdraw(pool);

    // TODO: implement withdraw bonding period here.
    principal_withdraw.join(rewards_withdraw);
    principal_withdraw
}

Function withdraw_from_principal

Withdraw the principal SUI stored in the StakedSui object, and calculate the corresponding amount of pool tokens using exchange rate at staking epoch. Returns values are amount of pool tokens withdrawn and withdrawn principal portion of SUI.

public(friend) fun withdraw_from_principal(pool: &staking_pool::StakingPool, staked_sui: staking_pool::StakedSui): (u64, balance::Balance<sui::SUI>)
Implementation
public(package) fun withdraw_from_principal(
    pool: &StakingPool,
    staked_sui: StakedSui,
) : (u64, Balance<SUI>) {

    // Check that the stake information matches the pool.
    assert!(staked_sui.pool_id == object::id(pool), EWrongPool);

    let exchange_rate_at_staking_epoch = pool_token_exchange_rate_at_epoch(pool, staked_sui.stake_activation_epoch);
    let principal_withdraw = unwrap_staked_sui(staked_sui);
    let pool_token_withdraw_amount = get_token_amount(
		&exchange_rate_at_staking_epoch,
		principal_withdraw.value()
	);

    (
        pool_token_withdraw_amount,
        principal_withdraw,
    )
}

Function unwrap_staked_sui

fun unwrap_staked_sui(staked_sui: staking_pool::StakedSui): balance::Balance<sui::SUI>
Implementation
fun unwrap_staked_sui(staked_sui: StakedSui): Balance<SUI> {
    let StakedSui {
        id,
        pool_id: _,
        stake_activation_epoch: _,
        principal,
    } = staked_sui;
    object::delete(id);
    principal
}

Function deposit_rewards

Called at epoch advancement times to add rewards (in SUI) to the staking pool.

public(friend) fun deposit_rewards(pool: &mut staking_pool::StakingPool, rewards: balance::Balance<sui::SUI>)
Implementation
public(package) fun deposit_rewards(pool: &mut StakingPool, rewards: Balance<SUI>) {
    pool.sui_balance = pool.sui_balance + rewards.value();
    pool.rewards_pool.join(rewards);
}

Function process_pending_stakes_and_withdraws

public(friend) fun process_pending_stakes_and_withdraws(pool: &mut staking_pool::StakingPool, ctx: &tx_context::TxContext)
Implementation
public(package) fun process_pending_stakes_and_withdraws(pool: &mut StakingPool, ctx: &TxContext) {
    let new_epoch = ctx.epoch() + 1;
    process_pending_stake_withdraw(pool);
    process_pending_stake(pool);
    pool.exchange_rates.add(
        new_epoch,
        PoolTokenExchangeRate { sui_amount: pool.sui_balance, pool_token_amount: pool.pool_token_balance },
    );
    check_balance_invariants(pool, new_epoch);
}

Function process_pending_stake_withdraw

Called at epoch boundaries to process pending stake withdraws requested during the epoch. Also called immediately upon withdrawal if the pool is inactive.

fun process_pending_stake_withdraw(pool: &mut staking_pool::StakingPool)
Implementation
fun process_pending_stake_withdraw(pool: &mut StakingPool) {
    pool.sui_balance = pool.sui_balance - pool.pending_total_sui_withdraw;
    pool.pool_token_balance = pool.pool_token_balance - pool.pending_pool_token_withdraw;
    pool.pending_total_sui_withdraw = 0;
    pool.pending_pool_token_withdraw = 0;
}

Function process_pending_stake

Called at epoch boundaries to process the pending stake.

public(friend) fun process_pending_stake(pool: &mut staking_pool::StakingPool)
Implementation
public(package) fun process_pending_stake(pool: &mut StakingPool) {
    // Use the most up to date exchange rate with the rewards deposited and withdraws effectuated.
    let latest_exchange_rate =
        PoolTokenExchangeRate { sui_amount: pool.sui_balance, pool_token_amount: pool.pool_token_balance };
    pool.sui_balance = pool.sui_balance + pool.pending_stake;
    pool.pool_token_balance = get_token_amount(&latest_exchange_rate, pool.sui_balance);
    pool.pending_stake = 0;
}

Function withdraw_rewards

This function does the following:

  1. Calculates the total amount of SUI (including principal and rewards) that the provided pool tokens represent at the current exchange rate.
  2. Using the above number and the given principal_withdraw_amount, calculates the rewards portion of the stake we should withdraw.
  3. Withdraws the rewards portion from the rewards pool at the current exchange rate. We only withdraw the rewards portion because the principal portion was already taken out of the staker's self custodied StakedSui.
fun withdraw_rewards(pool: &mut staking_pool::StakingPool, principal_withdraw_amount: u64, pool_token_withdraw_amount: u64, epoch: u64): balance::Balance<sui::SUI>
Implementation
fun withdraw_rewards(
    pool: &mut StakingPool,
    principal_withdraw_amount: u64,
    pool_token_withdraw_amount: u64,
    epoch: u64,
) : Balance<SUI> {
    let exchange_rate = pool_token_exchange_rate_at_epoch(pool, epoch);
    let total_sui_withdraw_amount = get_sui_amount(&exchange_rate, pool_token_withdraw_amount);
    let mut reward_withdraw_amount =
        if (total_sui_withdraw_amount >= principal_withdraw_amount)
            total_sui_withdraw_amount - principal_withdraw_amount
        else 0;
    // This may happen when we are withdrawing everything from the pool and
    // the rewards pool balance may be less than reward_withdraw_amount.
    // TODO: FIGURE OUT EXACTLY WHY THIS CAN HAPPEN.
    reward_withdraw_amount = reward_withdraw_amount.min(pool.rewards_pool.value());
    pool.rewards_pool.split(reward_withdraw_amount)
}

Function activate_staking_pool

Called by validator module to activate a staking pool.

public(friend) fun activate_staking_pool(pool: &mut staking_pool::StakingPool, activation_epoch: u64)
Implementation
public(package) fun activate_staking_pool(pool: &mut StakingPool, activation_epoch: u64) {
    // Add the initial exchange rate to the table.
    pool.exchange_rates.add(
        activation_epoch,
        initial_exchange_rate()
    );
    // Check that the pool is preactive and not inactive.
    assert!(is_preactive(pool), EPoolAlreadyActive);
    assert!(!is_inactive(pool), EActivationOfInactivePool);
    // Fill in the active epoch.
    pool.activation_epoch.fill(activation_epoch);
}

Function deactivate_staking_pool

Deactivate a staking pool by setting the deactivation_epoch. After this pool deactivation, the pool stops earning rewards. Only stake withdraws can be made to the pool.

public(friend) fun deactivate_staking_pool(pool: &mut staking_pool::StakingPool, deactivation_epoch: u64)
Implementation
public(package) fun deactivate_staking_pool(pool: &mut StakingPool, deactivation_epoch: u64) {
    // We can't deactivate an already deactivated pool.
    assert!(!is_inactive(pool), EDeactivationOfInactivePool);
    pool.deactivation_epoch = option::some(deactivation_epoch);
}

Function sui_balance

public fun sui_balance(pool: &staking_pool::StakingPool): u64
Implementation
public fun sui_balance(pool: &StakingPool): u64 { pool.sui_balance }

Function pool_id

public fun pool_id(staked_sui: &staking_pool::StakedSui): object::ID
Implementation
public fun pool_id(staked_sui: &StakedSui): ID { staked_sui.pool_id }

Function staked_sui_amount

public fun staked_sui_amount(staked_sui: &staking_pool::StakedSui): u64
Implementation
public fun staked_sui_amount(staked_sui: &StakedSui): u64 { staked_sui.principal.value() }

Function stake_activation_epoch

public fun stake_activation_epoch(staked_sui: &staking_pool::StakedSui): u64
Implementation
public fun stake_activation_epoch(staked_sui: &StakedSui): u64 {
    staked_sui.stake_activation_epoch
}

Function is_preactive

Returns true if the input staking pool is preactive.

public fun is_preactive(pool: &staking_pool::StakingPool): bool
Implementation
public fun is_preactive(pool: &StakingPool): bool{
    pool.activation_epoch.is_none()
}

Function is_inactive

Returns true if the input staking pool is inactive.

public fun is_inactive(pool: &staking_pool::StakingPool): bool
Implementation
public fun is_inactive(pool: &StakingPool): bool {
    pool.deactivation_epoch.is_some()
}

Function split

Split StakedSui self to two parts, one with principal split_amount, and the remaining principal is left in self. All the other parameters of the StakedSui like stake_activation_epoch or pool_id remain the same.

public fun split(self: &mut staking_pool::StakedSui, split_amount: u64, ctx: &mut tx_context::TxContext): staking_pool::StakedSui
Implementation
public fun split(self: &mut StakedSui, split_amount: u64, ctx: &mut TxContext): StakedSui {
    let original_amount = self.principal.value();
    assert!(split_amount <= original_amount, EInsufficientSuiTokenBalance);
    let remaining_amount = original_amount - split_amount;
    // Both resulting parts should have at least MIN_STAKING_THRESHOLD.
    assert!(remaining_amount >= MIN_STAKING_THRESHOLD, EStakedSuiBelowThreshold);
    assert!(split_amount >= MIN_STAKING_THRESHOLD, EStakedSuiBelowThreshold);
    StakedSui {
        id: object::new(ctx),
        pool_id: self.pool_id,
        stake_activation_epoch: self.stake_activation_epoch,
        principal: self.principal.split(split_amount),
    }
}

Function split_staked_sui

Split the given StakedSui to the two parts, one with principal split_amount, transfer the newly split part to the sender address.

public entry fun split_staked_sui(stake: &mut staking_pool::StakedSui, split_amount: u64, ctx: &mut tx_context::TxContext)
Implementation
public entry fun split_staked_sui(stake: &mut StakedSui, split_amount: u64, ctx: &mut TxContext) {
    transfer::transfer(split(stake, split_amount, ctx), ctx.sender());
}

Function join_staked_sui

Consume the staked sui other and add its value to self. Aborts if some of the staking parameters are incompatible (pool id, stake activation epoch, etc.)

public entry fun join_staked_sui(self: &mut staking_pool::StakedSui, other: staking_pool::StakedSui)
Implementation
public entry fun join_staked_sui(self: &mut StakedSui, other: StakedSui) {
    assert!(is_equal_staking_metadata(self, &other), EIncompatibleStakedSui);
    let StakedSui {
        id,
        pool_id: _,
        stake_activation_epoch: _,
        principal,
    } = other;

    id.delete();
    self.principal.join(principal);
}

Function is_equal_staking_metadata

Returns true if all the staking parameters of the staked sui except the principal are identical

public fun is_equal_staking_metadata(self: &staking_pool::StakedSui, other: &staking_pool::StakedSui): bool
Implementation
public fun is_equal_staking_metadata(self: &StakedSui, other: &StakedSui): bool {
    (self.pool_id == other.pool_id) &&
    (self.stake_activation_epoch == other.stake_activation_epoch)
}

Function pool_token_exchange_rate_at_epoch

public fun pool_token_exchange_rate_at_epoch(pool: &staking_pool::StakingPool, epoch: u64): staking_pool::PoolTokenExchangeRate
Implementation
public fun pool_token_exchange_rate_at_epoch(pool: &StakingPool, epoch: u64): PoolTokenExchangeRate {
    // If the pool is preactive then the exchange rate is always 1:1.
    if (is_preactive_at_epoch(pool, epoch)) {
        return initial_exchange_rate()
    };
    let clamped_epoch = pool.deactivation_epoch.get_with_default(epoch);
    let mut epoch = clamped_epoch.min(epoch);
    let activation_epoch = *pool.activation_epoch.borrow();

    // Find the latest epoch that's earlier than the given epoch with an entry in the table
    while (epoch >= activation_epoch) {
        if (pool.exchange_rates.contains(epoch)) {
            return pool.exchange_rates[epoch]
        };
        epoch = epoch - 1;
    };
    // This line really should be unreachable. Do we want an assert false here?
    initial_exchange_rate()
}

Function pending_stake_amount

Returns the total value of the pending staking requests for this staking pool.

public fun pending_stake_amount(staking_pool: &staking_pool::StakingPool): u64
Implementation
public fun pending_stake_amount(staking_pool: &StakingPool): u64 {
    staking_pool.pending_stake
}

Function pending_stake_withdraw_amount

Returns the total withdrawal from the staking pool this epoch.

public fun pending_stake_withdraw_amount(staking_pool: &staking_pool::StakingPool): u64
Implementation
public fun pending_stake_withdraw_amount(staking_pool: &StakingPool): u64 {
    staking_pool.pending_total_sui_withdraw
}

Function exchange_rates

public(friend) fun exchange_rates(pool: &staking_pool::StakingPool): &table::Table<u64, staking_pool::PoolTokenExchangeRate>
Implementation
public(package) fun exchange_rates(pool: &StakingPool): &Table<u64, PoolTokenExchangeRate> {
    &pool.exchange_rates
}

Function sui_amount

public fun sui_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate): u64
Implementation
public fun sui_amount(exchange_rate: &PoolTokenExchangeRate): u64 {
    exchange_rate.sui_amount
}

Function pool_token_amount

public fun pool_token_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate): u64
Implementation
public fun pool_token_amount(exchange_rate: &PoolTokenExchangeRate): u64 {
    exchange_rate.pool_token_amount
}

Function is_preactive_at_epoch

Returns true if the provided staking pool is preactive at the provided epoch.

fun is_preactive_at_epoch(pool: &staking_pool::StakingPool, epoch: u64): bool
Implementation
fun is_preactive_at_epoch(pool: &StakingPool, epoch: u64): bool{
    // Either the pool is currently preactive or the pool's starting epoch is later than the provided epoch.
    is_preactive(pool) || (*pool.activation_epoch.borrow() > epoch)
}

Function get_sui_amount

fun get_sui_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate, token_amount: u64): u64
Implementation
fun get_sui_amount(exchange_rate: &PoolTokenExchangeRate, token_amount: u64): u64 {
    // When either amount is 0, that means we have no stakes with this pool.
    // The other amount might be non-zero when there's dust left in the pool.
    if (exchange_rate.sui_amount == 0 || exchange_rate.pool_token_amount == 0) {
        return token_amount
    };
    let res = exchange_rate.sui_amount as u128
            * (token_amount as u128)
            / (exchange_rate.pool_token_amount as u128);
    res as u64
}

Function get_token_amount

fun get_token_amount(exchange_rate: &staking_pool::PoolTokenExchangeRate, sui_amount: u64): u64
Implementation
fun get_token_amount(exchange_rate: &PoolTokenExchangeRate, sui_amount: u64): u64 {
    // When either amount is 0, that means we have no stakes with this pool.
    // The other amount might be non-zero when there's dust left in the pool.
    if (exchange_rate.sui_amount == 0 || exchange_rate.pool_token_amount == 0) {
        return sui_amount
    };
    let res = exchange_rate.pool_token_amount as u128
            * (sui_amount as u128)
            / (exchange_rate.sui_amount as u128);
    res as u64
}

Function initial_exchange_rate

fun initial_exchange_rate(): staking_pool::PoolTokenExchangeRate
Implementation
fun initial_exchange_rate(): PoolTokenExchangeRate {
    PoolTokenExchangeRate { sui_amount: 0, pool_token_amount: 0 }
}

Function check_balance_invariants

fun check_balance_invariants(pool: &staking_pool::StakingPool, epoch: u64)
Implementation
fun check_balance_invariants(pool: &StakingPool, epoch: u64) {
    let exchange_rate = pool_token_exchange_rate_at_epoch(pool, epoch);
    // check that the pool token balance and sui balance ratio matches the exchange rate stored.
    let expected = get_token_amount(&exchange_rate, pool.sui_balance);
    let actual = pool.pool_token_balance;
    assert!(expected == actual, ETokenBalancesDoNotMatchExchangeRate)
}