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
mod bubblegum;
mod burn;
mod collection;
mod delegate;
mod edition;
pub(crate) mod escrow;
mod fee;
mod freeze;
mod metadata;
mod state;
mod uses;
mod verification;

use borsh::{BorshDeserialize, BorshSerialize};
pub use bubblegum::*;
pub use burn::*;
pub use collection::*;
pub use delegate::*;
pub use edition::*;
pub use escrow::*;
pub use freeze::*;
pub use metadata::*;
use mpl_token_auth_rules::payload::Payload;
#[cfg(feature = "serde-feature")]
use serde::{Deserialize, Serialize};
use solana_program::{
    account_info::AccountInfo, entrypoint::ProgramResult, msg, program_error::ProgramError,
    pubkey::Pubkey,
};
pub use state::*;
pub use uses::*;
pub use verification::*;

use crate::{
    error::MetadataError,
    instruction::{
        MetadataInstruction, CREATE_METADATA_ACCOUNT, CREATE_METADATA_ACCOUNT_V2,
        DEPRECATED_CREATE_MASTER_EDITION, DEPRECATED_CREATE_RESERVATION_LIST,
        DEPRECATED_MINT_NEW_EDITION_FROM_MASTER_EDITION_VIA_PRINTING_TOKEN,
        DEPRECATED_MINT_PRINTING_TOKENS, DEPRECATED_MINT_PRINTING_TOKENS_VIA_TOKEN,
        DEPRECATED_SET_RESERVATION_LIST, MIGRATE, UPDATE_METADATA_ACCOUNT,
    },
    processor::{
        edition::{
            process_convert_master_edition_v1_to_v2, process_create_master_edition,
            process_mint_new_edition_from_master_edition_via_token,
        },
        escrow::process_transfer_out_of_escrow,
    },
    state::{
        Key, Metadata, TokenMetadataAccount, TokenStandard, TokenState, DISCRIMINATOR_INDEX,
        TOKEN_STATE_INDEX,
    },
};

#[repr(C)]
#[cfg_attr(feature = "serde-feature", derive(Serialize, Deserialize))]
#[derive(BorshSerialize, BorshDeserialize, PartialEq, Eq, Debug, Clone)]
pub struct AuthorizationData {
    pub payload: Payload,
}

impl AuthorizationData {
    pub fn new(payload: Payload) -> Self {
        Self { payload }
    }
    pub fn new_empty() -> Self {
        Self {
            payload: Payload::new(),
        }
    }
}

