|
1 | 1 | use crate::{
|
2 | 2 | error::LendingError,
|
3 | 3 | math::{Decimal, TryAdd, TryDiv, TryMul, TrySub},
|
| 4 | + state::unpack_decimal, |
| 5 | +}; |
| 6 | +use arrayref::{array_mut_ref, array_ref, array_refs, mut_array_refs}; |
| 7 | +use solana_program::program_pack::{Pack, Sealed}; |
| 8 | +use solana_program::{ |
| 9 | + clock::Clock, |
| 10 | + program_error::ProgramError, |
| 11 | + pubkey::{Pubkey, PUBKEY_BYTES}, |
4 | 12 | };
|
5 |
| -use solana_program::{clock::Clock, program_error::ProgramError, pubkey::Pubkey}; |
6 | 13 |
|
7 |
| -/// Cannot create a reward shorter than this. |
8 |
| -pub const MIN_REWARD_PERIOD_SECS: u64 = 3_600; |
| 14 | +use super::pack_decimal; |
9 | 15 |
|
10 | 16 | /// Determines the size of [PoolRewardManager]
|
11 |
| -/// TODO: This should be configured when we're dealing with migrations later but we should aim for 50. |
12 |
| -const MAX_REWARDS: usize = 44; |
| 17 | +const MAX_REWARDS: usize = 50; |
| 18 | + |
| 19 | +/// Cannot create a reward shorter than this. |
| 20 | +pub const MIN_REWARD_PERIOD_SECS: u64 = 3_600; |
13 | 21 |
|
14 | 22 | /// Each reserve has two managers:
|
15 | 23 | /// - one for deposits
|
16 | 24 | /// - one for borrows
|
| 25 | +#[derive(Clone, Debug, PartialEq)] |
17 | 26 | pub struct PoolRewardManager {
|
18 | 27 | /// Is updated when we change user shares in the reserve.
|
19 | 28 | pub total_shares: u64,
|
|
46 | 55 | /// reward is vacant or not to save space.
|
47 | 56 | ///
|
48 | 57 | /// If the pubkey is eq to default pubkey then slot is vacant.
|
| 58 | +#[derive(Clone, Debug, PartialEq)] |
49 | 59 | pub enum PoolRewardSlot {
|
50 | 60 | /// New reward can be added to this slot.
|
51 | 61 | Vacant {
|
52 | 62 | /// Increment this ID when adding new [PoolReward].
|
53 | 63 | last_pool_reward_id: PoolRewardId,
|
54 | 64 | },
|
55 | 65 | /// Reward has not been closed yet.
|
56 |
| - Occupied(PoolReward), |
| 66 | + /// |
| 67 | + /// We box the [PoolReward] to avoid stack overflow. |
| 68 | + Occupied(Box<PoolReward>), |
57 | 69 | }
|
58 | 70 |
|
59 | 71 | /// Tracks rewards in a specific mint over some period of time.
|
| 72 | +/// |
| 73 | +/// # Reward cancellation |
| 74 | +/// In Suilend we also store the amount of rewards that have been made available |
| 75 | +/// to users already. |
| 76 | +/// We keep adding `(total_rewards * time_passed) / (total_time)` every |
| 77 | +/// time someone interacts with the manager. |
| 78 | +/// This value is used to transfer the unallocated rewards to the admin. |
| 79 | +/// However, this can be calculated dynamically which avoids storing extra |
| 80 | +/// [Decimal] on each [PoolReward]. |
| 81 | +#[derive(Clone, Debug, Default, PartialEq)] |
60 | 82 | pub struct PoolReward {
|
61 | 83 | /// Unique ID for this slot that has never been used before, and will never
|
62 | 84 | /// be used again.
|
|
77 | 99 | /// There's a permission-less ix with which user rewards can be distributed
|
78 | 100 | /// that's used for cranking remaining rewards.
|
79 | 101 | pub num_user_reward_managers: u64,
|
80 |
| - /// Amount of rewards that have been made available to users. |
81 |
| - /// |
82 |
| - /// We keep adding `(total_rewards * time_passed) / (total_time)` every |
83 |
| - /// time someone interacts with the manager |
84 |
| - /// ([update_pool_reward_manager]). |
85 |
| - pub allocated_rewards: Decimal, |
86 | 102 | /// We keep adding `(unlocked_rewards) / (total_shares)` every time
|
87 | 103 | /// someone interacts with the manager ([update_pool_reward_manager])
|
88 | 104 | /// where
|
89 | 105 | /// `unlocked_rewards = (total_rewards * time_passed) / (total_time)`
|
| 106 | + /// |
| 107 | + /// # (Un)Packing |
| 108 | + /// We only store 16 most significant digits. |
90 | 109 | pub cumulative_rewards_per_share: Decimal,
|
91 | 110 | }
|
92 | 111 |
|
|
135 | 154 |
|
136 | 155 | impl PoolRewardManager {
|
137 | 156 | /// Should be updated before any interaction with rewards.
|
138 | 157 | fn update(&mut self, clock: &Clock) -> Result<(), ProgramError> {
|
139 | 158 | let curr_unix_timestamp_secs = clock.unix_timestamp as u64;
|
140 | 159 |
|
141 | 160 | if self.last_update_time_secs >= curr_unix_timestamp_secs {
|
|
173 | 192 | .try_mul(Decimal::from(time_passed_secs))?
|
174 | 193 | .try_div(Decimal::from(end_time_secs - reward.start_time_secs))?;
|
175 | 194 |
|
176 |
| - reward.allocated_rewards = reward.allocated_rewards.try_add(unlocked_rewards)?; |
177 |
| - |
178 | 195 | reward.cumulative_rewards_per_share = reward
|
179 | 196 | .cumulative_rewards_per_share
|
180 | 197 | .try_add(unlocked_rewards.try_div(Decimal::from(self.total_shares))?)?;
|
|
186 | 203 | }
|
187 | 204 | }
|
188 | 205 |
|
189 | 206 | enum CreatingNewUserRewardManager {
|
190 | 207 | /// If we are creating a [UserRewardManager] then we want to populate it.
|
191 | 208 | Yes,
|
192 | 209 | No,
|
|
198 | 215 | /// # Assumption
|
199 | 216 | /// Invoker has checked that this [PoolRewardManager] matches the
|
200 | 217 | /// [UserRewardManager].
|
201 | 218 | fn update(
|
202 | 219 | &mut self,
|
203 | 220 | pool_reward_manager: &mut PoolRewardManager,
|
204 | 221 | clock: &Clock,
|
|
280 | 297 | }
|
281 | 298 | }
|
282 | 299 |
|
| 300 | +impl PoolReward { |
| 301 | + const LEN: usize = PoolRewardId::LEN + PUBKEY_BYTES + 8 + 4 + 8 + 8 + 16; |
| 302 | +} |
| 303 | + |
| 304 | +impl PoolRewardId { |
| 305 | + const LEN: usize = std::mem::size_of::<Self>(); |
| 306 | +} |
| 307 | + |
| 308 | +impl Default for PoolRewardManager { |
| 309 | + fn default() -> Self { |
| 310 | + Self { |
| 311 | + total_shares: 0, |
| 312 | + last_update_time_secs: 0, |
| 313 | + pool_rewards: std::array::from_fn(|_| PoolRewardSlot::default()), |
| 314 | + } |
| 315 | + } |
| 316 | +} |
| 317 | + |
| 318 | +impl Default for PoolRewardSlot { |
| 319 | + fn default() -> Self { |
| 320 | + Self::Vacant { |
| 321 | + last_pool_reward_id: PoolRewardId(0), |
| 322 | + } |
| 323 | + } |
| 324 | +} |
| 325 | + |
| 326 | +impl PoolRewardManager { |
| 327 | + #[inline(never)] |
| 328 | + pub(crate) fn unpack_to_box(input: &[u8]) -> Result<Box<Self>, ProgramError> { |
| 329 | + Ok(Box::new(PoolRewardManager::unpack_from_slice(input)?)) |
| 330 | + } |
| 331 | +} |
| 332 | + |
| 333 | +impl Sealed for PoolRewardManager {} |
| 334 | + |
| 335 | +impl Pack for PoolRewardManager { |
| 336 | + /// total_shares + last_update_time_secs + pool_rewards. |
| 337 | + const LEN: usize = 8 + 8 + MAX_REWARDS * PoolReward::LEN; |
| 338 | + |
| 339 | + fn pack_into_slice(&self, output: &mut [u8]) { |
| 340 | + output[0..8].copy_from_slice(&self.total_shares.to_le_bytes()); |
| 341 | + output[8..16].copy_from_slice(&self.last_update_time_secs.to_le_bytes()); |
| 342 | + |
| 343 | + for (index, pool_reward_slot) in self.pool_rewards.iter().enumerate() { |
| 344 | + let offset = 16 + index * PoolReward::LEN; |
| 345 | + let raw_pool_reward = array_mut_ref![output, offset, PoolReward::LEN]; |
| 346 | + |
| 347 | + let ( |
| 348 | + dst_id, |
| 349 | + dst_vault, |
| 350 | + dst_start_time_secs, |
| 351 | + dst_duration_secs, |
| 352 | + dst_total_rewards, |
| 353 | + dst_num_user_reward_managers, |
| 354 | + dst_cumulative_rewards_per_share_wads, |
| 355 | + ) = mut_array_refs![ |
| 356 | + raw_pool_reward, |
| 357 | + PoolRewardId::LEN, |
| 358 | + PUBKEY_BYTES, |
| 359 | + 8, // start_time_secs |
| 360 | + 4, // duration_secs |
| 361 | + 8, // total_rewards |
| 362 | + 8, // num_user_reward_managers |
| 363 | + 16 // cumulative_rewards_per_share |
| 364 | + ]; |
| 365 | + |
| 366 | + let ( |
| 367 | + id, |
| 368 | + vault, |
| 369 | + start_time_secs, |
| 370 | + duration_secs, |
| 371 | + total_rewards, |
| 372 | + num_user_reward_managers, |
| 373 | + cumulative_rewards_per_share, |
| 374 | + ) = match pool_reward_slot { |
| 375 | + PoolRewardSlot::Vacant { |
| 376 | + last_pool_reward_id, |
| 377 | + } => ( |
| 378 | + *last_pool_reward_id, |
| 379 | + Pubkey::default(), |
| 380 | + 0u64, |
| 381 | + 0u32, |
| 382 | + 0u64, |
| 383 | + 0u64, |
| 384 | + Decimal::zero(), |
| 385 | + ), |
| 386 | + PoolRewardSlot::Occupied(pool_reward) => ( |
| 387 | + pool_reward.id, |
| 388 | + pool_reward.vault, |
| 389 | + pool_reward.start_time_secs, |
| 390 | + pool_reward.duration_secs, |
| 391 | + pool_reward.total_rewards, |
| 392 | + pool_reward.num_user_reward_managers, |
| 393 | + pool_reward.cumulative_rewards_per_share, |
| 394 | + ), |
| 395 | + }; |
| 396 | + |
| 397 | + dst_id.copy_from_slice(&id.0.to_le_bytes()); |
| 398 | + dst_vault.copy_from_slice(vault.as_ref()); |
| 399 | + *dst_start_time_secs = start_time_secs.to_le_bytes(); |
| 400 | + *dst_duration_secs = duration_secs.to_le_bytes(); |
| 401 | + *dst_total_rewards = total_rewards.to_le_bytes(); |
| 402 | + *dst_num_user_reward_managers = num_user_reward_managers.to_le_bytes(); |
| 403 | + pack_decimal( |
| 404 | + cumulative_rewards_per_share, |
| 405 | + dst_cumulative_rewards_per_share_wads, |
| 406 | + ); |
| 407 | + } |
| 408 | + } |
| 409 | + |
| 410 | + #[inline(never)] |
| 411 | + fn unpack_from_slice(input: &[u8]) -> Result<Self, ProgramError> { |
| 412 | + let mut pool_reward_manager = PoolRewardManager { |
| 413 | + total_shares: u64::from_le_bytes(*array_ref![input, 0, 8]), |
| 414 | + last_update_time_secs: u64::from_le_bytes(*array_ref![input, 8, 8]), |
| 415 | + ..Default::default() |
| 416 | + }; |
| 417 | + |
| 418 | + for index in 0..MAX_REWARDS { |
| 419 | + let offset = 8 + 8 + index * PoolReward::LEN; |
| 420 | + let raw_pool_reward = array_ref![input, offset, PoolReward::LEN]; |
| 421 | + |
| 422 | + let ( |
| 423 | + src_id, |
| 424 | + src_vault, |
| 425 | + src_start_time_secs, |
| 426 | + src_duration_secs, |
| 427 | + src_total_rewards, |
| 428 | + src_num_user_reward_managers, |
| 429 | + src_cumulative_rewards_per_share_wads, |
| 430 | + ) = array_refs![ |
| 431 | + raw_pool_reward, |
| 432 | + PoolRewardId::LEN, |
| 433 | + PUBKEY_BYTES, |
| 434 | + 8, // start_time_secs |
| 435 | + 4, // duration_secs |
| 436 | + 8, // total_rewards |
| 437 | + 8, // num_user_reward_managers |
| 438 | + 16 // cumulative_rewards_per_share |
| 439 | + ]; |
| 440 | + |
| 441 | + let vault = Pubkey::new_from_array(*src_vault); |
| 442 | + let pool_reward_id = PoolRewardId(u32::from_le_bytes(*src_id)); |
| 443 | + |
| 444 | + // SAFETY: ok to assign because we know the index is less than length |
| 445 | + pool_reward_manager.pool_rewards[index] = if vault == Pubkey::default() { |
| 446 | + PoolRewardSlot::Vacant { |
| 447 | + last_pool_reward_id: pool_reward_id, |
| 448 | + } |
| 449 | + } else { |
| 450 | + PoolRewardSlot::Occupied(Box::new(PoolReward { |
| 451 | + id: pool_reward_id, |
| 452 | + vault, |
| 453 | + start_time_secs: u64::from_le_bytes(*src_start_time_secs), |
| 454 | + duration_secs: u32::from_le_bytes(*src_duration_secs), |
| 455 | + total_rewards: u64::from_le_bytes(*src_total_rewards), |
| 456 | + num_user_reward_managers: u64::from_le_bytes(*src_num_user_reward_managers), |
| 457 | + cumulative_rewards_per_share: unpack_decimal( |
| 458 | + src_cumulative_rewards_per_share_wads, |
| 459 | + ), |
| 460 | + })) |
| 461 | + }; |
| 462 | + } |
| 463 | + |
| 464 | + Ok(pool_reward_manager) |
| 465 | + } |
| 466 | +} |
| 467 | + |
283 | 468 | #[cfg(test)]
|
284 | 469 | mod tests {
|
285 | 470 | //! TODO: Rewrite these tests from their Suilend counterparts.
|
286 | 471 | //! TODO: Calculate test coverage and add tests for missing branches.
|
287 | 472 |
|
288 | 473 | use super::*;
|
| 474 | + use proptest::prelude::*; |
| 475 | + use rand::Rng; |
| 476 | + |
| 477 | + fn pool_reward_manager_strategy() -> impl Strategy<Value = PoolRewardManager> { |
| 478 | + (0..100u32).prop_perturb(|_, mut rng| PoolRewardManager::new_rand(&mut rng)) |
| 479 | + } |
| 480 | + |
| 481 | + proptest! { |
| 482 | + #[test] |
| 483 | + fn it_packs_and_unpacks(pool_reward_manager in pool_reward_manager_strategy()) { |
| 484 | + let mut packed = vec![0u8; PoolRewardManager::LEN]; |
| 485 | + Pack::pack_into_slice(&pool_reward_manager, &mut packed); |
| 486 | + let unpacked = PoolRewardManager::unpack_from_slice(&packed).unwrap(); |
| 487 | + prop_assert_eq!(pool_reward_manager, unpacked); |
| 488 | + } |
| 489 | + } |
| 490 | + |
| 491 | + #[test] |
| 492 | + fn it_unpacks_empty_bytes_as_default() { |
| 493 | + let packed = vec![0u8; PoolRewardManager::LEN]; |
| 494 | + let unpacked = PoolRewardManager::unpack_from_slice(&packed).unwrap(); |
| 495 | + assert_eq!(unpacked, PoolRewardManager::default()); |
| 496 | + |
| 497 | + // sanity check that everything starts at 0 |
| 498 | + let all_rewards_are_empty = unpacked.pool_rewards.iter().all(|pool_reward| { |
| 499 | + matches!( |
| 500 | + pool_reward, |
| 501 | + PoolRewardSlot::Vacant { |
| 502 | + last_pool_reward_id: PoolRewardId(0) |
| 503 | + } |
| 504 | + ) |
| 505 | + }); |
| 506 | + |
| 507 | + assert!(all_rewards_are_empty); |
| 508 | + } |
289 | 509 |
|
290 | 510 | #[test]
|
291 | 511 | fn it_fits_reserve_realloc_into_single_ix() {
|
292 |
| - const MAX_REALLOC: usize = 10 * 1024; |
| 512 | + const MAX_REALLOC: usize = solana_program::entrypoint::MAX_PERMITTED_DATA_INCREASE; |
293 | 513 |
|
294 | 514 | let size_of_discriminant = 1;
|
295 |
| - let const_size_of_pool_manager = 8 + 8; |
296 |
| - let required_realloc = size_of_discriminant |
297 |
| - + const_size_of_pool_manager |
298 |
| - + 2 * MAX_REWARDS * std::mem::size_of::<PoolReward>(); |
299 |
| - |
300 |
| - println!("assert {required_realloc} <= {MAX_REALLOC}"); |
| 515 | + let required_realloc = size_of_discriminant * PoolRewardManager::LEN; |
301 | 516 | assert!(required_realloc <= MAX_REALLOC);
|
302 | 517 | }
|
303 | 518 |
|
|
330 | 545 | fn it_tests_pool_reward_manager_cancel_and_close_regression() {
|
331 | 546 | // TODO: rewrite Suilend "test_pool_reward_manager_cancel_and_close_regression"
|
332 | 547 | }
|
| 548 | + |
| 549 | + impl PoolRewardManager { |
| 550 | + pub(crate) fn new_rand(rng: &mut impl Rng) -> Self { |
| 551 | + Self { |
| 552 | + total_shares: rng.gen(), |
| 553 | + last_update_time_secs: rng.gen(), |
| 554 | + pool_rewards: std::array::from_fn(|_| { |
| 555 | + let is_vacant = rng.gen_bool(0.5); |
| 556 | + |
| 557 | + if is_vacant { |
| 558 | + PoolRewardSlot::Vacant { |
| 559 | + last_pool_reward_id: PoolRewardId(rng.gen()), |
| 560 | + } |
| 561 | + } else { |
| 562 | + PoolRewardSlot::Occupied(Box::new(PoolReward { |
| 563 | + id: PoolRewardId(rng.gen()), |
| 564 | + vault: Pubkey::new_unique(), |
| 565 | + start_time_secs: rng.gen(), |
| 566 | + duration_secs: rng.gen(), |
| 567 | + total_rewards: rng.gen(), |
| 568 | + cumulative_rewards_per_share: Decimal::from_scaled_val(rng.gen()), |
| 569 | + num_user_reward_managers: rng.gen(), |
| 570 | + })) |
| 571 | + } |
| 572 | + }), |
| 573 | + } |
| 574 | + } |
| 575 | + } |
333 | 576 | }
|
0 commit comments