Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
73 changes: 73 additions & 0 deletions contracts/rewards/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,8 @@ mod poseidon_merkle_tests;
mod poseidon_vs_sha256_bench;
#[cfg(test)]
mod airdrop_test;
#[cfg(test)]
mod pool_rebalance_test;

#[contracterror]
#[derive(Clone, Copy, Debug, Eq, PartialEq, PartialOrd, Ord)]
Expand Down Expand Up @@ -494,6 +496,9 @@ const CAMPAIGN_CAP: Symbol = symbol_short!("campcap");
const CAMPAIGN_ISSUED: Symbol = symbol_short!("campiss");
/// Campaign supply cap set event: topics (campcap, campaign_id), data (cap: u64)
const CAMPAIGN_CAP_EVENT: Symbol = symbol_short!("campcap");
/// Reward pool rebalanced event (#1186): topics (poolrbal, from_campaign, to_campaign),
/// data (amount: u64, from_cap: u64, to_cap: u64) — the caps are post-move values.
const POOL_REBALANCE_EVENT: Symbol = symbol_short!("poolrbal");

// ── Issue #895: Operator delegation constants ────────────────────────────────
/// Operator delegation storage: (OP_DELEGATION, operator, campaign_id) -> OperatorDelegation
Expand Down Expand Up @@ -2837,6 +2842,74 @@ impl RewardsContract {
.unwrap_or(0)
}

/// Unspent reward pool of a capped campaign: `cap - issued` (#1186).
///
/// Returns 0 for uncapped campaigns (cap = 0), which have no bounded pool
/// to rebalance — check `campaign_supply_cap` to tell the two apart.
pub fn campaign_unspent_supply(env: Env, campaign_id: u64) -> u64 {
let cap = Self::campaign_supply_cap(env.clone(), campaign_id);
if cap == 0 {
return 0;
}
cap.saturating_sub(Self::campaign_issued(env, campaign_id))
}

/// Move `amount` of unspent reward pool from one capped campaign to
/// another in the same suite (admin only, #1186).
///
/// Reallocates rewards from an underperforming track to a high-demand one
/// without touching anything already issued: `from_campaign`'s cap drops by
/// `amount` and `to_campaign`'s cap rises by the same amount, so the
/// combined pool of the two campaigns is unchanged.
///
/// # Errors
/// * `Unauthorized` — `admin` is not the stored admin.
/// * `ZeroAmount` — `amount` is 0.
/// * `InvalidSupplyCap` — the campaigns are the same, or either is uncapped.
/// * `CampaignSupplyCapExceeded` — `amount` exceeds `from_campaign`'s
/// unspent pool (`campaign_unspent_supply`).
/// * `Overflow` — `to_campaign`'s cap would overflow `u64`.
pub fn rebalance_campaign_pool(
env: Env,
admin: Address,
from_campaign: u64,
to_campaign: u64,
amount: u64,
) -> Result<(), Error> {
require_admin(&env, &admin)?;
if amount == 0 {
return Err(Error::ZeroAmount);
}
if from_campaign == to_campaign {
return Err(Error::InvalidSupplyCap);
}

let from_cap = Self::campaign_supply_cap(env.clone(), from_campaign);
let to_cap = Self::campaign_supply_cap(env.clone(), to_campaign);
if from_cap == 0 || to_cap == 0 {
return Err(Error::InvalidSupplyCap);
}

let unspent = Self::campaign_unspent_supply(env.clone(), from_campaign);
if amount > unspent {
return Err(Error::CampaignSupplyCapExceeded);
}

let new_from_cap = from_cap - amount; // amount <= unspent <= from_cap
let new_to_cap = to_cap.checked_add(amount).ok_or(Error::Overflow)?;

let storage = env.storage().instance();
storage.set(&(CAMPAIGN_CAP, from_campaign), &new_from_cap);
storage.set(&(CAMPAIGN_CAP, to_campaign), &new_to_cap);
storage.extend_ttl(TTL_THRESHOLD, TTL_EXTEND_TO);

env.events().publish(
(POOL_REBALANCE_EVENT, from_campaign, to_campaign),
(amount, new_from_cap, new_to_cap),
);
Ok(())
}

