Repository navigation
Expand file tree
/
Copy pathOnChainProgram.rs
More file actions
549 lines (494 loc) · 17.8 KB
/
Copy pathOnChainProgram.rs
File metadata and controls
549 lines (494 loc) · 17.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
use anchor_lang::prelude::*;
use anchor_lang::solana_program::program::invoke;
use anchor_lang::solana_program::system_instruction;
declare_id!("MagnumOpus1111111111111111111111111111111111");
pub const REWARD_PRECISION: u128 = 1_000_000_000;
pub const FEE_DENOMINATOR: u64 = 10_000;
#[program]
pub mod on_chain_program {
use super::*;
// ---------------------------------------------------------------------
// Vault Management
// ---------------------------------------------------------------------
/// Initialize a new vault for the given authority.
/// The vault is a PDA seeded with "vault" and the bump.
pub fn initialize(ctx: Context<Initialize>, bump: u8) -> Result<()> {
let vault = &mut ctx.accounts.vault;
vault.authority = *ctx.accounts.authority.key;
vault.bump = bump;
vault.balance = 0;
vault.staked_balance = 0;
vault.reward_debt = 0;
vault.pending_rewards = 0;
vault.reward_per_token_paid = 0;
vault.created_at = Clock::get()?.unix_timestamp;
vault.last_action_slot = Clock::get()?.slot;
emit!(VaultInitialized { authority: vault.authority, bump });
Ok(())
}
/// Deposit lamports into the vault.
pub fn deposit(ctx: Context<Deposit>, amount: u64) -> Result<()> {
require!(amount > 0, ErrorCode::InvalidAmount);
let vault = &mut ctx.accounts.vault;
vault.balance = vault
.balance
.checked_add(amount)
.ok_or(ErrorCode::Overflow)?;
vault.last_action_slot = Clock::get()?.slot;
// Transfer lamports from the signer to the vault PDA.
**ctx.accounts.authority.to_account_info().try_borrow_mut_lamports()? -= amount;
**ctx.accounts.vault.to_account_info().try_borrow_mut_lamports()? += amount;
emit!(DepositEvent { authority: vault.authority, amount, new_balance: vault.balance });
Ok(())
}
/// Withdraw lamports from the vault.
pub fn withdraw(ctx: Context<Withdraw>, amount: u64) -> Result<()> {
let vault = &mut ctx.accounts.vault;
require!(vault.balance >= amount, ErrorCode::InsufficientFunds);
vault.balance = vault
.balance
.checked_sub(amount)
.ok_or(ErrorCode::Underflow)?;
vault.last_action_slot = Clock::get()?.slot;
// Transfer lamports back to the authority.
**ctx.accounts.vault.to_account_info().try_borrow_mut_lamports()? -= amount;
**ctx.accounts.authority.to_account_info().try_borrow_mut_lamports()? += amount;
emit!(WithdrawEvent { authority: vault.authority, amount, new_balance: vault.balance });
Ok(())
}
/// Change the authority of the vault. Only the current authority can call.
pub fn set_authority(ctx: Context<SetAuthority>, new_authority: Pubkey) -> Result<()> {
let vault = &mut ctx.accounts.vault;
require!(vault.authority == *ctx.accounts.authority.key, ErrorCode::Unauthorized);
let old = vault.authority;
vault.authority = new_authority;
emit!(AuthorityChanged { old_authority: old, new_authority });
Ok(())
}
// ---------------------------------------------------------------------
// Staking Pool Management
// ---------------------------------------------------------------------
/// Initialize a new global staking pool with reward emission rate per second.
pub fn initialize_staking_pool(
ctx: Context<InitializeStakingPool>,
reward_rate_per_second: u64,
bump: u8,
) -> Result<()> {
let pool = &mut ctx.accounts.staking_pool;
pool.authority = ctx.accounts.authority.key();
pool.bump = bump;
pool.total_staked = 0;
pool.reward_per_token = 0;
pool.last_update_time = Clock::get()?.unix_timestamp;
pool.reward_rate_per_second = reward_rate_per_second;
pool.total_rewards_distributed = 0;
pool.paused = false;
emit!(StakingPoolInitialized {
authority: pool.authority,
reward_rate_per_second,
timestamp: pool.last_update_time,
});
Ok(())
}
/// Pause the staking pool (emergency stop).
pub fn pause_pool(ctx: Context<PausePool>) -> Result<()> {
let pool = &mut ctx.accounts.staking_pool;
require!(pool.authority == *ctx.accounts.authority.key, ErrorCode::Unauthorized);
pool.paused = true;
emit!(PoolPaused { authority: pool.authority, timestamp: Clock::get()?.unix_timestamp });
Ok(())
}
/// Resume a paused staking pool.
pub fn resume_pool(ctx: Context<ResumePool>) -> Result<()> {
let pool = &mut ctx.accounts.staking_pool;
require!(pool.authority == *ctx.accounts.authority.key, ErrorCode::Unauthorized);
pool.paused = false;
emit!(PoolResumed { authority: pool.authority, timestamp: Clock::get()?.unix_timestamp });
Ok(())
}
/// Update the reward rate of the staking pool.
pub fn update_reward_rate(ctx: Context<UpdateRewardRate>, new_rate: u64) -> Result<()> {
let pool = &mut ctx.accounts.staking_pool;
require!(pool.authority == *ctx.accounts.authority.key, ErrorCode::Unauthorized);
pool.reward_rate_per_second = new_rate;
emit!(RewardRateUpdated {
authority: pool.authority,
new_rate,
timestamp: Clock::get()?.unix_timestamp,
});
Ok(())
}
/// Stake tokens into the pool.
pub fn stake(ctx: Context<Stake>, amount: u64) -> Result<()> {
require!(amount > 0, ErrorCode::InvalidAmount);
let pool = &mut ctx.accounts.staking_pool;
let vault = &mut ctx.accounts.vault;
require!(vault.balance >= amount, ErrorCode::InsufficientFunds);
require!(!pool.paused, ErrorCode::PoolPaused);
// Update the reward per token.
let current_time = Clock::get()?.unix_timestamp;
let time_elapsed = current_time - pool.last_update_time;
if time_elapsed > 0 {
let reward_per_token = pool.reward_per_token
.checked_add(
(time_elapsed as u128)
.checked_mul(pool.reward_rate_per_second as u128)
.ok_or(ErrorCode::Overflow)?
.checked_mul(REWARD_PRECISION)
.ok_or(ErrorCode::Overflow)?
.checked_div(pool.total_staked as u128)
.ok_or(ErrorCode::DivisionByZero)?,
)
.ok_or(ErrorCode::Overflow)?;
pool.reward_per_token = reward_per_token;
pool.last_update_time = current_time;
}
// Update the user's reward debt and pending rewards.
let reward_debt = vault.reward_debt
.checked_add(
vault.staked_balance
.checked_mul(pool.reward_per_token)
.ok_or(ErrorCode::Overflow)?
.checked_div(REWARD_PRECISION)
.ok_or(ErrorCode::DivisionByZero)?
.checked_sub(vault.reward_debt)
.ok_or(ErrorCode::Underflow)?,
)
.ok_or(ErrorCode::Overflow)?;
vault.reward_debt = reward_debt;
// Update the pool's total staked balance.
pool.total_staked = pool
.total_staked
.checked_add(amount)
.ok_or(ErrorCode::Overflow)?;
// Update the vault's staked balance.
vault.staked_balance = vault
.staked_balance
.checked_add(amount)
.ok_or(ErrorCode::Overflow)?;
// Transfer lamports from the vault to the pool.
**ctx.accounts.vault.to_account_info().try_borrow_mut_lamports()? -= amount;
**ctx.accounts.staking_pool.to_account_info().try_borrow_mut_lamports()? += amount;
emit!(StakeEvent {
authority: vault.authority,
amount,
new_staked_balance: vault.staked_balance,
timestamp: current_time,
});
Ok(())
}
/// Unstake tokens from the pool.
pub fn unstake(ctx: Context<Unstake>, amount: u64) -> Result<()> {
require!(amount > 0, ErrorCode::InvalidAmount);
let pool = &mut ctx.accounts.staking_pool;
let vault = &mut ctx.accounts.vault;
require!(vault.staked_balance >= amount, ErrorCode::InsufficientFunds);
require!(!pool.paused, ErrorCode::PoolPaused);
// Update the reward per token.
let current_time = Clock::get()?.unix_timestamp;
let time_elapsed = current_time - pool.last_update_time;
if time_elapsed > 0 {
let reward_per_token = pool.reward_per_token
.checked_add(
(time_elapsed as u128)
.checked_mul(pool.reward_rate_per_second as u128)
.ok_or(ErrorCode::Overflow)?
.checked_mul(REWARD_PRECISION)
.ok_or(ErrorCode::Overflow)?
.checked_div(pool.total_staked as u128)
.ok_or(ErrorCode::DivisionByZero)?,
)
.ok_or(ErrorCode::Overflow)?;
pool.reward_per_token = reward_per_token;
pool.last_update_time = current_time;
}
// Update the user's reward debt and pending rewards.
let pending_rewards = vault.staked_balance
.checked_mul(pool.reward_per_token)
.ok_or(ErrorCode::Overflow)?
.checked_div(REWARD_PRECISION)
.ok_or(ErrorCode::DivisionByZero)?
.checked_sub(vault.reward_debt)
.ok_or(ErrorCode::Underflow)?;
vault.pending_rewards = pending_rewards;
vault.reward_debt = 0;
// Update the pool's total staked balance.
pool.total_staked = pool
.total_staked
.checked_sub(amount)
.ok_or(ErrorCode::Underflow)?;
// Update the vault's staked balance.
vault.staked_balance = vault
.staked_balance
.checked_sub(amount)
.ok_or(ErrorCode::Underflow)?;
// Transfer lamports from the pool to the vault.
**ctx.accounts.staking_pool.to_account_info().try_borrow_mut_lamports()? -= amount;
**ctx.accounts.vault.to_account_info().try_borrow_mut_lamports()? += amount;
emit!(UnstakeEvent {
authority: vault.authority,
amount,
new_staked_balance: vault.staked_balance,
pending_rewards,
timestamp: current_time,
});
Ok(())
}
/// Claim pending rewards from the staking pool.
pub fn claim_rewards(ctx: Context<ClaimRewards>) -> Result<()> {
let pool = &mut ctx.accounts.staking_pool;
let vault = &mut ctx.accounts.vault;
require!(vault.pending_rewards > 0, ErrorCode::NoRewardsToClaim);
require!(!pool.paused, ErrorCode::PoolPaused);
// Update the reward per token.
let current_time = Clock::get()?.unix_timestamp;
let time_elapsed = current_time - pool.last_update_time;
if time_elapsed > 0 {
let reward_per_token = pool.reward_per_token
.checked_add(
(time_elapsed as u128)
.checked_mul(pool.reward_rate_per_second as u128)
.ok_or(ErrorCode::Overflow)?
.checked_mul(REWARD_PRECISION)
.ok_or(ErrorCode::Overflow)?
.checked_div(pool.total_staked as u128)
.ok_or(ErrorCode::DivisionByZero)?,
)
.ok_or(ErrorCode::Overflow)?;
pool.reward_per_token = reward_per_token;
pool.last_update_time = current_time;
}
// Update the user's reward debt and pending rewards.
let pending_rewards = vault.staked_balance
.checked_mul(pool.reward_per_token)
.ok_or(ErrorCode::Overflow)?
.checked_div(REWARD_PRECISION)
.ok_or(ErrorCode::DivisionByZero)?
.checked_sub(vault.reward_debt)
.ok_or(ErrorCode::Underflow)?;
vault.pending_rewards = pending_rewards;
vault.reward_debt = 0;
// Transfer rewards from the pool to the vault.
**ctx.accounts.staking_pool.to_account_info().try_borrow_mut_lamports()? -= pending_rewards;
**ctx.accounts.vault.to_account_info().try_borrow_mut_lamports()? += pending_rewards;
emit!(RewardsClaimed {
authority: vault.authority,
amount: pending_rewards,
timestamp: current_time,
});
Ok(())
}
}
#[derive(Accounts)]
pub struct Initialize<'info> {
#[account(
init,
payer = authority,
space = 8 + std::mem::size_of::<Vault>(),
seeds = [b"vault", authority.key().as_ref()],
bump,
)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Deposit<'info> {
#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Withdraw<'info> {
#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct SetAuthority<'info> {
#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct InitializeStakingPool<'info> {
#[account(
init,
payer = authority,
space = 8 + std::mem::size_of::<StakingPool>(),
seeds = [b"staking_pool"],
bump,
)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct PausePool<'info> {
#[account(mut, has_one = authority)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct ResumePool<'info> {
#[account(mut, has_one = authority)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct UpdateRewardRate<'info> {
#[account(mut, has_one = authority)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Stake<'info> {
#[account(mut)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct Unstake<'info> {
#[account(mut)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[derive(Accounts)]
pub struct ClaimRewards<'info> {
#[account(mut)]
pub staking_pool: Account<'info, StakingPool>,
#[account(mut, has_one = authority)]
pub vault: Account<'info, Vault>,
#[account(mut)]
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}
#[account]
pub struct Vault {
pub authority: Pubkey,
pub bump: u8,
pub balance: u64,
pub staked_balance: u64,
pub reward_debt: u128,
pub pending_rewards: u128,
pub reward_per_token_paid: u128,
pub created_at: i64,
pub last_action_slot: u64,
}
#[account]
pub struct StakingPool {
pub authority: Pubkey,
pub bump: u8,
pub total_staked: u64,
pub reward_per_token: u128,
pub last_update_time: i64,
pub reward_rate_per_second: u64,
pub total_rewards_distributed: u64,
pub paused: bool,
}
#[event]
pub struct VaultInitialized {
pub authority: Pubkey,
pub bump: u8,
}
#[event]
pub struct DepositEvent {
pub authority: Pubkey,
pub amount: u64,
pub new_balance: u64,
}
#[event]
pub struct WithdrawEvent {
pub authority: Pubkey,
pub amount: u64,
pub new_balance: u64,
}
#[event]
pub struct AuthorityChanged {
pub old_authority: Pubkey,
pub new_authority: Pubkey,
}
#[event]
pub struct StakingPoolInitialized {
pub authority: Pubkey,
pub reward_rate_per_second: u64,
pub timestamp: i64,
}
#[event]
pub struct PoolPaused {
pub authority: Pubkey,
pub timestamp: i64,
}
#[event]
pub struct PoolResumed {
pub authority: Pubkey,
pub timestamp: i64,
}
#[event]
pub struct RewardRateUpdated {
pub authority: Pubkey,
pub new_rate: u64,
pub timestamp: i64,
}
#[event]
pub struct StakeEvent {
pub authority: Pubkey,
pub amount: u64,
pub new_staked_balance: u64,
pub timestamp: i64,
}
#[event]
pub struct UnstakeEvent {
pub authority: Pubkey,
pub amount: u64,
pub new_staked_balance: u64,
pub pending_rewards: u128,
pub timestamp: i64,
}
#[event]
pub struct RewardsClaimed {
pub authority: Pubkey,
pub amount: u128,
pub timestamp: i64,
}
#[error_code]
pub enum ErrorCode {
#[msg("Invalid amount")]
InvalidAmount,
#[msg("Overflow")]
Overflow,
#[msg("Underflow")]
Underflow,
#[msg("Insufficient funds")]
InsufficientFunds,
#[msg("Unauthorized")]
Unauthorized,
#[msg("Division by zero")]
DivisionByZero,
#[msg("Pool is paused")]
PoolPaused,
#[msg("No rewards to claim")]
NoRewardsToClaim,
}