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
use solana_program::{account_info::AccountInfo, program_error::ProgramError, pubkey::Pubkey};

use crate::{
    assertions::assert_derivation,
    error::MetadataError,
    pda::find_collection_authority_account,
    state::{
        Collection, CollectionAuthorityRecord, MasterEditionV2, Metadata, TokenMetadataAccount,
        TokenStandard, EDITION, PREFIX,
    },
};

/// Checks whether the collection update is allowed or not based on the `verified` status.
pub fn assert_collection_update_is_valid(
    edition: bool,
    existing: &Option<Collection>,
    incoming: &Option<Collection>,
) -> Result<(), ProgramError> {
    let is_incoming_verified = if let Some(status) = incoming {
        status.verified
    } else {
        false
    };

    let is_existing_verified = if let Some(status) = existing {
        status.verified
    } else {
        false
    };

    let valid_update = if is_incoming_verified {
        // verified: can only update if the details match
        is_existing_verified && (existing.as_ref().unwrap().key == incoming.as_ref().unwrap().key)
    } else {
        // unverified: can only update if existing is unverified
        !is_existing_verified
    };

    // overrule: if we are dealing with an edition
    if !valid_update && !edition {
        return Err(MetadataError::CollectionCannotBeVerifiedInThisInstruction.into());
    }

    Ok(())
}

pub fn assert_is_collection_delegated_authority(
    authority_record: &AccountInfo,
    collection_authority: &Pubkey,
    mint: &Pubkey,
) -> Result<u8, ProgramError> {
    let (pda, bump) = find_collection_authority_account(mint, collection_authority);
    if pda != *authority_record.key {
        return Err(MetadataError::DerivedKeyInvalid.into());
    }
    Ok(bump)
}

pub fn assert_has_collection_authority(
    collection_authority_info: &AccountInfo,
    collection_data: &Metadata,
    mint: &Pubkey,
    delegate_collection_authority_record: Option<&AccountInfo>,
) -> Result<(), ProgramError> {
    // Mint is the correct one for the metadata account.
    if collection_data.mint != *mint {
        return Err(MetadataError::MintMismatch.into());
    }

    if let Some(collection_authority_record) = delegate_collection_authority_record {
        let bump = assert_is_collection_delegated_authority(
            collection_authority_record,
            collection_authority_info.key,
            mint,
        )?;
        let data = collection_authority_record.try_borrow_data()?;
        if data.len() == 0 {
            return Err(MetadataError::InvalidCollectionUpdateAuthority.into());
        }
        let record = CollectionAuthorityRecord::from_bytes(&data)?;
        if record.bump != bump {
            return Err(MetadataError::InvalidCollectionUpdateAuthority.into());
        }
        match record.update_authority {
            Some(update_authority) => {
                if update_authority != collection_data.update_authority {
                    return Err(MetadataError::InvalidCollectionUpdateAuthority.into());
                }
            }
            None => return Err(MetadataError::InvalidCollectionUpdateAuthority.into()),
        }
    } else if collection_data.update_authority != *collection_authority_info.key {
        return Err(MetadataError::InvalidCollectionUpdateAuthority.into());
    }
    Ok(())
}

pub fn assert_collection_verify_is_valid(
    member_collection: &Option<Collection>,
    collection_data: &Metadata,
    collection_mint: &AccountInfo,
    edition_account_info: &AccountInfo,
) -> Result<(), ProgramError> {
    match member_collection {
        Some(collection) => {
            if collection.key != *collection_mint.key
                || collection_data.mint != *collection_mint.key
            {
                return Err(MetadataError::CollectionNotFound.into());
            }
        }
        None => {
            return Err(MetadataError::CollectionNotFound.into());
        }
    }

    assert_derivation(
        &crate::id(),
        edition_account_info,
        &[
            PREFIX.as_bytes(),
            crate::id().as_ref(),
            collection_data.mint.as_ref(),
            EDITION.as_bytes(),
        ],
    )
    .map_err(|_| MetadataError::CollectionMasterEditionAccountInvalid)?;

    assert_master_edition(collection_data, edition_account_info)?;
    Ok(())
}

pub fn assert_master_edition(
    collection_data: &Metadata,
    edition_account_info: &AccountInfo,
) -> Result<(), ProgramError> {
    let edition = MasterEditionV2::from_account_info(edition_account_info)
        .map_err(|_err: ProgramError| MetadataError::CollectionMustBeAUniqueMasterEdition)?;
    if collection_data.token_standard != Some(TokenStandard::NonFungible)
        || edition.max_supply != Some(0)
    {
        return Err(MetadataError::CollectionMustBeAUniqueMasterEdition.into());
    }
    Ok(())
}

#[cfg(test)]
pub mod tests {
    use super::*;

    #[test]
    fn test_assert_collection_update_is_valid() {
        let key_1 = Pubkey::new_unique();
        let key_2 = Pubkey::new_unique();

        // collection 1

        let collection_key1_false = Collection {
            key: key_1,
            verified: false,
        };

        let collection_key1_true = Collection {
            key: key_1,
            verified: true,
        };

        // collection 2

        let collection_key2_false = Collection {
            key: key_2,
            verified: false,
        };

        let collection_key2_true = Collection {
            key: key_2,
            verified: true,
        };

        // [OK] "unverified" same collection details

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_false.clone()),
            &Some(collection_key1_false.clone()),
        )
        .unwrap();

        // [OK] "verified" same collection details

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_true.clone()),
            &Some(collection_key1_true.clone()),
        )
        .unwrap();

        // [ERROR] "unverify" collection

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_true.clone()),
            &Some(collection_key1_false.clone()),
        )
        .unwrap_err();

        // [ERROR] "verify" collection

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_false.clone()),
            &Some(collection_key1_true.clone()),
        )
        .unwrap_err();

        // [OK] "unverified" update collection details

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_false.clone()),
            &Some(collection_key2_false.clone()),
        )
        .unwrap();

        // [ERROR] "verified" update collection details

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_false),
            &Some(collection_key2_true.clone()),
        )
        .unwrap_err();

        // [ERROR] "verified" update collection details

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_true.clone()),
            &Some(collection_key2_false),
        )
        .unwrap_err();

        // [ERROR] "verified" update collection details

        assert_collection_update_is_valid(
            false,
            &Some(collection_key1_true.clone()),
            &Some(collection_key2_true.clone()),
        )
        .unwrap_err();

        // [OK] "edition" override

        assert_collection_update_is_valid(
            true,
            &Some(collection_key1_true),
            &Some(collection_key2_true),
        )
        .unwrap();
    }
}