-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathlib.rs
More file actions
630 lines (533 loc) · 21.6 KB
/
lib.rs
File metadata and controls
630 lines (533 loc) · 21.6 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
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
extern crate jito_merkle_tree;
extern crate merkle_distributor;
use std::{path::PathBuf, str::FromStr};
use anchor_lang::{prelude::Pubkey, AccountDeserialize, InstructionData, Key, ToAccountMetas};
use anchor_spl::token;
use clap::{Parser, Subcommand};
use jito_merkle_tree::{
airdrop_merkle_tree::AirdropMerkleTree,
utils::{get_claim_status_pda, get_merkle_distributor_pda, get_page_account_pda},
};
use merkle_distributor::state::merkle_distributor::MerkleDistributor;
use solana_program::instruction::Instruction;
use solana_rpc_client::rpc_client::RpcClient;
use solana_sdk::{
account::Account,
bs58,
commitment_config::CommitmentConfig,
compute_budget::ComputeBudgetInstruction,
signature::{read_keypair_file, Keypair},
signer::Signer,
transaction::Transaction,
};
use spl_associated_token_account::{
get_associated_token_address, instruction::create_associated_token_account,
};
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
pub struct Args {
#[clap(subcommand)]
pub command: Commands,
/// Airdrop version
#[clap(long, default_value_t = 0)]
pub airdrop_version: u64,
/// SPL Mint address
#[clap(long)]
pub mint: Pubkey,
/// Staking address
#[clap(long)]
pub staking: Pubkey,
/// RPC url
#[clap(long)]
pub rpc_url: String,
/// Program id
#[clap(long, default_value_t = merkle_distributor::id())]
pub program_id: Pubkey,
/// Payer keypair
#[clap(long)]
pub keypair_path: PathBuf,
/// Priority fee
#[clap(long)]
pub priority: Option<u64>,
}
// cargo run new-distributor --mint 4dzPmLDFSpuaCcTUoQjw71Bq8u8RWgHJQcLS63Y8ZrZp --staking 5dNR1Lav7T4WNbZUHd2EFMZ71Rfhz3sEFGyR6tgWB5uK --clawback-receiver-token-account 5pT9ijgv2Qpxn4ux4u4crCCJhgAe4w7GoeaCPJKgP4NW --start-vesting-ts 1738340679 --end-vesting-ts 1749350679 --merkle-tree-path /Users/mykyta/development/composable/mantis-staking-program/solana/merkle-tree/test_fixtures/test_csv.csv --clawback-start-ts 1749950679
// Subcommands
#[derive(Subcommand, Debug)]
pub enum Commands {
/// Claim unlocked tokens
Claim(ClaimArgs),
/// Admin claim unlocked tokens
AdminNewClaim,
/// Create a new instance of a merkle distributor
NewDistributor(NewDistributorArgs),
/// Clawback tokens from merkle distributor
#[clap(hide = true)]
Clawback(ClawbackArgs),
/// Create a Merkle tree, given a CSV of recipients
CreateMerkleTree(CreateMerkleTreeArgs),
SetAdmin(SetAdminArgs),
}
// NewClaim and Claim subcommand args
#[derive(Parser, Debug)]
pub struct ClaimArgs {
/// Merkle distributor path
#[clap(long)]
pub merkle_tree_path: PathBuf,
}
// NewDistributor subcommand args
#[derive(Parser, Debug)]
pub struct NewDistributorArgs {
/// Clawback receiver token account
#[clap(long)]
pub clawback_receiver_token_account: Pubkey,
/// Lockup timestamp start
#[clap(long)]
pub start_vesting_ts: i64,
/// Lockup timestamp end (unix timestamp)
#[clap(long)]
pub end_vesting_ts: i64,
/// Merkle distributor path
#[clap(long)]
pub merkle_tree_path: PathBuf,
/// When to make the clawback period start. Must be at least a day after the end_vesting_ts
#[clap(long)]
pub clawback_start_ts: i64,
}
#[derive(Parser, Debug)]
pub struct ClawbackArgs {
#[clap(long)]
pub clawback_keypair_path: PathBuf,
}
#[derive(Parser, Debug)]
pub struct CreateMerkleTreeArgs {
/// CSV path
#[clap(long)]
pub csv_path: PathBuf,
/// Merkle tree out path
#[clap(long)]
pub merkle_tree_path: PathBuf,
}
#[derive(Parser, Debug)]
pub struct SetAdminArgs {
#[clap(long)]
pub new_admin: Pubkey,
}
fn process_new_claim(args: &Args, claim_args: &ClaimArgs) {
use dotenv::dotenv;
dotenv().ok();
let env_siner_private_key =
std::env::var("SIGNER_PRIV_KEY").expect("SIGNER_PRIV_KEY must be set.");
let private_key_bytes = bs58::decode(env_siner_private_key).into_vec().unwrap();
let keypair = Keypair::from_bytes(&private_key_bytes).unwrap();
// let keypair = read_keypair_file(&args.keypair_path).expect("Failed reading keypair file");
let claimant = keypair.pubkey();
println!("Claiming tokens for user {}...", claimant);
let merkle_tree = AirdropMerkleTree::new_from_csv(&claim_args.merkle_tree_path)
.expect("failed to load merkle tree from file");
let (distributor, _bump) =
get_merkle_distributor_pda(&args.program_id, &args.mint, args.airdrop_version);
// Get user's node in claim
let node = merkle_tree.get_node(&claimant);
let (claim_status_pda, _bump) = get_claim_status_pda(&args.program_id, &claimant, &distributor);
let client = RpcClient::new_with_commitment(&args.rpc_url, CommitmentConfig::confirmed());
let claimant_ata = get_associated_token_address(&claimant, &args.mint);
let mut ixs = vec![];
match client.get_account(&claimant_ata) {
Ok(_) => {}
Err(e) => {
// TODO: directly pattern match on error kind
if e.to_string().contains("AccountNotFound") {
println!("PDA does not exist. creating.");
let ix =
create_associated_token_account(&claimant, &claimant, &args.mint, &token::ID);
ixs.push(ix);
} else {
panic!("Error fetching PDA: {e}")
}
}
}
let x = get_associated_token_address(&distributor, &args.mint);
println!("distributor: {distributor}");
println!("claim_status: {claim_status_pda}");
println!("from: {x}");
println!("to: {claimant_ata}");
println!("claimant: {claimant}");
let new_claim_ix = Instruction {
program_id: args.program_id,
accounts: merkle_distributor::accounts::NewClaim {
distributor,
claim_status: claim_status_pda,
from: get_associated_token_address(&distributor, &args.mint),
to: claimant_ata,
claimant,
token_program: token::ID,
system_program: solana_program::system_program::ID,
}
.to_account_metas(None),
data: merkle_distributor::instruction::NewClaim {
amount_unlocked: node.amount_unlocked(),
amount_locked: node.amount_locked(),
proof: node.proof.expect("proof not found"),
}
.data(),
};
ixs.push(new_claim_ix);
let blockhash = client.get_latest_blockhash().unwrap();
let tx =
Transaction::new_signed_with_payer(&ixs, Some(&claimant.key()), &[&keypair], blockhash);
let signature = client
.send_and_confirm_transaction_with_spinner(&tx)
.unwrap();
println!("successfully created new claim with signature {signature:#?}");
}
pub fn call_process_admin_claim(
claimant: Pubkey,
amount_unlocked: u64,
amount_locked: u64,
page_index: u8,
) -> (bool, String) {
use dotenv::dotenv;
dotenv().ok();
let mint = std::env::var("WHITELIST_MINT").expect("WHITELIST_MINT must be set.");
let vesting_program =
std::env::var("VESTING_PROGRAM_ID").expect("VESTING_PROGRAM_ID must be set.");
let solana_rpc_url = std::env::var("SOLANA_RPC_URL").expect("SOLANA_RPC_URL must be set.");
let args: Args = Args {
command: Commands::AdminNewClaim,
airdrop_version: 0,
mint: Pubkey::from_str(&mint).unwrap(),
staking: Pubkey::from_str(&vesting_program).unwrap(),
rpc_url: solana_rpc_url,
program_id: Pubkey::from_str(&vesting_program).unwrap(),
keypair_path: PathBuf::from(""),
priority: None,
};
return process_admin_claim(&args, claimant, amount_unlocked, amount_locked, page_index);
}
fn process_admin_claim(
args: &Args,
claimant: Pubkey,
amount_unlocked: u64,
amount_locked: u64,
page_index: u8,
) -> (bool, String) {
use dotenv::dotenv;
dotenv().ok();
let env_siner_private_key =
std::env::var("SIGNER_PRIV_KEY").expect("SIGNER_PRIV_KEY must be set.");
let admin_private_key_bytes = bs58::decode(env_siner_private_key).into_vec().unwrap();
let keypair = Keypair::from_bytes(&admin_private_key_bytes).unwrap();
println!("Setting airdrop/vesting schedule for user {}...", claimant);
let (distributor, _bump) =
get_merkle_distributor_pda(&args.program_id, &args.mint, args.airdrop_version);
let (page_account_pda, _bump) = get_page_account_pda(&args.program_id, 1);
let client = RpcClient::new_with_commitment(&args.rpc_url, CommitmentConfig::confirmed());
// let claimant_ata = get_associated_token_address(&claimant, &args.mint);
let mut ixs = vec![];
// match client.get_account(&claimant_ata) {
// Ok(_) => {}
// Err(e) => {
// // TODO: directly pattern match on error kind
// if e.to_string().contains("AccountNotFound") {
// println!("PDA does not exist. creating.");
// let ix =
// create_associated_token_account(&claimant, &claimant, &args.mint, &token::ID);
// ixs.push(ix);
// } else {
// panic!("Error fetching PDA: {e}")
// }
// }
// }
let x = get_associated_token_address(&distributor, &args.mint);
println!("distributor: {distributor}");
println!("claim_status: {page_account_pda}");
println!("from: {x}");
// println!("to: {claimant_ata}");
println!("claimant: {claimant}");
let new_claim_ix = Instruction {
program_id: args.program_id,
accounts: merkle_distributor::accounts::AdminNewClaim {
distributor,
admin: keypair.pubkey(),
page_account_state: page_account_pda,
token_program: token::ID,
system_program: solana_program::system_program::ID,
}
.to_account_metas(None),
data: merkle_distributor::instruction::AdminNewClaim {
amount_unlocked: amount_unlocked,
amount_locked: amount_locked,
page_index: page_index,
claimant: claimant,
}
.data(),
};
ixs.push(new_claim_ix);
let blockhash = client.get_latest_blockhash().unwrap();
let tx = Transaction::new_signed_with_payer(
&ixs,
Some(&keypair.pubkey().key()),
&[&keypair],
blockhash,
);
let signature = client.send_and_confirm_transaction_with_spinner(&tx);
let msg_signature = format!("{:?}", signature);
println!("{}", msg_signature);
if signature.is_err() {
return (false, msg_signature);
}
return (true, msg_signature);
}
fn process_claim(args: &Args, claim_args: &ClaimArgs) {
use dotenv::dotenv;
dotenv().ok();
let env_siner_private_key =
std::env::var("SIGNER_PRIV_KEY").expect("SIGNER_PRIV_KEY must be set.");
let private_key_bytes = bs58::decode(env_siner_private_key).into_vec().unwrap();
let keypair = Keypair::from_bytes(&private_key_bytes).unwrap();
println!("This is pubkey {}", keypair.pubkey().to_string());
// let keypair = read_keypair_file(&args.keypair_path).expect("Failed reading keypair file");
let claimant = keypair.pubkey();
let priority_fee = args.priority.unwrap_or(0);
let (distributor, bump) =
get_merkle_distributor_pda(&args.program_id, &args.mint, args.airdrop_version);
println!("distributor pubkey {}", distributor);
let (claim_status_pda, _bump) = get_claim_status_pda(&args.program_id, &claimant, &distributor);
println!("claim pda: {claim_status_pda}, bump: {bump}");
let client = RpcClient::new_with_commitment(&args.rpc_url, CommitmentConfig::confirmed());
match client.get_account(&claim_status_pda) {
Ok(_) => {}
Err(e) => {
// TODO: match on the error kind
if e.to_string().contains("AccountNotFound") {
println!("PDA does not exist. creating.");
process_new_claim(args, claim_args);
} else {
panic!("error getting PDA: {e}")
}
}
}
let claimant_ata = get_associated_token_address(&claimant, &args.mint);
let mut ixs = vec![];
println!("distributed pubkey: {distributor}");
println!("claim_status: {claim_status_pda}");
let x = get_associated_token_address(&distributor, &args.mint);
println!("from: {x}");
println!("to: {claimant_ata}");
println!("claimant: {claimant}");
// return;
let claim_ix = Instruction {
program_id: args.program_id,
accounts: merkle_distributor::accounts::ClaimLocked {
distributor,
claim_status: claim_status_pda,
from: get_associated_token_address(&distributor, &args.mint),
to: claimant_ata,
claimant,
token_program: token::ID,
}
.to_account_metas(None),
data: merkle_distributor::instruction::ClaimLocked {}.data(),
};
ixs.push(claim_ix);
if priority_fee > 0 {
let instruction = ComputeBudgetInstruction::set_compute_unit_price(priority_fee);
ixs.push(instruction);
println!(
"Added priority fee instruction of {} microlamports",
priority_fee
);
} else {
println!("No priority fee added. Add one with --priority <microlamports u64>");
}
let blockhash = client.get_latest_blockhash().unwrap();
let tx =
Transaction::new_signed_with_payer(&ixs, Some(&claimant.key()), &[&keypair], blockhash);
let signature = client
.send_and_confirm_transaction_with_spinner(&tx)
.unwrap();
println!("successfully claimed tokens with signature {signature:#?}",);
}
fn check_distributor_onchain_matches(
account: &Account,
merkle_tree: &AirdropMerkleTree,
new_distributor_args: &NewDistributorArgs,
pubkey: Pubkey,
) -> Result<(), &'static str> {
if let Ok(distributor) = MerkleDistributor::try_deserialize(&mut account.data.as_slice()) {
if distributor.root != merkle_tree.merkle_root {
return Err("root mismatch");
}
if distributor.max_total_claim != merkle_tree.max_total_claim {
return Err("max_total_claim mismatch");
}
if distributor.max_num_nodes != merkle_tree.max_num_nodes {
return Err("max_num_nodes mismatch");
}
if distributor.start_ts != new_distributor_args.start_vesting_ts {
return Err("start_ts mismatch");
}
if distributor.end_ts != new_distributor_args.end_vesting_ts {
return Err("end_ts mismatch");
}
if distributor.clawback_start_ts != new_distributor_args.clawback_start_ts {
return Err("clawback_start_ts mismatch");
}
if distributor.clawback_receiver != new_distributor_args.clawback_receiver_token_account {
return Err("clawback_receiver mismatch");
}
if distributor.admin != pubkey {
return Err("admin mismatch");
}
}
Ok(())
}
fn process_new_distributor(args: &Args, new_distributor_args: &NewDistributorArgs) {
use dotenv::dotenv;
dotenv().ok();
let env_siner_private_key =
std::env::var("SIGNER_PRIV_KEY").expect("SIGNER_PRIV_KEY must be set.");
let private_key_bytes = bs58::decode(env_siner_private_key).into_vec().unwrap();
let keypair = Keypair::from_bytes(&private_key_bytes).unwrap();
println!("This is pubkey {}", keypair.pubkey().to_string());
let ret_back = get_associated_token_address(&keypair.pubkey(), &args.mint);
// let keypair = read_keypair_file(&args.keypair_path).expect("Failed reading keypair file");
let client = RpcClient::new_with_commitment(&args.rpc_url, CommitmentConfig::finalized());
let merkle_tree = AirdropMerkleTree::new_from_csv(&new_distributor_args.merkle_tree_path)
.expect("failed to read");
let (distributor_pubkey, _bump) =
get_merkle_distributor_pda(&args.program_id, &args.mint, args.airdrop_version);
let token_vault = get_associated_token_address(&distributor_pubkey, &args.mint);
if let Some(account) = client
.get_account_with_commitment(&distributor_pubkey, CommitmentConfig::confirmed())
.unwrap()
.value
{
println!("merkle distributor account exists, checking parameters...");
check_distributor_onchain_matches(
&account,
&merkle_tree,
new_distributor_args,
keypair.pubkey(),
).expect("merkle root on-chain does not match provided arguments! Confirm admin and clawback parameters to avoid loss of funds!");
}
println!("creating new distributor with args: {new_distributor_args:#?}");
let new_distributor_ix = Instruction {
program_id: args.program_id,
accounts: merkle_distributor::accounts::NewDistributor {
clawback_receiver: ret_back,
mint: args.mint,
token_vault,
distributor: distributor_pubkey,
system_program: solana_program::system_program::id(),
associated_token_program: spl_associated_token_account::ID,
token_program: token::ID,
admin: keypair.pubkey(),
}
.to_account_metas(None),
data: merkle_distributor::instruction::NewDistributor {
version: args.airdrop_version,
root: merkle_tree.merkle_root,
max_total_claim: merkle_tree.max_total_claim,
max_num_nodes: merkle_tree.max_num_nodes,
start_vesting_ts: new_distributor_args.start_vesting_ts,
end_vesting_ts: new_distributor_args.end_vesting_ts,
clawback_start_ts: new_distributor_args.clawback_start_ts,
staking_contract_address: None,
}
.data(),
};
let blockhash = client.get_latest_blockhash().unwrap();
let tx = Transaction::new_signed_with_payer(
&[new_distributor_ix],
Some(&keypair.pubkey()),
&[&keypair],
blockhash,
);
// See comments on new_distributor instruction inside the program to ensure this transaction
// didn't get frontrun.
// If this fails, make sure to run it again.
match client.send_and_confirm_transaction_with_spinner(&tx) {
Ok(_) => {}
Err(e) => {
println!("Failed to create MerkleDistributor: {:?}", e);
// double check someone didn't frontrun this transaction with a malicious merkle root
if let Some(account) = client
.get_account_with_commitment(&distributor_pubkey, CommitmentConfig::processed())
.unwrap()
.value
{
check_distributor_onchain_matches(
&account,
&merkle_tree,
new_distributor_args,
keypair.pubkey(),
).expect("merkle root on-chain does not match provided arguments! Confirm admin and clawback parameters to avoid loss of funds!");
}
}
}
}
fn process_clawback(args: &Args, clawback_args: &ClawbackArgs) {
let payer_keypair = read_keypair_file(&args.keypair_path).expect("Failed reading keypair file");
let clawback_keypair = read_keypair_file(&clawback_args.clawback_keypair_path)
.expect("Failed reading keypair file");
let clawback_ata = get_associated_token_address(&clawback_keypair.pubkey(), &args.mint);
let client = RpcClient::new_with_commitment(&args.rpc_url, CommitmentConfig::confirmed());
let (distributor, _bump) =
get_merkle_distributor_pda(&args.program_id, &args.mint, args.airdrop_version);
let from = get_associated_token_address(&distributor, &args.mint);
println!("from: {from}");
let clawback_ix = Instruction {
program_id: args.program_id,
accounts: merkle_distributor::accounts::Clawback {
distributor,
from,
to: clawback_ata,
claimant: clawback_keypair.pubkey(),
system_program: solana_program::system_program::ID,
token_program: token::ID,
}
.to_account_metas(None),
data: merkle_distributor::instruction::Clawback {}.data(),
};
let tx = Transaction::new_signed_with_payer(
&[clawback_ix],
Some(&payer_keypair.pubkey()),
&[&payer_keypair, &clawback_keypair],
client.get_latest_blockhash().unwrap(),
);
let signature = client
.send_and_confirm_transaction_with_spinner(&tx)
.unwrap();
println!("Successfully clawed back funds! signature: {signature:#?}");
}
fn process_create_merkle_tree(merkle_tree_args: &CreateMerkleTreeArgs) {
let merkle_tree = AirdropMerkleTree::new_from_csv(&merkle_tree_args.csv_path).unwrap();
merkle_tree.write_to_file(&merkle_tree_args.merkle_tree_path);
}
fn process_set_admin(args: &Args, set_admin_args: &SetAdminArgs) {
let keypair = read_keypair_file(&args.keypair_path).expect("Failed reading keypair file");
let client = RpcClient::new_with_commitment(&args.rpc_url, CommitmentConfig::confirmed());
let (distributor, _bump) =
get_merkle_distributor_pda(&args.program_id, &args.mint, args.airdrop_version);
let set_admin_ix = Instruction {
program_id: args.program_id,
accounts: merkle_distributor::accounts::SetAdmin {
distributor,
admin: keypair.pubkey(),
new_admin: set_admin_args.new_admin,
}
.to_account_metas(None),
data: merkle_distributor::instruction::SetAdmin {}.data(),
};
let tx = Transaction::new_signed_with_payer(
&[set_admin_ix],
Some(&keypair.pubkey()),
&[&keypair],
client.get_latest_blockhash().unwrap(),
);
let signature = client
.send_and_confirm_transaction_with_spinner(&tx)
.unwrap();
println!("Successfully set admin! signature: {signature:#?}");
}