/// Process Token Metadata instructions.
///
/// The processor is divided into two parts:
/// * It first tries to match the instruction into the new API;
/// * If it is not one of the new instructions, it checks that any metadata
///   account is not a pNFT before forwarding the transaction processing to
///   the "legacy" processor.
pub fn process_instruction<'a>(
    program_id: &'a Pubkey,
    accounts: &'a [AccountInfo<'a>],
    input: &[u8],
) -> ProgramResult {
    let (variant, _args) = input
        .split_first()
        .ok_or(MetadataError::InvalidInstruction)?;

    let instruction = match MetadataInstruction::try_from_slice(input) {
        Ok(instruction) => Ok(instruction),
        // Check if the instruction is a deprecated instruction.
        Err(_) => match *variant {
            CREATE_METADATA_ACCOUNT
            | UPDATE_METADATA_ACCOUNT
            | DEPRECATED_CREATE_MASTER_EDITION
            | DEPRECATED_MINT_NEW_EDITION_FROM_MASTER_EDITION_VIA_PRINTING_TOKEN
            | DEPRECATED_SET_RESERVATION_LIST
            | DEPRECATED_CREATE_RESERVATION_LIST
            | DEPRECATED_MINT_PRINTING_TOKENS_VIA_TOKEN
            | DEPRECATED_MINT_PRINTING_TOKENS
            | CREATE_METADATA_ACCOUNT_V2
            | MIGRATE => Err(MetadataError::Removed.into()),
            _ => Err(ProgramError::InvalidInstructionData),
        },
    }?;

    // checks if there is a locked token; this will block any instruction that
    // requires the token record account when the token is locked – 'Update' is
    // an example of an instruction that does not require the token record, so
    // it can be executed even when a token is locked
    if is_locked(program_id, accounts) && !matches!(instruction, MetadataInstruction::Unlock(_)) {
        return Err(MetadataError::LockedToken.into());
    }

    // match on the new instruction set
    match instruction {
        MetadataInstruction::Burn(args) => {
            msg!("IX: Burn");
            burn::burn(program_id, accounts, args)
        }
        MetadataInstruction::Create(args) => {
            msg!("IX: Create");
            metadata::create(program_id, accounts, args)
        }
        MetadataInstruction::Mint(args) => {
            msg!("IX: Mint");
            metadata::mint(program_id, accounts, args)
        }
        MetadataInstruction::Delegate(args) => {
            msg!("IX: Delegate");
            delegate::delegate(program_id, accounts, args)
        }
        MetadataInstruction::Revoke(args) => {
            msg!("IX: Revoke");
            delegate::revoke(program_id, accounts, args)
        }
        MetadataInstruction::Lock(args) => {
            msg!("IX: Lock");
            state::lock(program_id, accounts, args)
        }
        MetadataInstruction::Unlock(args) => {
            msg!("IX: Unlock");
            state::unlock(program_id, accounts, args)
        }
        MetadataInstruction::Migrate => Err(MetadataError::Removed.into()),
        MetadataInstruction::Transfer(args) => {
            msg!("IX: Transfer");
            metadata::transfer(program_id, accounts, args)
        }
        MetadataInstruction::Update(args) => {
            msg!("IX: Update");
            metadata::update(program_id, accounts, args)
        }
        MetadataInstruction::Verify(args) => {
            msg!("IX: Verify");
            verification::verify(program_id, accounts, args)
        }
        MetadataInstruction::Unverify(args) => {
            msg!("IX: Unverify");
            verification::unverify(program_id, accounts, args)
        }
        MetadataInstruction::Collect => fee::process_collect_fees(program_id, accounts),
        MetadataInstruction::Print(args) => {
            msg!("IX: Print");
            metadata::print(program_id, accounts, args)
        }
        _ => {
            // pNFT accounts can only be used by the "new" API; before forwarding
            // the transaction to the "legacy" processor we determine whether we are
            // dealing with a pNFT or not
            if !has_programmable_metadata(program_id, accounts)? {
                process_legacy_instruction(program_id, accounts, instruction)
            } else {
                Err(MetadataError::InstructionNotSupported.into())
            }
        }
    }
}

