Skip to content

Commit

Permalink
rename collection, add solana account tratit to rust client
Browse files Browse the repository at this point in the history
  • Loading branch information
nhanphan committed Mar 5, 2024
1 parent b83d448 commit 303d882
Show file tree
Hide file tree
Showing 19 changed files with 111 additions and 95 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,17 @@ import {
} from '@metaplex-foundation/umi';
import {
Serializer,
mapSerializer,
publicKey as publicKeySerializer,
string,
struct,
u32,
} from '@metaplex-foundation/umi/serializers';
import { Key, KeyArgs, getKeySerializer } from '../types';

export type CollectionData = Account<CollectionDataAccountData>;
export type Collection = Account<CollectionAccountData>;

export type CollectionDataAccountData = {
export type CollectionAccountData = {
key: Key;
updateAuthority: PublicKey;
name: string;
Expand All @@ -39,98 +40,93 @@ export type CollectionDataAccountData = {
currentSize: number;
};

export type CollectionDataAccountDataArgs = {
key: KeyArgs;
export type CollectionAccountDataArgs = {
updateAuthority: PublicKey;
name: string;
uri: string;
numMinted: number;
currentSize: number;
};

export function getCollectionDataAccountDataSerializer(): Serializer<
CollectionDataAccountDataArgs,
CollectionDataAccountData
export function getCollectionAccountDataSerializer(): Serializer<
CollectionAccountDataArgs,
CollectionAccountData
> {
return struct<CollectionDataAccountData>(
[
['key', getKeySerializer()],
['updateAuthority', publicKeySerializer()],
['name', string()],
['uri', string()],
['numMinted', u32()],
['currentSize', u32()],
],
{ description: 'CollectionDataAccountData' }
) as Serializer<CollectionDataAccountDataArgs, CollectionDataAccountData>;
return mapSerializer<CollectionAccountDataArgs, any, CollectionAccountData>(
struct<CollectionAccountData>(
[
['key', getKeySerializer()],
['updateAuthority', publicKeySerializer()],
['name', string()],
['uri', string()],
['numMinted', u32()],
['currentSize', u32()],
],
{ description: 'CollectionAccountData' }
),
(value) => ({ ...value, key: Key.Collection })
) as Serializer<CollectionAccountDataArgs, CollectionAccountData>;
}

export function deserializeCollectionData(
rawAccount: RpcAccount
): CollectionData {
return deserializeAccount(
rawAccount,
getCollectionDataAccountDataSerializer()
);
export function deserializeCollection(rawAccount: RpcAccount): Collection {
return deserializeAccount(rawAccount, getCollectionAccountDataSerializer());
}

export async function fetchCollectionData(
export async function fetchCollection(
context: Pick<Context, 'rpc'>,
publicKey: PublicKey | Pda,
options?: RpcGetAccountOptions
): Promise<CollectionData> {
): Promise<Collection> {
const maybeAccount = await context.rpc.getAccount(
toPublicKey(publicKey, false),
options
);
assertAccountExists(maybeAccount, 'CollectionData');
return deserializeCollectionData(maybeAccount);
assertAccountExists(maybeAccount, 'Collection');
return deserializeCollection(maybeAccount);
}

export async function safeFetchCollectionData(
export async function safeFetchCollection(
context: Pick<Context, 'rpc'>,
publicKey: PublicKey | Pda,
options?: RpcGetAccountOptions
): Promise<CollectionData | null> {
): Promise<Collection | null> {
const maybeAccount = await context.rpc.getAccount(
toPublicKey(publicKey, false),
options
);
return maybeAccount.exists ? deserializeCollectionData(maybeAccount) : null;
return maybeAccount.exists ? deserializeCollection(maybeAccount) : null;
}

export async function fetchAllCollectionData(
export async function fetchAllCollection(
context: Pick<Context, 'rpc'>,
publicKeys: Array<PublicKey | Pda>,
options?: RpcGetAccountsOptions
): Promise<CollectionData[]> {
): Promise<Collection[]> {
const maybeAccounts = await context.rpc.getAccounts(
publicKeys.map((key) => toPublicKey(key, false)),
options
);
return maybeAccounts.map((maybeAccount) => {
assertAccountExists(maybeAccount, 'CollectionData');
return deserializeCollectionData(maybeAccount);
assertAccountExists(maybeAccount, 'Collection');
return deserializeCollection(maybeAccount);
});
}

export async function safeFetchAllCollectionData(
export async function safeFetchAllCollection(
context: Pick<Context, 'rpc'>,
publicKeys: Array<PublicKey | Pda>,
options?: RpcGetAccountsOptions
): Promise<CollectionData[]> {
): Promise<Collection[]> {
const maybeAccounts = await context.rpc.getAccounts(
publicKeys.map((key) => toPublicKey(key, false)),
options
);
return maybeAccounts
.filter((maybeAccount) => maybeAccount.exists)
.map((maybeAccount) =>
deserializeCollectionData(maybeAccount as RpcAccount)
);
.map((maybeAccount) => deserializeCollection(maybeAccount as RpcAccount));
}

export function getCollectionDataGpaBuilder(
export function getCollectionGpaBuilder(
context: Pick<Context, 'rpc' | 'programs'>
) {
const programId = context.programs.getPublicKey(
Expand All @@ -153,7 +149,6 @@ export function getCollectionDataGpaBuilder(
numMinted: [null, u32()],
currentSize: [null, u32()],
})
.deserializeUsing<CollectionData>((account) =>
deserializeCollectionData(account)
);
.deserializeUsing<Collection>((account) => deserializeCollection(account))
.whereField('key', Key.Collection);
}
2 changes: 1 addition & 1 deletion clients/js/src/generated/accounts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
*/

export * from './asset';
export * from './collectionData';
export * from './collection';
export * from './hashedAsset';
export * from './pluginHeader';
export * from './pluginRegistry';
12 changes: 6 additions & 6 deletions clients/js/src/hooked/fetchCollectionWithPlugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ import {
publicKey as toPublicKey,
} from '@metaplex-foundation/umi';
import {
CollectionData,
Collection,
PluginHeaderAccountData,
PluginRegistryAccountData,
deserializeCollectionData,
getCollectionDataAccountDataSerializer,
deserializeCollection,
getCollectionAccountDataSerializer,
getPluginHeaderAccountDataSerializer,
getPluginRegistryAccountDataSerializer,
getPluginSerializer,
} from '../generated';
import { PluginList, PluginWithAuthorities } from '.';

export type CollectionWithPlugins = CollectionData & PluginList;
export type CollectionWithPlugins = Collection & PluginList;

export async function fetchCollectionWithPlugins(
context: Pick<Context, 'rpc'>,
Expand All @@ -30,9 +30,9 @@ export async function fetchCollectionWithPlugins(
options
);
assertAccountExists(maybeAccount, 'Collection');
const collection = deserializeCollectionData(maybeAccount);
const collection = deserializeCollection(maybeAccount);
const collectionData =
getCollectionDataAccountDataSerializer().serialize(collection);
getCollectionAccountDataSerializer().serialize(collection);

let pluginHeader: PluginHeaderAccountData | undefined;
let pluginRegistry: PluginRegistryAccountData | undefined;
Expand Down
8 changes: 4 additions & 4 deletions clients/js/test/addPlugin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import test from 'ava';
import {
Asset,
AssetWithPlugins,
CollectionData,
Collection,
CollectionWithPlugins,
DataState,
PluginType,
Expand All @@ -14,7 +14,7 @@ import {
createCollection,
fetchAsset,
fetchAssetWithPlugins,
fetchCollectionData,
fetchCollection,
fetchCollectionWithPlugins,
updateAuthority,
} from '../src';
Expand Down Expand Up @@ -101,9 +101,9 @@ test('it can add a plugin to a collection', async (t) => {
}).sendAndConfirm(umi);

// Then an account was created with the correct data.
const collection = await fetchCollectionData(umi, collectionAddress.publicKey);
const collection = await fetchCollection(umi, collectionAddress.publicKey);
// console.log("Account State:", collection);
t.like(collection, <CollectionData>{
t.like(collection, <Collection>{
publicKey: collectionAddress.publicKey,
updateAuthority: umi.identity.publicKey,
name: 'Test Bread',
Expand Down
8 changes: 4 additions & 4 deletions clients/js/test/createCollection.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,13 @@ import { generateSigner } from '@metaplex-foundation/umi';
import test from 'ava';
import {
AssetWithPlugins,
CollectionData,
Collection,
CollectionWithPlugins,
DataState,
create,
createCollection,
fetchAssetWithPlugins,
fetchCollectionData,
fetchCollection,
fetchCollectionWithPlugins,
updateAuthority,
} from '../src';
Expand All @@ -28,12 +28,12 @@ test('it can create a new collection', async (t) => {
}).sendAndConfirm(umi);

// Then an account was created with the correct data.
const collection = await fetchCollectionData(
const collection = await fetchCollection(
umi,
collectionAddress.publicKey
);
// console.log("Account State:", collection);
t.like(collection, <CollectionData>{
t.like(collection, <Collection>{
publicKey: collectionAddress.publicKey,
updateAuthority: umi.identity.publicKey,
name: 'Test Bread Collection',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use solana_program::pubkey::Pubkey;

#[derive(BorshSerialize, BorshDeserialize, Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct CollectionData {
pub struct Collection {
pub key: Key,
#[cfg_attr(
feature = "serde",
Expand All @@ -25,15 +25,15 @@ pub struct CollectionData {
pub current_size: u32,
}

impl CollectionData {
impl Collection {
#[inline(always)]
pub fn from_bytes(data: &[u8]) -> Result<Self, std::io::Error> {
let mut data = data;
Self::deserialize(&mut data)
}
}

impl<'a> TryFrom<&solana_program::account_info::AccountInfo<'a>> for CollectionData {
impl<'a> TryFrom<&solana_program::account_info::AccountInfo<'a>> for Collection {
type Error = std::io::Error;

fn try_from(
Expand Down
4 changes: 2 additions & 2 deletions clients/rust/src/generated/accounts/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@
//!
pub(crate) mod asset;
pub(crate) mod collection_data;
pub(crate) mod collection;
pub(crate) mod hashed_asset;
pub(crate) mod plugin_header;
pub(crate) mod plugin_registry;

pub use self::asset::*;
pub use self::collection_data::*;
pub use self::collection::*;
pub use self::hashed_asset::*;
pub use self::plugin_header::*;
pub use self::plugin_registry::*;
23 changes: 22 additions & 1 deletion clients/rust/src/hooked/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use borsh::{BorshDeserialize, BorshSerialize};
pub use plugins::*;

use crate::{
accounts::{Asset, PluginHeader, PluginRegistry},
accounts::{Asset, Collection, PluginHeader, PluginRegistry},
errors::MplCoreError,
types::{Key, Plugin, PluginType},
};
Expand All @@ -28,6 +28,11 @@ impl Asset {
pub const BASE_LENGTH: usize = 1 + 32 + 33 + 4 + 4;
}

impl Collection {
/// The base length of the collection account with an empty name and uri.
pub const BASE_LENGTH: usize = 1 + 32 + 4 + 4 + 4 + 4;
}

impl DataBlob for Asset {
fn get_initial_size() -> usize {
Asset::BASE_LENGTH
Expand All @@ -44,6 +49,22 @@ impl SolanaAccount for Asset {
}
}

impl DataBlob for Collection {
fn get_initial_size() -> usize {
Self::BASE_LENGTH
}

fn get_size(&self) -> usize {
Self::BASE_LENGTH + self.name.len() + self.uri.len()
}
}

impl SolanaAccount for Collection {
fn key() -> Key {
Key::Collection
}
}

impl SolanaAccount for PluginRegistry {
fn key() -> Key {
Key::PluginRegistry
Expand Down
2 changes: 1 addition & 1 deletion idls/mpl_core.json
Original file line number Diff line number Diff line change
Expand Up @@ -1334,7 +1334,7 @@
}
},
{
"name": "CollectionData",
"name": "Collection",
"type": {
"kind": "struct",
"fields": [
Expand Down
6 changes: 3 additions & 3 deletions programs/mpl-core/src/plugins/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ use solana_program::{

use crate::{
error::MplCoreError,
state::{Asset, Authority, CollectionData, CoreAsset, DataBlob, Key, SolanaAccount},
state::{Asset, Authority, Collection, CoreAsset, DataBlob, Key, SolanaAccount},
utils::{assert_authority, load_key, resize_or_reallocate_account},
};

Expand All @@ -30,7 +30,7 @@ pub fn create_meta_idempotent<'a>(
Key::Collection => {
let collection = {
let mut bytes: &[u8] = &(*account.data).borrow();
CollectionData::deserialize(&mut bytes)?
Collection::deserialize(&mut bytes)?
};

collection.get_size()
Expand Down Expand Up @@ -194,7 +194,7 @@ pub fn initialize_plugin<'a>(
Key::Collection => {
let collection = {
let mut bytes: &[u8] = &(*account.data).borrow();
CollectionData::deserialize(&mut bytes)?
Collection::deserialize(&mut bytes)?
};

collection.get_size()
Expand Down
Loading

0 comments on commit 303d882

Please sign in to comment.