forked from samuelvanderwaal/metaboss
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmint.rs
648 lines (581 loc) · 18.1 KB
/
mint.rs
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
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
use anyhow::{anyhow, Result};
use glob::glob;
use log::{error, info};
use metaboss_lib::decode::*;
use mpl_token_metadata::{
instruction::{
create_master_edition, create_metadata_accounts_v2,
mint_new_edition_from_master_edition_via_token, update_metadata_accounts_v2,
},
ID as TOKEN_METADATA_PROGRAM_ID,
};
use rayon::prelude::*;
use reqwest;
use retry::{delay::Exponential, retry};
use serde::Serialize;
use serde_json::Value;
use solana_client::rpc_client::RpcClient;
use solana_sdk::{
pubkey::Pubkey,
signature::Signature,
signer::{keypair::Keypair, Signer},
system_instruction::create_account,
transaction::Transaction,
};
use spl_associated_token_account::{
get_associated_token_address, instruction::create_associated_token_account,
};
use spl_token::{
instruction::{initialize_mint, mint_to},
ID as TOKEN_PROGRAM_ID,
};
use std::{fs, fs::File, path::Path, str::FromStr};
use crate::derive::derive_edition_pda;
use crate::sign::sign_one;
use crate::{constants::*, parse::convert_local_to_remote_data};
use crate::{data::NFTData, derive::derive_metadata_pda};
use crate::{find::find_missing_editions, parse::*};
use crate::{limiter::create_default_rate_limiter, spinner::create_spinner};
const MINT_LAYOUT: u64 = 82;
#[allow(clippy::too_many_arguments)]
pub fn mint_list(
client: &RpcClient,
keypair_path: Option<String>,
receiver: Option<String>,
list_dir: Option<String>,
external_metadata_uris: Option<String>,
immutable: bool,
primary_sale_happened: bool,
sign: bool,
track: bool,
) -> Result<()> {
if !is_only_one_option(&list_dir, &external_metadata_uris) {
return Err(anyhow!(
"Only one of --list-dir or --external-metadata-uris can be specified"
));
}
let max_editions = 0;
if let Some(list_dir) = list_dir {
mint_from_files(
client,
keypair_path,
receiver,
list_dir,
immutable,
primary_sale_happened,
max_editions,
sign,
)?;
} else if let Some(external_metadata_uris) = external_metadata_uris {
mint_from_uris(
client,
keypair_path,
receiver,
external_metadata_uris,
immutable,
primary_sale_happened,
max_editions,
sign,
track,
)?;
} else {
return Err(anyhow!(
"Either --list-dir or --external-metadata-uris must be specified"
));
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn mint_from_files(
client: &RpcClient,
keypair_path: Option<String>,
receiver: Option<String>,
list_dir: String,
immutable: bool,
primary_sale_happened: bool,
max_editions: i64,
sign: bool,
) -> Result<()> {
let use_rate_limit = *USE_RATE_LIMIT.read().unwrap();
let handle = create_default_rate_limiter();
let path = Path::new(&list_dir).join("*.json");
let pattern = path
.to_str()
.ok_or_else(|| anyhow!("Invalid directory path"))?;
let (paths, errors): (Vec<_>, Vec<_>) = glob(pattern)?.into_iter().partition(Result::is_ok);
let paths: Vec<_> = paths.into_iter().map(Result::unwrap).collect();
let errors: Vec<_> = errors.into_iter().map(Result::unwrap_err).collect();
paths.par_iter().for_each(|path| {
let mut handle = handle.clone();
if use_rate_limit {
handle.wait();
}
match mint_one(
client,
keypair_path.clone(),
&receiver,
Some(path),
None,
immutable,
primary_sale_happened,
max_editions,
sign,
) {
Ok(_) => (),
Err(e) => error!("Failed to mint {:?}: {}", &path, e),
}
});
// TODO: handle errors in a better way.
if !errors.is_empty() {
error!("Failed to read some of the files with the following errors:");
for error in errors {
error!("{}", error);
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn mint_from_uris(
client: &RpcClient,
keypair_path: Option<String>,
receiver: Option<String>,
external_metadata_uris_path: String,
immutable: bool,
primary_sale_happened: bool,
max_editions: i64,
sign: bool,
track: bool,
) -> Result<()> {
let f = File::open(&external_metadata_uris_path)?;
let external_metadata_uris: Vec<String> = serde_json::from_reader(f)?;
if !track {
external_metadata_uris
.par_iter()
// .progress()
.for_each(|uri| {
match mint_one(
client,
keypair_path.clone(),
&receiver,
None::<String>,
Some(uri),
immutable,
primary_sale_happened,
max_editions,
sign,
) {
Ok(_) => (),
Err(e) => println!("Failed to mint {:?}: {}", &uri, e),
}
});
} else {
#[derive(Serialize)]
struct MintResult {
pub uri: String,
pub mint_account: Option<String>,
}
// Minted file contains all succesful MintResults, unminted file simply contains
// a list of unminted uris to make it easier to resume minting.
let minted_path = external_metadata_uris_path.replace(".json", "-output.json");
let unminted_path = external_metadata_uris_path.replace(".json", "-unminted.json");
let mut minted: Vec<&MintResult> = Vec::new();
let mut unminted: Vec<String> = Vec::new();
let results: Vec<MintResult> = external_metadata_uris
.par_iter()
.map(|uri| -> MintResult {
match mint_one(
client,
keypair_path.clone(),
&receiver,
None::<String>,
Some(uri),
immutable,
primary_sale_happened,
max_editions,
sign,
) {
Ok(m) => MintResult {
uri: uri.clone(),
mint_account: Some(m),
},
Err(e) => {
error!("Failed to mint {:?}: {}", &uri, e);
MintResult {
uri: uri.clone(),
mint_account: None,
}
}
}
})
.collect();
results.iter().for_each(|result| {
if result.mint_account.is_none() {
unminted.push(result.uri.clone())
} else {
minted.push(result)
}
});
if !unminted.is_empty() {
fs::write(unminted_path, serde_json::to_string_pretty(&unminted)?)?;
}
if !minted.is_empty() {
fs::write(minted_path, serde_json::to_string_pretty(&minted)?)?;
}
}
Ok(())
}
#[allow(clippy::too_many_arguments)]
pub fn mint_one<P: AsRef<Path>>(
client: &RpcClient,
keypair_path: Option<String>,
receiver: &Option<String>,
nft_data_file: Option<P>,
external_metadata_uri: Option<&String>,
immutable: bool,
primary_sale_happened: bool,
max_editions: i64,
sign: bool,
) -> Result<String> {
if !is_only_one_option(&nft_data_file, &external_metadata_uri) {
return Err(anyhow!(
"You must supply either --nft_data_file or --external-metadata-uris but not both"
));
}
let solana_opts = parse_solana_config();
let keypair = parse_keypair(keypair_path.clone(), solana_opts);
let receiver = if let Some(address) = receiver {
Pubkey::from_str(address)?
} else {
keypair.pubkey()
};
let nft_data: NFTData = if let Some(nft_data_file) = nft_data_file {
let f = File::open(nft_data_file)?;
serde_json::from_reader(f)?
} else if let Some(external_metadata_uri) = external_metadata_uri {
let body: Value = reqwest::blocking::get(external_metadata_uri)?.json()?;
let creators_json = body
.get("properties")
.ok_or_else(|| anyhow!("Bad JSON"))?
.get("creators")
.ok_or_else(|| anyhow!("Bad JSON"))?;
let name = parse_name(&body)?;
let creators = parse_creators(creators_json)?;
let symbol = parse_symbol(&body)?;
let seller_fee_basis_points = parse_seller_fee_basis_points(&body)?;
NFTData {
name,
symbol,
creators: Some(creators),
uri: external_metadata_uri.to_string(),
seller_fee_basis_points,
}
} else {
return Err(anyhow!(
"You must supply either --nft_data_file or --external-metadata-uris but not both"
));
};
let (tx_id, mint_account) = mint(
client,
keypair,
receiver,
nft_data,
immutable,
primary_sale_happened,
max_editions,
)?;
info!("Tx id: {:?}\nMint account: {:?}", &tx_id, &mint_account);
let message = format!("Tx id: {:?}\nMint account: {:?}", &tx_id, &mint_account,);
println!("{}", message);
if sign {
//TODO: Error handling
sign_one(client, keypair_path, mint_account.to_string())?;
}
Ok(mint_account.to_string())
}
pub fn mint_editions(
client: &RpcClient,
keypair_path: Option<String>,
account: String,
receiver: &Option<String>,
next_editions: Option<u64>,
specific_editions: Option<Vec<u64>>,
) -> Result<()> {
let spinner = create_spinner("Minting...");
if let Some(next_editions) = next_editions {
for _ in 0..next_editions {
mint_next_edition(client, &keypair_path, &account, receiver)?;
}
return Ok(());
}
if let Some(specific_editions) = specific_editions {
for num in specific_editions {
mint_edition(client, &keypair_path, &account, num, receiver)?;
}
return Ok(());
}
spinner.finish();
Ok(())
}
fn mint_next_edition(
client: &RpcClient,
keypair_path: &Option<String>,
account: &str,
receiver: &Option<String>,
) -> Result<()> {
// Send tx with retries.
let master_edition_res = retry(
Exponential::from_millis_with_factor(250, 2.0).take(3),
|| decode_master_edition_from_mint(client, account),
);
// Get current edition number
let master_edition = master_edition_res?;
let current_edition_num = master_edition.supply;
let next_edition_num = current_edition_num + 1;
if let Some(max_supply) = master_edition.max_supply {
if next_edition_num > max_supply {
return Err(anyhow!(
"Next edition number {} is greater than max_supply {}",
next_edition_num,
max_supply
));
}
}
mint_edition(client, keypair_path, account, next_edition_num, receiver)?;
Ok(())
}
fn mint_edition(
client: &RpcClient,
keypair_path: &Option<String>,
account: &str,
edition_num: u64,
receiver: &Option<String>,
) -> Result<(Signature, Pubkey)> {
let solana_opts = parse_solana_config();
let funder = parse_keypair(keypair_path.clone(), solana_opts);
let metadata_mint = Pubkey::from_str(account)?;
let new_mint_keypair = Keypair::new();
let new_mint = new_mint_keypair.pubkey();
let receiver = if let Some(address) = receiver {
Pubkey::from_str(address)?
} else {
funder.pubkey()
};
let master_edition = derive_edition_pda(&metadata_mint);
let new_edition = derive_edition_pda(&new_mint);
let metadata = derive_metadata_pda(&metadata_mint);
let new_metadata = derive_metadata_pda(&new_mint);
// Allocate memory for the account
let min_rent = client.get_minimum_balance_for_rent_exemption(MINT_LAYOUT as usize)?;
// Create mint account
let create_mint_account_ix = create_account(
&funder.pubkey(),
&new_mint,
min_rent,
MINT_LAYOUT,
&TOKEN_PROGRAM_ID,
);
// Initalize mint ix
let init_mint_ix = initialize_mint(
&TOKEN_PROGRAM_ID,
&new_mint,
&funder.pubkey(),
Some(&funder.pubkey()),
0,
)?;
// Derive associated token account
let assoc = get_associated_token_address(&funder.pubkey(), &metadata_mint);
let new_assoc = get_associated_token_address(&receiver, &new_mint);
let create_assoc_account_ix =
create_associated_token_account(&funder.pubkey(), &receiver, &new_mint);
// Mint to instruction
let mint_to_ix = mint_to(
&TOKEN_PROGRAM_ID,
&new_mint,
&new_assoc,
&funder.pubkey(),
&[],
1,
)?;
let mint_editions_ix = mint_new_edition_from_master_edition_via_token(
TOKEN_METADATA_PROGRAM_ID,
new_metadata,
new_edition,
master_edition,
new_mint,
funder.pubkey(),
funder.pubkey(),
funder.pubkey(),
assoc,
funder.pubkey(),
metadata,
metadata_mint,
edition_num,
);
let instructions = vec![
create_mint_account_ix,
init_mint_ix,
create_assoc_account_ix,
mint_to_ix,
mint_editions_ix,
];
let recent_blockhash = client.get_latest_blockhash()?;
let tx = Transaction::new_signed_with_payer(
&instructions,
Some(&funder.pubkey()),
&[&funder, &new_mint_keypair],
recent_blockhash,
);
// Send tx with retries.
let res = retry(
Exponential::from_millis_with_factor(250, 2.0).take(3),
|| client.send_and_confirm_transaction(&tx),
);
let sig = res?;
println!("Edition with mint: {:?}", &new_mint);
println!("Created in tx: {:?}", &sig);
Ok((sig, new_mint))
}
pub fn mint_missing_editions(
client: &RpcClient,
keypair_path: &Option<String>,
mint_account: &str,
) -> Result<()> {
let missing_editions = find_missing_editions(client, mint_account)?;
let spinner = create_spinner("Printing missing editions");
for missing_edition in missing_editions {
mint_edition(client, keypair_path, mint_account, missing_edition, &None)?;
}
spinner.finish();
Ok(())
}
pub fn mint(
client: &RpcClient,
funder: Keypair,
receiver: Pubkey,
nft_data: NFTData,
immutable: bool,
primary_sale_happened: bool,
max_editions: i64,
) -> Result<(Signature, Pubkey)> {
let metaplex_program_id = Pubkey::from_str(METAPLEX_PROGRAM_ID)?;
let mint = Keypair::new();
// Max editions of -1 means infinite supply (max_supply = None)
// Otherwise max_supply is the number of editions
let max_supply = if max_editions == -1 {
None
} else {
Some(max_editions as u64)
};
// Convert local NFTData type to Metaplex Data type
let data = convert_local_to_remote_data(nft_data)?;
// Allocate memory for the account
let min_rent = client.get_minimum_balance_for_rent_exemption(MINT_LAYOUT as usize)?;
// Create mint account
let create_mint_account_ix = create_account(
&funder.pubkey(),
&mint.pubkey(),
min_rent,
MINT_LAYOUT,
&TOKEN_PROGRAM_ID,
);
// Initalize mint ix
let init_mint_ix = initialize_mint(
&TOKEN_PROGRAM_ID,
&mint.pubkey(),
&funder.pubkey(),
Some(&funder.pubkey()),
0,
)?;
// Derive associated token account
let assoc = get_associated_token_address(&receiver, &mint.pubkey());
// Create associated account instruction
let create_assoc_account_ix =
create_associated_token_account(&funder.pubkey(), &receiver, &mint.pubkey());
// Mint to instruction
let mint_to_ix = mint_to(
&TOKEN_PROGRAM_ID,
&mint.pubkey(),
&assoc,
&funder.pubkey(),
&[],
1,
)?;
// Derive metadata account
let metadata_seeds = &[
"metadata".as_bytes(),
&metaplex_program_id.to_bytes(),
&mint.pubkey().to_bytes(),
];
let (metadata_account, _pda) =
Pubkey::find_program_address(metadata_seeds, &metaplex_program_id);
// Derive Master Edition account
let master_edition_seeds = &[
"metadata".as_bytes(),
&metaplex_program_id.to_bytes(),
&mint.pubkey().to_bytes(),
"edition".as_bytes(),
];
let (master_edition_account, _pda) =
Pubkey::find_program_address(master_edition_seeds, &metaplex_program_id);
let create_metadata_account_ix = create_metadata_accounts_v2(
metaplex_program_id,
metadata_account,
mint.pubkey(),
funder.pubkey(),
funder.pubkey(),
funder.pubkey(),
data.name,
data.symbol,
data.uri,
data.creators,
data.seller_fee_basis_points,
true,
!immutable,
None,
None,
);
let create_master_edition_account_ix = create_master_edition(
metaplex_program_id,
master_edition_account,
mint.pubkey(),
funder.pubkey(),
funder.pubkey(),
metadata_account,
funder.pubkey(),
max_supply,
);
let mut instructions = vec![
create_mint_account_ix,
init_mint_ix,
create_assoc_account_ix,
mint_to_ix,
create_metadata_account_ix,
create_master_edition_account_ix,
];
if primary_sale_happened {
let ix = update_metadata_accounts_v2(
metaplex_program_id,
metadata_account,
funder.pubkey(),
None,
None,
Some(true),
None,
);
instructions.push(ix);
}
let recent_blockhash = client.get_latest_blockhash()?;
let tx = Transaction::new_signed_with_payer(
&instructions,
Some(&funder.pubkey()),
&[&funder, &mint],
recent_blockhash,
);
// Send tx with retries.
let res = retry(
Exponential::from_millis_with_factor(250, 2.0).take(3),
|| client.send_and_confirm_transaction(&tx),
);
let sig = res?;
Ok((sig, mint.pubkey()))
}