/// Matches "legacy" (pre-pNFT) instructions.
fn process_legacy_instruction<'a>(
    program_id: &'a Pubkey,
    accounts: &'a [AccountInfo<'a>],
    instruction: MetadataInstruction,
) -> ProgramResult {
    match instruction {
        MetadataInstruction::CreateMetadataAccount => Err(MetadataError::Removed.into()),
        MetadataInstruction::UpdateMetadataAccount => Err(MetadataError::Removed.into()),
        MetadataInstruction::CreateMetadataAccountV2 => Err(MetadataError::Removed.into()),
        MetadataInstruction::CreateMetadataAccountV3(args) => {
            msg!("IX: Create Metadata Accounts v3");
            process_create_metadata_accounts_v3(
                program_id,
                accounts,
                args.data,
                args.is_mutable,
                args.collection_details,
            )
        }
        MetadataInstruction::UpdateMetadataAccountV2(args) => {
            msg!("IX: Update Metadata Accounts v2");
            process_update_metadata_accounts_v2(
                program_id,
                accounts,
                args.data,
                args.update_authority,
                args.primary_sale_happened,
                args.is_mutable,
            )
        }
        MetadataInstruction::DeprecatedCreateMasterEdition => Err(MetadataError::Removed.into()),
        MetadataInstruction::DeprecatedMintNewEditionFromMasterEditionViaPrintingToken => {
            Err(MetadataError::Removed.into())
        }
        MetadataInstruction::UpdatePrimarySaleHappenedViaToken => {
            msg!("IX: Update primary sale via token");
            process_update_primary_sale_happened_via_token(program_id, accounts)
        }
        MetadataInstruction::DeprecatedSetReservationList => Err(MetadataError::Removed.into()),
        MetadataInstruction::DeprecatedCreateReservationList => Err(MetadataError::Removed.into()),
        MetadataInstruction::SignMetadata => {
            msg!("IX: Sign Metadata");
            process_sign_metadata(program_id, accounts)
        }
        MetadataInstruction::RemoveCreatorVerification => {
            msg!("IX: Remove Creator Verification");
            process_remove_creator_verification(program_id, accounts)
        }
        MetadataInstruction::DeprecatedMintPrintingTokensViaToken => {
            Err(MetadataError::Removed.into())
        }
        MetadataInstruction::DeprecatedMintPrintingTokens => Err(MetadataError::Removed.into()),
        MetadataInstruction::CreateMasterEdition => Err(MetadataError::Removed.into()),
        MetadataInstruction::CreateMasterEditionV3(args) => {
            msg!("V3 Create Master Edition");
            process_create_master_edition(program_id, accounts, args.max_supply)
        }
        MetadataInstruction::MintNewEditionFromMasterEditionViaToken(args) => {
            msg!("IX: Mint New Edition from Master Edition Via Token");
            process_mint_new_edition_from_master_edition_via_token(
                program_id,
                accounts,
                args.edition,
            )
        }
        MetadataInstruction::ConvertMasterEditionV1ToV2 => {
            msg!("IX: Convert Master Edition V1 to V2");
            process_convert_master_edition_v1_to_v2(program_id, accounts)
        }
        MetadataInstruction::MintNewEditionFromMasterEditionViaVaultProxy(_args) => {
            Err(MetadataError::Removed.into())
        }
        MetadataInstruction::PuffMetadata => {
            msg!("IX: Puff Metadata");
            process_puff_metadata_account(program_id, accounts)
        }
        MetadataInstruction::VerifyCollection => {
            msg!("IX: Verify Collection");
            verify_collection(program_id, accounts)
        }
        MetadataInstruction::SetAndVerifyCollection => {
            msg!("IX: Set and Verify Collection");
            set_and_verify_collection(program_id, accounts)
        }
        MetadataInstruction::UnverifyCollection => {
            msg!("IX: Unverify Collection");
            unverify_collection(program_id, accounts)
        }
        MetadataInstruction::Utilize(args) => {
            msg!("IX: Use/Utilize Token");
            process_utilize(program_id, accounts, args.number_of_uses)
        }
        MetadataInstruction::ApproveUseAuthority(args) => {
            msg!("IX: Approve Use Authority");
            process_approve_use_authority(program_id, accounts, args.number_of_uses)
        }
        MetadataInstruction::RevokeUseAuthority => {
            msg!("IX: Revoke Use Authority");
            process_revoke_use_authority(program_id, accounts)
        }
        MetadataInstruction::ApproveCollectionAuthority => {
            msg!("IX: Approve Collection Authority");
            process_approve_collection_authority(program_id, accounts)
        }
        MetadataInstruction::RevokeCollectionAuthority => {
            msg!("IX: Revoke Collection Authority");
            process_revoke_collection_authority(program_id, accounts)
        }
        MetadataInstruction::FreezeDelegatedAccount => {
            msg!("IX: Freeze Delegated Account");
            process_freeze_delegated_account(program_id, accounts)
        }
        MetadataInstruction::ThawDelegatedAccount => {
            msg!("IX: Thaw Delegated Account");
            process_thaw_delegated_account(program_id, accounts)
        }
        MetadataInstruction::BurnNft => {
            msg!("IX: Burn NFT");
            process_burn_nft(program_id, accounts)
        }
        MetadataInstruction::BurnEditionNft => {
            msg!("IX: Burn Edition NFT");
            process_burn_edition_nft(program_id, accounts)
        }
        MetadataInstruction::VerifySizedCollectionItem => {
            msg!("IX: Verify Collection V2");
            verify_sized_collection_item(program_id, accounts)
        }
        MetadataInstruction::SetAndVerifySizedCollectionItem => {
            msg!("IX: Set and Verify Collection");
            set_and_verify_sized_collection_item(program_id, accounts)
        }
        MetadataInstruction::UnverifySizedCollectionItem => {
            msg!("IX: Unverify Sized Collection");
            unverify_sized_collection_item(program_id, accounts)
        }
        MetadataInstruction::SetCollectionSize(args) => {
            msg!("IX: Set Collection Size");
            set_collection_size(program_id, accounts, args)
        }
        MetadataInstruction::SetTokenStandard => {
            msg!("IX: Set Token Standard");
            process_set_token_standard(program_id, accounts)
        }
        MetadataInstruction::BubblegumSetCollectionSize(args) => {
            msg!("IX: Bubblegum Program Set Collection Size");
            bubblegum_set_collection_size(program_id, accounts, args)
        }
        MetadataInstruction::CreateEscrowAccount => {
            msg!("IX: Create Escrow Account");
            process_create_escrow_account(program_id, accounts)
        }
        MetadataInstruction::CloseEscrowAccount => {
            msg!("IX: Close Escrow Account");
            process_close_escrow_account(program_id, accounts)
        }
        MetadataInstruction::TransferOutOfEscrow(args) => {
            msg!("IX: Transfer Out Of Escrow");
            process_transfer_out_of_escrow(program_id, accounts, args)
        }
        _ => Err(ProgramError::InvalidInstructionData),
    }
}

