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
use borsh::BorshSerialize;
use mpl_token_auth_rules::{
    instruction::{builders::ValidateBuilder, InstructionBuilder, ValidateArgs},
    payload::PayloadType,
};
use mpl_utils::{create_or_allocate_account_raw, token::TokenTransferParams};
use solana_program::{
    account_info::AccountInfo, entrypoint::ProgramResult, msg, program::invoke_signed,
    program_error::ProgramError, pubkey::Pubkey,
};
use spl_token::instruction::{freeze_account, thaw_account};

use crate::{
    assertions::{assert_derivation, programmable::assert_valid_authorization},
    error::MetadataError,
    pda::{EDITION, PREFIX},
    processor::{AuthorizationData, TransferScenario},
    state::{
        Operation, PayloadKey, ProgrammableConfig, ToAccountMeta, TokenMetadataAccount,
        TokenRecord, TOKEN_RECORD_SEED,
    },
};

pub fn create_token_record_account<'a>(
    program_id: &Pubkey,
    token_record_info: &'a AccountInfo<'a>,
    mint_info: &'a AccountInfo<'a>,
    token_info: &'a AccountInfo<'a>,
    payer_info: &'a AccountInfo<'a>,
    system_program_info: &'a AccountInfo<'a>,
) -> ProgramResult {
    if !token_record_info.data_is_empty() {
        return Err(MetadataError::DelegateAlreadyExists.into());
    }

    let mut signer_seeds = Vec::from([
        PREFIX.as_bytes(),
        crate::ID.as_ref(),
        mint_info.key.as_ref(),
        TOKEN_RECORD_SEED.as_bytes(),
        token_info.key.as_ref(),
    ]);

    let bump = &[assert_derivation(
        program_id,
        token_record_info,
        &signer_seeds,
    )?];
    signer_seeds.push(bump);

    // allocate the delegate account

    create_or_allocate_account_raw(
        *program_id,
        token_record_info,
        system_program_info,
        payer_info,
        TokenRecord::size(),
        &signer_seeds,
    )?;

    let token_record = TokenRecord {
        bump: bump[0],
        ..Default::default()
    };
    token_record.serialize(&mut *token_record_info.try_borrow_mut_data()?)?;

    Ok(())
}

pub fn freeze<'a>(
    mint: AccountInfo<'a>,
    token: AccountInfo<'a>,
    edition: AccountInfo<'a>,
    spl_token_program: AccountInfo<'a>,
) -> ProgramResult {
    let edition_info_path = Vec::from([
        PREFIX.as_bytes(),
        crate::ID.as_ref(),
        mint.key.as_ref(),
        EDITION.as_bytes(),
    ]);
    let edition_info_path_bump_seed = &[assert_derivation(
        &crate::id(),
        &edition,
        &edition_info_path,
    )?];
    let mut edition_info_seeds = edition_info_path.clone();
    edition_info_seeds.push(edition_info_path_bump_seed);

    invoke_signed(
        &freeze_account(spl_token_program.key, token.key, mint.key, edition.key, &[]).unwrap(),
        &[token, mint, edition],
        &[&edition_info_seeds],
    )?;
    Ok(())
}

pub fn thaw<'a>(
    mint_info: AccountInfo<'a>,
    token_info: AccountInfo<'a>,
    edition_info: AccountInfo<'a>,
    spl_token_program: AccountInfo<'a>,
) -> ProgramResult {
    let edition_info_path = Vec::from([
        PREFIX.as_bytes(),
        crate::ID.as_ref(),
        mint_info.key.as_ref(),
        EDITION.as_bytes(),
    ]);
    let edition_info_path_bump_seed = &[assert_derivation(
        &crate::id(),
        &edition_info,
        &edition_info_path,
    )?];
    let mut edition_info_seeds = edition_info_path.clone();
    edition_info_seeds.push(edition_info_path_bump_seed);

    invoke_signed(
        &thaw_account(
            spl_token_program.key,
            token_info.key,
            mint_info.key,
            edition_info.key,
            &[],
        )
        .unwrap(),
        &[token_info, mint_info, edition_info],
        &[&edition_info_seeds],
    )?;
    Ok(())
}

pub fn validate<'a>(
    ruleset: &'a AccountInfo<'a>,
    operation: Operation,
    mint_info: &'a AccountInfo<'a>,
    additional_rule_accounts: Vec<&'a AccountInfo<'a>>,
    auth_data: &AuthorizationData,
    rule_set_revision: Option<usize>,
) -> Result<(), ProgramError> {
    let account_metas = additional_rule_accounts
        .iter()
        .map(|account| account.to_account_meta())
        .collect();

    let validate_ix = ValidateBuilder::new()
        .rule_set_pda(*ruleset.key)
        .mint(*mint_info.key)
        .additional_rule_accounts(account_metas)
        .build(ValidateArgs::V1 {
            operation: operation.to_string(),
            payload: auth_data.payload.clone(),
            update_rule_state: false,
            rule_set_revision,
        })
        .map_err(|_error| MetadataError::InvalidAuthorizationRules)?
        .instruction();

    let mut account_infos = vec![ruleset.clone(), mint_info.clone()];
    account_infos.extend(additional_rule_accounts.into_iter().cloned());
    invoke_signed(&validate_ix, account_infos.as_slice(), &[])
}

