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
use lpl_utils::assert_initialized;
use safecoin_program::{
    account_info::AccountInfo, entrypoint::ProgramResult, msg, program::invoke, program_pack::Pack,
    pubkey::Pubkey, rent::Rent, system_instruction, sysvar::Sysvar,
};
use safe_token::{native_mint::DECIMALS, state::Mint};

use crate::{
    error::MetadataError,
    instruction::{Context, Create, CreateArgs},
    state::{
        Metadata, ProgrammableConfig, TokenMetadataAccount, TokenStandard, MAX_MASTER_EDITION_LEN,
        TOKEN_STANDARD_INDEX,
    },
    utils::{
        create_master_edition, process_create_metadata_accounts_logic,
        CreateMetadataAccountsLogicArgs,
    },
};

/// Create the associated metadata accounts for a mint.
///
/// The instruction will also initialize the mint if the account does not
/// exist. For `NonFungible` assets, a `master_edition` account is required.
pub fn create<'a>(
    program_id: &Pubkey,
    accounts: &'a [AccountInfo<'a>],
    args: CreateArgs,
) -> ProgramResult {
    let context = Create::to_context(accounts)?;

    match args {
        CreateArgs::V1 { .. } => create_v1(program_id, context, args),
    }
}

/// V1 implementation of the create instruction.
fn create_v1(program_id: &Pubkey, ctx: Context<Create>, args: CreateArgs) -> ProgramResult {
    // get the args for the instruction
    let CreateArgs::V1 {
        ref asset_data,
        decimals,
        print_supply,
    } = args;

    // cannot create non-fungible editions on this instruction
    if matches!(asset_data.token_standard, TokenStandard::NonFungibleEdition) {
        return Err(MetadataError::InvalidTokenStandard.into());
    }

    // if the account does not exist, we will allocate a new mint

    if ctx.accounts.mint_info.data_is_empty() {
        // mint account must be a signer in the transaction
        if !ctx.accounts.mint_info.is_signer {
            return Err(MetadataError::MintIsNotSigner.into());
        }

        msg!("Init mint");

        invoke(
            &system_instruction::create_account(
                ctx.accounts.payer_info.key,
                ctx.accounts.mint_info.key,
                Rent::get()?.minimum_balance(safe_token::state::Mint::LEN),
                safe_token::state::Mint::LEN as u64,
                &safe_token::id(),
            ),
            &[
                ctx.accounts.payer_info.clone(),
                ctx.accounts.mint_info.clone(),
            ],
        )?;

        let decimals = match asset_data.token_standard {
            // for NonFungible variants, we ignore the argument and
            // always use 0 decimals
            TokenStandard::NonFungible | TokenStandard::ProgrammableNonFungible => 0,
            // for Fungile variants, we either use the specified decimals or the default
            // DECIMALS from safe-token 
            TokenStandard::FungibleAsset | TokenStandard::Fungible => match decimals {
                Some(decimals) => decimals,
                // if decimals not provided, use the default
                None => DECIMALS,
            },
            _ => {
                return Err(MetadataError::InvalidTokenStandard.into());
            }
        };

        // initializing the mint account
        invoke(
            &safe_token::instruction::initialize_mint2(
                ctx.accounts.safe_token_program_info.key,
                ctx.accounts.mint_info.key,
                ctx.accounts.authority_info.key,
                Some(ctx.accounts.authority_info.key),
                decimals,
            )?,
            &[
                ctx.accounts.mint_info.clone(),
                ctx.accounts.authority_info.clone(),
            ],
        )?;
    } else {
        // validates the existing mint account

        let mint: Mint = assert_initialized(ctx.accounts.mint_info, MetadataError::Uninitialized)?;
        // NonFungible assets must have decimals == 0 and supply no greater than 1
        if matches!(
            asset_data.token_standard,
            TokenStandard::NonFungible | TokenStandard::ProgrammableNonFungible
        ) && (mint.decimals > 0 || mint.supply > 1)
        {
            return Err(MetadataError::InvalidMintForTokenStandard.into());
        }
        // Programmable assets must have supply == 0
        if matches!(
            asset_data.token_standard,
            TokenStandard::ProgrammableNonFungible
        ) && (mint.supply > 0)
        {
            return Err(MetadataError::MintSupplyMustBeZero.into());
        }
    }

    // creates the metadata account

    process_create_metadata_accounts_logic(
        program_id,
        CreateMetadataAccountsLogicArgs {
            metadata_account_info: ctx.accounts.metadata_info,
            mint_info: ctx.accounts.mint_info,
            mint_authority_info: ctx.accounts.authority_info,
            payer_account_info: ctx.accounts.payer_info,
            update_authority_info: ctx.accounts.update_authority_info,
            system_account_info: ctx.accounts.system_program_info,
        },
        asset_data.as_data_v2(),
        false,
        asset_data.is_mutable,
        false,
        true,
        asset_data.collection_details.clone(),
    )?;

    // creates the master edition account (only for NonFungible assets)

    if matches!(
        asset_data.token_standard,
        TokenStandard::NonFungible | TokenStandard::ProgrammableNonFungible
    ) {
        let print_supply = print_supply.ok_or(MetadataError::MissingPrintSupply)?;

        if let Some(master_edition) = ctx.accounts.master_edition_info {
            create_master_edition(
                program_id,
                master_edition,
                ctx.accounts.mint_info,
                ctx.accounts.update_authority_info,
                ctx.accounts.authority_info,
                ctx.accounts.payer_info,
                ctx.accounts.metadata_info,
                ctx.accounts.safe_token_program_info,
                ctx.accounts.system_program_info,
                print_supply.to_option(),
            )?;

            // for pNFTs, we store the token standard value at the end of the
            // master edition account
            if matches!(
                asset_data.token_standard,
                TokenStandard::ProgrammableNonFungible
            ) {
                let mut data = master_edition.data.borrow_mut();

                if data.len() < MAX_MASTER_EDITION_LEN {
                    return Err(MetadataError::InvalidMasterEditionAccountLength.into());
                }

                data[TOKEN_STANDARD_INDEX] = TokenStandard::ProgrammableNonFungible as u8;
            }
        } else {
            return Err(MetadataError::MissingMasterEditionAccount.into());
        }
    } else if print_supply.is_some() {
        msg!("Ignoring print supply for selected token standard");
    }

    let mut metadata = Metadata::from_account_info(ctx.accounts.metadata_info)?;
    metadata.token_standard = Some(asset_data.token_standard);

    // sets the programmable config for programmable assets

    if matches!(
        asset_data.token_standard,
        TokenStandard::ProgrammableNonFungible
    ) {
        metadata.programmable_config = Some(ProgrammableConfig::V1 {
            rule_set: asset_data.rule_set,
        });
    }

    // saves the state
    metadata.save(&mut ctx.accounts.metadata_info.try_borrow_mut_data()?)?;

    Ok(())
}