/// Checks if the instruction's accounts contain a pNFT metadata.
///
/// We need to determine if we are dealing with a pNFT metadata or not
/// so we can restrict the available instructions.
fn has_programmable_metadata(
    program_id: &Pubkey,
    accounts: &[AccountInfo],
) -> Result<bool, ProgramError> {
    for account_info in accounts {
        // checks the account is owned by Token Metadata and it has data
        if account_info.owner == program_id && !account_info.data_is_empty() {
            let discriminator = account_info.data.borrow()[DISCRIMINATOR_INDEX];
            // checks if the account is a Metadata account
            if discriminator == Key::MetadataV1 as u8 {
                let metadata = Metadata::from_account_info(account_info)?;

                if matches!(
                    metadata.token_standard,
                    Some(TokenStandard::ProgrammableNonFungible)
                ) {
                    return Ok(true);
                }
            }
        }
    }

    Ok(false)
}

/// Checks if the instruction's accounts contain a locked pNFT.
fn is_locked(program_id: &Pubkey, accounts: &[AccountInfo]) -> bool {
    for account_info in accounts {
        // checks the account is owned by Token Metadata and it has data
        if account_info.owner == program_id && !account_info.data_is_empty() {
            let data = account_info.data.borrow();
            // checks if the account is a Metadata account
            if (data[DISCRIMINATOR_INDEX] == Key::TokenRecord as u8)
                && (data[TOKEN_STATE_INDEX] == TokenState::Locked as u8)
            {
                return true;
            }
        }
    }

    false
}

macro_rules! all_account_infos {
    ($accounts:expr, $($account:ident),*) => {
        let [$($account),*] = match $accounts {
            [$($account),*, ..] => [$($account),*],
            _ => return Err(solana_program::program_error::ProgramError::NotEnoughAccountKeys),
        };
    };
}

pub(crate) use all_account_infos;