#[derive(Debug, Clone)]
pub struct AuthRulesValidateParams<'a> {
    pub mint_info: &'a AccountInfo<'a>,
    pub source_info: Option<&'a AccountInfo<'a>>,
    pub destination_info: Option<&'a AccountInfo<'a>>,
    pub authority_info: Option<&'a AccountInfo<'a>>,
    pub owner_info: Option<&'a AccountInfo<'a>>,
    pub programmable_config: Option<ProgrammableConfig>,
    pub amount: u64,
    pub auth_data: Option<AuthorizationData>,
    pub auth_rules_info: Option<&'a AccountInfo<'a>>,
    pub operation: Operation,
    pub is_wallet_to_wallet: bool,
    pub rule_set_revision: Option<usize>,
}

pub fn auth_rules_validate(params: AuthRulesValidateParams) -> ProgramResult {
    let AuthRulesValidateParams {
        mint_info,
        owner_info,
        source_info,
        destination_info,
        authority_info,
        programmable_config,
        amount,
        auth_data,
        auth_rules_info,
        operation,
        is_wallet_to_wallet,
        rule_set_revision,
    } = params;

    if is_wallet_to_wallet {
        msg!("Wallet to wallet transfer. Skipping auth rules validation");
        return Ok(());
    }

    if let Operation::Transfer { scenario } = &operation {
        // Migration delegate is allowed to skip auth rules to guarantee that
        // it can transfer the asset.
        if matches!(scenario, TransferScenario::MigrationDelegate) {
            return Ok(());
        }
    }

    if let Some(ref config) = programmable_config {
        if let ProgrammableConfig::V1 { rule_set: Some(_) } = config {
            msg!("Programmable config exists");

            assert_valid_authorization(auth_rules_info, config)?;

            msg!("valid auth data. Adding rules...");
            // We can safely unwrap here because they were all checked for existence
            // in the assertion above.
            let auth_pda = auth_rules_info.unwrap();

            let mut auth_data = if let Some(auth_data) = auth_data {
                auth_data
            } else {
                AuthorizationData::new_empty()
            };

            let mut additional_rule_accounts = vec![];
            if let Some(target_info) = source_info {
                additional_rule_accounts.push(target_info);
            }
            if let Some(target_info) = destination_info {
                additional_rule_accounts.push(target_info);
            }
            if let Some(authority_info) = authority_info {
                additional_rule_accounts.push(authority_info);
            }
            if let Some(owner_info) = owner_info {
                additional_rule_accounts.push(owner_info);
            }

            // Insert auth rules for the operation type.
            match operation {
                Operation::Transfer { scenario: _ } => {
                    // Get account infos
                    let authority_info = authority_info.ok_or(MetadataError::InvalidOperation)?;
                    let source_info = source_info.ok_or(MetadataError::InvalidOperation)?;
                    let destination_info =
                        destination_info.ok_or(MetadataError::InvalidOperation)?;

                    // Transfer Amount
                    auth_data
                        .payload
                        .insert(PayloadKey::Amount.to_string(), PayloadType::Number(amount));

                    // Transfer Authority
                    auth_data.payload.insert(
                        PayloadKey::Authority.to_string(),
                        PayloadType::Pubkey(*authority_info.key),
                    );

                    // Transfer Source
                    auth_data.payload.insert(
                        PayloadKey::Source.to_string(),
                        PayloadType::Pubkey(*source_info.key),
                    );

                    // Transfer Destination
                    auth_data.payload.insert(
                        PayloadKey::Destination.to_string(),
                        PayloadType::Pubkey(*destination_info.key),
                    );
                }
                _ => {
                    return Err(MetadataError::InvalidOperation.into());
                }
            }

            validate(
                auth_pda,
                operation,
                mint_info,
                additional_rule_accounts,
                &auth_data,
                rule_set_revision,
            )?;
        }
    }
    Ok(())
}

pub fn frozen_transfer<'a, 'b>(
    params: TokenTransferParams<'a, 'b>,
    edition_opt_info: Option<&'a AccountInfo<'a>>,
) -> ProgramResult {
    if edition_opt_info.is_none() {
        return Err(MetadataError::MissingEditionAccount.into());
    }
    let master_edition_info = edition_opt_info.unwrap();

    thaw(
        params.mint.clone(),
        params.source.clone(),
        master_edition_info.clone(),
        params.token_program.clone(),
    )?;

    let mint_info = params.mint.clone();
    let dest_info = params.destination.clone();
    let token_program_info = params.token_program.clone();

    mpl_utils::token::spl_token_transfer(params).unwrap();

    freeze(
        mint_info,
        dest_info.clone(),
        master_edition_info.clone(),
        token_program_info.clone(),
    )?;

    Ok(())
}