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
use std::{
    cmp,
    sync::{
        atomic::{AtomicBool, Ordering},
        Arc,
    },
};

use anchor_client::solana_sdk::{pubkey::Pubkey, signature::Keypair};
use anyhow::Result;
use console::style;
use futures::future::select_all;
use mpl_candy_machine::{accounts as nft_accounts, instruction as nft_instruction, ConfigLine};
pub use mpl_token_metadata::state::{
    MAX_CREATOR_LIMIT, MAX_NAME_LENGTH, MAX_SYMBOL_LENGTH, MAX_URI_LENGTH,
};

use crate::{
    cache::*, candy_machine::CANDY_MACHINE_ID, common::*, config::data::*, deploy::errors::*,
    setup::setup_client, utils::*,
};

/// The maximum config line bytes per transaction.
const MAX_TRANSACTION_BYTES: usize = 1000;

/// The maximum number of config lines per transaction.
const MAX_TRANSACTION_LINES: usize = 17;

pub struct TxInfo {
    candy_pubkey: Pubkey,
    payer: Keypair,
    chunk: Vec<(u32, ConfigLine)>,
}

/// Determine the config lines that need to be uploaded.
pub fn generate_config_lines(
    num_items: u64,
    cache_items: &CacheItems,
) -> Result<Vec<Vec<(u32, ConfigLine)>>> {
    let mut config_lines: Vec<Vec<(u32, ConfigLine)>> = Vec::new();
    let mut current: Vec<(u32, ConfigLine)> = Vec::new();
    let mut tx_size = 0;

    for i in 0..num_items {
        let item = match cache_items.get(&i.to_string()) {
            Some(item) => item,
            None => {
                return Err(
                    DeployError::AddConfigLineFailed(format!("Missing cache item {}", i)).into(),
                );
            }
        };

        if item.on_chain {
            // if the current item is on-chain already, store the previous
            // items as a transaction since we cannot have gaps in the indices
            // to write the config lines
            if !current.is_empty() {
                config_lines.push(current);
                current = Vec::new();
                tx_size = 0;
            }
        } else {
            let config_line = item
                .to_config_line()
                .expect("Could not convert item to config line");

            let size = (2 * STRING_LEN_SIZE) + config_line.name.len() + config_line.uri.len();

            if (tx_size + size) > MAX_TRANSACTION_BYTES || current.len() == MAX_TRANSACTION_LINES {
                // we need a separate tx to not break the size limit
                config_lines.push(current);
                current = Vec::new();
                tx_size = 0;
            }

            tx_size += size;
            current.push((i as u32, config_line));
        }
    }
    // adds the last chunk (if there is one)
    if !current.is_empty() {
        config_lines.push(current);
    }

    Ok(config_lines)
}

/// Send the config lines to the candy machine program.
pub async fn upload_config_lines(
    sugar_config: Arc<SugarConfig>,
    candy_pubkey: Pubkey,
    cache: &mut Cache,
    config_lines: Vec<Vec<(u32, ConfigLine)>>,
    interrupted: Arc<AtomicBool>,
) -> Result<Vec<DeployError>> {
    println!(
        "Sending config line(s) in {} transaction(s): (Ctrl+C to abort)",
        config_lines.len()
    );

    let pb = progress_bar_with_style(config_lines.len() as u64);

    debug!("Num of config line chunks: {:?}", config_lines.len());
    info!("Uploading config lines in chunks...");

    let mut transactions = Vec::new();

    for chunk in config_lines {
        let keypair = bs58::encode(sugar_config.keypair.to_bytes()).into_string();
        let payer = Keypair::from_base58_string(&keypair);

        transactions.push(TxInfo {
            candy_pubkey,
            payer,
            chunk,
        });
    }

    let mut handles = Vec::new();

    for tx in transactions.drain(0..cmp::min(transactions.len(), PARALLEL_LIMIT)) {
        let config = sugar_config.clone();
        handles.push(tokio::spawn(
            async move { add_config_lines(config, tx).await },
        ));
    }

    let mut errors = Vec::new();

    while !interrupted.load(Ordering::SeqCst) && !handles.is_empty() {
        match select_all(handles).await {
            (Ok(res), _index, remaining) => {
                // independently if the upload was successful or not
                // we continue to try the remaining ones
                handles = remaining;

                if res.is_ok() {
                    let indices = res?;

                    for index in indices {
                        let item = cache.items.get_mut(&index.to_string()).unwrap();
                        item.on_chain = true;
                    }
                    // updates the progress bar
                    pb.inc(1);
                } else {
                    // user will need to retry the upload
                    errors.push(DeployError::AddConfigLineFailed(format!(
                        "Transaction error: {:?}",
                        res.err().unwrap()
                    )));
                }
            }
            (Err(err), _index, remaining) => {
                // user will need to retry the upload
                errors.push(DeployError::AddConfigLineFailed(format!(
                    "Transaction error: {:?}",
                    err
                )));
                // ignoring all errors
                handles = remaining;
            }
        }

        if !transactions.is_empty() {
            // if we are half way through, let spawn more transactions
            if (PARALLEL_LIMIT - handles.len()) > (PARALLEL_LIMIT / 2) {
                // saves the progress to the cache file
                cache.sync_file()?;

                for tx in transactions.drain(0..cmp::min(transactions.len(), PARALLEL_LIMIT / 2)) {
                    let config = sugar_config.clone();
                    handles.push(tokio::spawn(
                        async move { add_config_lines(config, tx).await },
                    ));
                }
            }
        }
    }

    if !errors.is_empty() {
        pb.abandon_with_message(format!("{}", style("Deploy failed ").red().bold()));
    } else if !transactions.is_empty() {
        pb.abandon_with_message(format!("{}", style("Upload aborted ").red().bold()));
        return Err(DeployError::AddConfigLineFailed(
            "Not all config lines were deployed.".to_string(),
        )
        .into());
    } else {
        pb.finish_with_message(format!(
            "{}",
            style("Write config lines successful ").green().bold()
        ));
    }

    // makes sure the cache file is updated
    cache.sync_file()?;

    Ok(errors)
}

/// Send the `add_config_lines` instruction to the candy machine program.
pub async fn add_config_lines(config: Arc<SugarConfig>, tx_info: TxInfo) -> Result<Vec<u32>> {
    let client = setup_client(&config)?;
    let program = client.program(CANDY_MACHINE_ID);

    // this will be used to update the cache
    let mut indices: Vec<u32> = Vec::new();
    // configLine does not implement clone, so we have to do this
    let mut config_lines: Vec<ConfigLine> = Vec::new();
    // start index
    let start_index = tx_info.chunk[0].0;

    for (index, line) in tx_info.chunk {
        indices.push(index);
        config_lines.push(line);
    }

    let _sig = program
        .request()
        .accounts(nft_accounts::AddConfigLines {
            candy_machine: tx_info.candy_pubkey,
            authority: program.payer(),
        })
        .args(nft_instruction::AddConfigLines {
            index: start_index,
            config_lines,
        })
        .signer(&tx_info.payer)
        .send()?;

    Ok(indices)
}