/// Credit points using campaign multiplier with supply cap enforcement.
/// Extends `credit_for_campaign` to check against the campaign's supply cap.
pub fn credit_for_campaign_capped(
Expand Down
100 changes: 100 additions & 0 deletions contracts/rewards/src/pool_rebalance_test.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
//! Tests for campaign reward pool rebalancing (#1186).
extern crate std;

use super::*;
use soroban_sdk::testutils::Address as _;
use soroban_sdk::{symbol_short, Address, Env};

const FROM: u64 = 1;
const TO: u64 = 2;

fn setup() -> (Env, RewardsContractClient<'static>, Address) {
let env = Env::default();
env.mock_all_auths();
let contract_id = env.register_contract(None, RewardsContract);
let client = RewardsContractClient::new(&env, &contract_id);
let admin = Address::generate(&env);
client.initialize(&admin, &symbol_short!("Trivela"), &symbol_short!("TVL"));
client.set_campaign_supply_cap(&admin, &FROM, &1_000);
client.set_campaign_supply_cap(&admin, &TO, &500);
(env, client, admin)
}

#[test]
fn moves_unspent_pool_between_campaigns() {
let (_env, client, admin) = setup();

client.rebalance_campaign_pool(&admin, &FROM, &TO, &400);

assert_eq!(client.campaign_supply_cap(&FROM), 600);
assert_eq!(client.campaign_supply_cap(&TO), 900);
// Combined pool is conserved.
assert_eq!(
client.campaign_supply_cap(&FROM) + client.campaign_supply_cap(&TO),
1_500
);
}

#[test]
fn cannot_move_already_issued_rewards() {
let (env, client, admin) = setup();
let user = Address::generate(&env);
client.credit_for_campaign_capped(&admin, &user, &FROM, &700);
assert_eq!(client.campaign_unspent_supply(&FROM), 300);

assert_eq!(
client.try_rebalance_campaign_pool(&admin, &FROM, &TO, &301),
Err(Ok(Error::CampaignSupplyCapExceeded))
);

client.rebalance_campaign_pool(&admin, &FROM, &TO, &300);
assert_eq!(client.campaign_unspent_supply(&FROM), 0);
assert_eq!(client.campaign_supply_cap(&FROM), 700);
assert_eq!(client.campaign_issued(&FROM), 700);
assert_eq!(client.campaign_unspent_supply(&TO), 800);
}

#[test]
fn rejects_zero_same_and_uncapped_campaigns() {
let (_env, client, admin) = setup();

assert_eq!(
client.try_rebalance_campaign_pool(&admin, &FROM, &TO, &0),
Err(Ok(Error::ZeroAmount))
);
assert_eq!(
client.try_rebalance_campaign_pool(&admin, &FROM, &FROM, &10),
Err(Ok(Error::InvalidSupplyCap))
);
// Campaign 3 is uncapped, in either direction.
assert_eq!(
client.try_rebalance_campaign_pool(&admin, &FROM, &3, &10),
Err(Ok(Error::InvalidSupplyCap))
);
assert_eq!(
client.try_rebalance_campaign_pool(&admin, &3, &TO, &10),
Err(Ok(Error::InvalidSupplyCap))
);
assert_eq!(client.campaign_unspent_supply(&3), 0);
}

#[test]
fn rejects_non_admin() {
let (env, client, _admin) = setup();
let stranger = Address::generate(&env);
assert_eq!(
client.try_rebalance_campaign_pool(&stranger, &FROM, &TO, &10),
Err(Ok(Error::Unauthorized))
);
assert_eq!(client.campaign_supply_cap(&FROM), 1_000);
}

#[test]
fn rejects_destination_cap_overflow() {
let (_env, client, admin) = setup();
client.set_campaign_supply_cap(&admin, &TO, &u64::MAX);
assert_eq!(
client.try_rebalance_campaign_pool(&admin, &FROM, &TO, &1),
Err(Ok(Error::Overflow))
);
}
Loading