Skip to main content

mpl_core/hooked/
mod.rs

1pub mod plugin;
2pub use plugin::*;
3
4pub mod advanced_types;
5pub use advanced_types::*;
6
7pub mod asset;
8
9pub mod collection;
10
11#[cfg(feature = "anchor")]
12use anchor_lang::prelude::{
13    AnchorDeserialize as CrateDeserialize, AnchorSerialize as CrateSerialize,
14};
15use base64::prelude::*;
16#[cfg(not(feature = "anchor"))]
17use borsh::{BorshDeserialize as CrateDeserialize, BorshSerialize as CrateSerialize};
18use modular_bitfield::{bitfield, specifiers::B29};
19use num_traits::FromPrimitive;
20use std::{cmp::Ordering, mem::size_of};
21
22use crate::{
23    accounts::{BaseAssetV1, BaseCollectionV1, PluginHeaderV1, PluginRegistryV1},
24    errors::MplCoreError,
25    types::{
26        ExternalCheckResult, ExternalPluginAdapterKey, ExternalPluginAdapterSchema,
27        ExternalPluginAdapterType, Key, Plugin, PluginType, RegistryRecord, UpdateAuthority,
28    },
29};
30use solana_program::account_info::AccountInfo;
31
32impl From<&Plugin> for PluginType {
33    fn from(plugin: &Plugin) -> Self {
34        match plugin {
35            Plugin::AddBlocker(_) => PluginType::AddBlocker,
36            Plugin::ImmutableMetadata(_) => PluginType::ImmutableMetadata,
37            Plugin::Royalties(_) => PluginType::Royalties,
38            Plugin::FreezeDelegate(_) => PluginType::FreezeDelegate,
39            Plugin::BurnDelegate(_) => PluginType::BurnDelegate,
40            Plugin::TransferDelegate(_) => PluginType::TransferDelegate,
41            Plugin::UpdateDelegate(_) => PluginType::UpdateDelegate,
42            Plugin::PermanentFreezeDelegate(_) => PluginType::PermanentFreezeDelegate,
43            Plugin::Attributes(_) => PluginType::Attributes,
44            Plugin::PermanentTransferDelegate(_) => PluginType::PermanentTransferDelegate,
45            Plugin::PermanentBurnDelegate(_) => PluginType::PermanentBurnDelegate,
46            Plugin::Edition(_) => PluginType::Edition,
47            Plugin::MasterEdition(_) => PluginType::MasterEdition,
48            Plugin::VerifiedCreators(_) => PluginType::VerifiedCreators,
49            Plugin::Autograph(_) => PluginType::Autograph,
50            Plugin::BubblegumV2(_) => PluginType::BubblegumV2,
51            Plugin::FreezeExecute(_) => PluginType::FreezeExecute,
52            Plugin::PermanentFreezeExecute(_) => PluginType::PermanentFreezeExecute,
53            Plugin::Groups(_) => PluginType::Groups,
54        }
55    }
56}
57
58impl BaseAssetV1 {
59    /// The base length of the asset account with an empty name and uri and no seq.
60    const BASE_LEN: usize = 1 // Key
61                            + 32 // Owner
62                            + 1 // Update Authority discriminator
63                            + 4 // Name length
64                            + 4 // URI length
65                            + 1; // Seq option
66}
67
68impl BaseCollectionV1 {
69    /// The base length of the collection account with an empty name and uri.
70    const BASE_LEN: usize = 1 // Key
71                            + 32 // Update Authority
72                            + 4 // Name Length
73                            + 4 // URI Length
74                            + 4 // num_minted
75                            + 4; // current_size
76}
77
78/// Anchor implementations that enable using `Account<BaseAssetV1>` and `Account<BaseCollectionV1>`
79/// in Anchor programs.
80#[cfg(feature = "anchor")]
81mod anchor_impl {
82    use super::*;
83    use anchor_lang::{
84        prelude::{Owner, Pubkey},
85        AccountDeserialize, AccountSerialize, Discriminator,
86    };
87
88    impl AccountDeserialize for BaseAssetV1 {
89        fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
90            let base_asset = Self::from_bytes(buf)?;
91            Ok(base_asset)
92        }
93    }
94
95    // Not used as an Anchor program using Account<BaseAssetV1> would not have permission to
96    // reserialize the account as it's owned by mpl-core.
97    impl AccountSerialize for BaseAssetV1 {}
98
99    // Not used but needed for Anchor.
100    impl Discriminator for BaseAssetV1 {
101        const DISCRIMINATOR: &'static [u8] = &[Key::AssetV1 as u8];
102    }
103
104    impl Owner for BaseAssetV1 {
105        fn owner() -> Pubkey {
106            crate::ID
107        }
108    }
109
110    impl AccountDeserialize for BaseCollectionV1 {
111        fn try_deserialize_unchecked(buf: &mut &[u8]) -> anchor_lang::Result<Self> {
112            let base_asset = Self::from_bytes(buf)?;
113            Ok(base_asset)
114        }
115    }
116
117    // Not used as an Anchor program using Account<BaseCollectionV1> would not have permission to
118    // reserialize the account as it's owned by mpl-core.
119    impl AccountSerialize for BaseCollectionV1 {}
120
121    // Not used but needed for Anchor.
122    impl Discriminator for BaseCollectionV1 {
123        const DISCRIMINATOR: &'static [u8] = &[Key::CollectionV1 as u8];
124    }
125
126    impl Owner for BaseCollectionV1 {
127        fn owner() -> Pubkey {
128            crate::ID
129        }
130    }
131}
132
133impl DataBlob for BaseAssetV1 {
134    fn len(&self) -> usize {
135        let mut size = BaseAssetV1::BASE_LEN + self.name.len() + self.uri.len();
136
137        if let UpdateAuthority::Address(_) | UpdateAuthority::Collection(_) = self.update_authority
138        {
139            size += 32;
140        }
141
142        if self.seq.is_some() {
143            size += size_of::<u64>();
144        }
145        size
146    }
147}
148
149impl SolanaAccount for BaseAssetV1 {
150    fn key() -> Key {
151        Key::AssetV1
152    }
153}
154
155impl DataBlob for BaseCollectionV1 {
156    fn len(&self) -> usize {
157        Self::BASE_LEN + self.name.len() + self.uri.len()
158    }
159}
160
161impl SolanaAccount for BaseCollectionV1 {
162    fn key() -> Key {
163        Key::CollectionV1
164    }
165}
166
167impl SolanaAccount for PluginRegistryV1 {
168    fn key() -> Key {
169        Key::PluginRegistryV1
170    }
171}
172
173impl SolanaAccount for PluginHeaderV1 {
174    fn key() -> Key {
175        Key::PluginHeaderV1
176    }
177}
178
179impl Key {
180    /// Load the one byte key from a slice of data at the given offset.
181    pub fn from_slice(data: &[u8], offset: usize) -> Result<Self, std::io::Error> {
182        let key_byte = *data.get(offset).ok_or_else(|| {
183            std::io::Error::new(
184                std::io::ErrorKind::Other,
185                MplCoreError::DeserializationError.to_string(),
186            )
187        })?;
188
189        Self::from_u8(key_byte).ok_or_else(|| {
190            std::io::Error::new(
191                std::io::ErrorKind::Other,
192                MplCoreError::DeserializationError.to_string(),
193            )
194        })
195    }
196}
197
198/// Load the one byte key from the account data at the given offset.
199pub fn load_key(account: &AccountInfo, offset: usize) -> Result<Key, std::io::Error> {
200    let data = account.data.borrow();
201    Key::from_slice(&data, offset)
202}
203
204/// A trait for generic blobs of data that have size.
205#[allow(clippy::len_without_is_empty)]
206pub trait DataBlob: CrateSerialize + CrateDeserialize {
207    /// Get the current length of the data blob.
208    fn len(&self) -> usize;
209}
210
211/// A trait for Solana accounts.
212pub trait SolanaAccount: CrateSerialize + CrateDeserialize {
213    /// Get the discriminator key for the account.
214    fn key() -> Key;
215
216    /// Load the account from the given account info starting at the offset.
217    fn load(account: &AccountInfo, offset: usize) -> Result<Self, std::io::Error> {
218        let key = load_key(account, offset)?;
219
220        if key != Self::key() {
221            return Err(std::io::Error::new(
222                std::io::ErrorKind::Other,
223                MplCoreError::DeserializationError.to_string(),
224            ));
225        }
226
227        if account.owner != &crate::ID {
228            return Err(std::io::Error::new(
229                std::io::ErrorKind::Other,
230                MplCoreError::IncorrectAccount.to_string(),
231            ));
232        }
233
234        let mut bytes: &[u8] = &(*account.data).borrow()[offset..];
235        Self::deserialize(&mut bytes)
236    }
237
238    /// Save the account to the given account info starting at the offset.
239    fn save(&self, account: &AccountInfo, offset: usize) -> Result<(), std::io::Error> {
240        borsh::to_writer(&mut account.data.borrow_mut()[offset..], self)
241    }
242}
243
244impl RegistryRecord {
245    /// Associated function for sorting `RegistryRecords` by offset.
246    pub fn compare_offsets(a: &RegistryRecord, b: &RegistryRecord) -> Ordering {
247        a.offset.cmp(&b.offset)
248    }
249}
250
251/// Bitfield representation of lifecycle permissions for external plugin adapter, third party plugins.
252#[bitfield(bits = 32)]
253#[derive(Eq, PartialEq, Copy, Clone, Debug, Default)]
254pub struct ExternalCheckResultBits {
255    pub can_listen: bool,
256    pub can_approve: bool,
257    pub can_reject: bool,
258    pub empty_bits: B29,
259}
260
261impl From<ExternalCheckResult> for ExternalCheckResultBits {
262    fn from(check_result: ExternalCheckResult) -> Self {
263        ExternalCheckResultBits::from_bytes(check_result.flags.to_le_bytes())
264    }
265}
266
267impl From<ExternalCheckResultBits> for ExternalCheckResult {
268    fn from(bits: ExternalCheckResultBits) -> Self {
269        ExternalCheckResult {
270            flags: u32::from_le_bytes(bits.into_bytes()),
271        }
272    }
273}
274
275impl From<&ExternalPluginAdapterKey> for ExternalPluginAdapterType {
276    fn from(key: &ExternalPluginAdapterKey) -> Self {
277        match key {
278            ExternalPluginAdapterKey::LifecycleHook(_) => ExternalPluginAdapterType::LifecycleHook,
279            ExternalPluginAdapterKey::LinkedLifecycleHook(_) => {
280                ExternalPluginAdapterType::LinkedLifecycleHook
281            }
282            ExternalPluginAdapterKey::Oracle(_) => ExternalPluginAdapterType::Oracle,
283            ExternalPluginAdapterKey::AppData(_) => ExternalPluginAdapterType::AppData,
284            ExternalPluginAdapterKey::LinkedAppData(_) => ExternalPluginAdapterType::LinkedAppData,
285            ExternalPluginAdapterKey::DataSection(_) => ExternalPluginAdapterType::DataSection,
286            ExternalPluginAdapterKey::AgentIdentity => ExternalPluginAdapterType::AgentIdentity,
287        }
288    }
289}
290
291/// Use `ExternalPluginAdapterSchema` to convert data to string.  If schema is binary or there is
292/// an error, then use Base64 encoding.
293pub fn convert_external_plugin_adapter_data_to_string(
294    schema: &ExternalPluginAdapterSchema,
295    data_slice: &[u8],
296) -> String {
297    match schema {
298        ExternalPluginAdapterSchema::Binary => {
299            // Encode the binary data as a base64 string.
300            BASE64_STANDARD.encode(data_slice)
301        }
302        ExternalPluginAdapterSchema::Json => {
303            // Convert the byte slice to a UTF-8 string, replacing invalid characterse.
304            String::from_utf8_lossy(data_slice).to_string()
305        }
306        ExternalPluginAdapterSchema::MsgPack => {
307            // Attempt to decode `MsgPack` to serde_json::Value and serialize to JSON string.
308            match rmp_serde::decode::from_slice::<serde_json::Value>(data_slice) {
309                Ok(json_val) => serde_json::to_string(&json_val)
310                    .unwrap_or_else(|_| BASE64_STANDARD.encode(data_slice)),
311                Err(_) => {
312                    // Failed to decode `MsgPack`, fallback to base64.
313                    BASE64_STANDARD.encode(data_slice)
314                }
315            }
316        }
317    }
318}