### Examples of Website Scaffolding Source: https://www.metaplex.com/docs/dev-tools/cli/toolbox/scaffolding-website These examples demonstrate both interactive template selection and direct cloning of a specified template. Ensure `git` is installed and accessible. ```bash mplx toolbox template website ``` ```bash mplx toolbox template website --template "standard - nextjs-tailwind" ``` -------------------------------- ### Launchpool with Metadata and Allocations Source: https://www.metaplex.com/docs/dev-tools/cli/genesis/launch This example demonstrates a comprehensive launchpool setup including metadata (description, website, social links) and locked allocations specified in a JSON file. ```bash mplx genesis launch create \ --name "My Token" \ --symbol "MTK" \ --image "https://gateway.irys.xyz/abc123" \ --description "A community token for builders" \ --website "https://example.com" \ --twitter "https://x.com/myproject" \ --telegram "https://t.me/myproject" \ --tokenAllocation 500000000 \ --depositStartTime 2025-03-01T00:00:00Z \ --raiseGoal 250 \ --raydiumLiquidityBps 5000 \ --fundsRecipient \ --lockedAllocations allocations.json ``` -------------------------------- ### Install Turbo SDK Source: https://www.metaplex.com/docs/guides/general/create-deterministic-metadata-with-turbo Install the necessary packages for this guide using npm. ```bash npm i @ardrive/turbo-sdk ``` -------------------------------- ### Quick Start: Asset-Signer Wallet Setup Source: https://www.metaplex.com/docs/dev-tools/cli/config/asset-signer-wallets Follow these steps to set up an asset-signer wallet. This involves creating or using an existing asset, registering it as a wallet, funding its PDA, and switching the CLI to use it. ```bash mplx core asset create --name "My Vault" --uri "https://example.com/vault" ``` ```bash mplx config wallets add vault --asset ``` ```bash mplx core asset execute info ``` ```bash mplx toolbox sol transfer 0.1 ``` ```bash mplx config wallets set vault ``` ```bash mplx toolbox sol balance ``` ```bash mplx toolbox sol transfer 0.01 ``` ```bash mplx core asset create --name "PDA Created NFT" --uri "https://example.com/nft" ``` -------------------------------- ### Install and Start Amman Source: https://www.metaplex.com/docs/solana/working-with-devnet-and-testnet Installs the Amman toolkit and starts the local validator. Recommended for Metaplex development. ```bash # Install npm install -D @metaplex-foundation/amman # Create config file .ammanrc.js # Start npx amman start ``` -------------------------------- ### Core NFT Asset Example Program Setup Source: https://www.metaplex.com/docs/smart-contracts/core/guides/anchor/how-to-create-a-core-nft-asset-with-anchor Defines necessary imports, the program ID, and the basic structure for creating a Core NFT asset with Anchor. ```rust use anchor_lang::prelude::*; use mpl_core:: ID as MPL_CORE_ID, accounts::BaseCollectionV1, instructions::CreateV2CpiBuilder, ; declare_id!("C9PLf3qMCVqtUCJtEBy8NCcseNp3KTZwFJxAtDdN1bto"); #[derive(AnchorDeserialize, AnchorSerialize)] pub struct CreateAssetArgs { } #[program] pub mod create_core_asset_example { use super::*; pub fn create_core_asset(ctx: Context, args: CreateAssetArgs) -> Result<()> { Ok(()) } } #[derive(Accounts)] pub struct CreateAsset<'info> { } ``` -------------------------------- ### Install @solana/kit Adapters Source: https://www.metaplex.com/docs/dev-tools/umi/kit-adapters Install the adapters package using npm. ```bash npm i @metaplex-foundation/umi-kit-adapters ``` -------------------------------- ### Install Rust using rustup Source: https://www.metaplex.com/docs/smart-contracts/candy-machine/sugar/installation Recommended method to install Rust, which is a prerequisite for installing Sugar from crates.io or building from source. ```bash curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` -------------------------------- ### Install Dependencies Source: https://www.metaplex.com/docs/tokens/launch-token Install the necessary Metaplex Foundation packages for token launching. ```bash mkdir my-token-launch cd my-token-launch npm init -y npm install @metaplex-foundation/genesis @metaplex-foundation/umi @metaplex-foundation/umi-bundle-defaults @metaplex-foundation/mpl-toolbox ``` -------------------------------- ### Get Assets By Group using Umi Source: https://www.metaplex.com/docs/dev-tools/das-api/methods/get-assets-by-group This example demonstrates how to fetch assets belonging to a specific group using the Umi SDK. Ensure you have the `@metaplex-foundation/umi` and `@metaplex-foundation/digital-asset-standard-api` packages installed and configured. ```javascript import { publicKey } from '@metaplex-foundation/umi' import { createUmi } from '@metaplex-foundation/umi-bundle-defaults' import { dasApi } from '@metaplex-foundation/digital-asset-standard-api' const umi = createUmi('https://api.devnet.solana.com').use(dasApi()) const result = await umi.rpc.getAssetsByGroup({ groupKey: '', groupValue: '' }) console.log(result) ``` -------------------------------- ### Install Core Umi Plugins with Arguments Source: https://www.metaplex.com/docs/dev-tools/umi/plugins Demonstrates installing core Umi plugins like RPC, storage, and downloaders, passing necessary configuration arguments. ```typescript import { web3JsRpc } from '@metaplex-foundation/umi-rpc-web3js'; import { mockStorage } from '@metaplex-foundation/umi-storage-mock'; import { httpDownloader } from '@metaplex-foundation/umi-downloader-http'; umi.use(web3JsRpc('https://api.mainnet-beta.solana.com')) .use(mockStorage()) .use(httpDownloader()); ``` -------------------------------- ### Get Assets By Creator with UMI SDK Source: https://www.metaplex.com/docs/dev-tools/das-api/methods/get-assets-by-creator This example demonstrates how to fetch assets created by a specific address using the UMI SDK. It's recommended to use `onlyVerified: true` to ensure asset authenticity. Ensure you have the UMI SDK and DAS API plugin installed and configured. ```javascript import { publicKey } from '@metaplex-foundation/umi' import { createUmi } from '@metaplex-foundation/umi-bundle-defaults' import { dasApi } from '@metaplex-foundation/digital-asset-standard-api' const umi = createUmi('https://api.devnet.solana.com').use(dasApi()) const result = await umi.rpc.getAssetsByCreator({ }) console.log(result) ``` -------------------------------- ### createAndRegisterLaunch SDK Usage Source: https://www.metaplex.com/docs/smart-contracts/genesis/integration-apis/create-launch This snippet demonstrates how to use the `createAndRegisterLaunch` function, which simplifies the process of creating, signing, sending, and registering a launch. It includes setting up the UMI instance and defining the input parameters for the launch. ```APIDOC ## createAndRegisterLaunch ### Description Creates and registers a new launch, handling transaction creation, signing, and submission. ### Method Signature `createAndRegisterLaunch(umi: Umi, options: {}, input: CreateLaunchInput): Promise<{ launch: { link: string }}>` ### Parameters #### `umi` (Umi) - The UMI instance configured with necessary plugins. #### `options` (object) - Optional configuration for the operation. #### `input` (CreateLaunchInput) - **wallet** (PublicKey) - The public key of the wallet initiating the launch. - **token** (object) - Details of the token being launched. - **name** (string) - The name of the token. - **symbol** (string) - The symbol of the token. - **image** (string) - The URL of the token's image. - **launchType** (string) - The type of launch (e.g., 'launchpool'). - **launch** (object) - Specific details for the launch type. - **launchpool** (object) - Configuration for a launchpool. - **tokenAllocation** (number) - The total number of tokens allocated for the launchpool. - **depositStartTime** (Date) - The start time for deposits into the launchpool. - **raiseGoal** (number) - The fundraising goal for the launchpool. - **raydiumLiquidityBps** (number) - The basis points for Raydium liquidity. - **fundsRecipient** (PublicKey) - The public key of the recipient for the raised funds. ### Returns - **Promise<{ launch: { link: string }}>** - A promise that resolves to an object containing the link to the newly created launch. ``` -------------------------------- ### Installing and Using Mock Storage Source: https://www.metaplex.com/docs/dev-tools/umi/storage Provides instructions for installing the mock storage package and integrating it with Umi. This allows for testing storage functionalities without a real backend. ```bash npm install @metaplex-foundation/umi-storage-mock ``` -------------------------------- ### Example cURL Request Source: https://www.metaplex.com/docs/smart-contracts/genesis/integration-apis/get-launch An example of how to call the GET launch endpoint using cURL to fetch data for a specific genesis address. ```curl curl https://api.metaplex.com/v1/launches/7nE9GvcwsqzYcPUYfm5gxzCKfmPqi68FM7gPaSfG6EQN ``` -------------------------------- ### Full Presale Lifecycle Example Source: https://www.metaplex.com/docs/dev-tools/cli/genesis/presale This script demonstrates the complete process of setting up and interacting with a presale, including token creation, defining deposit and claim windows, and user participation. ```bash # 1. Create the token mplx genesis create \ --name "Example Token" \ --symbol "EXM" \ --totalSupply 1000000000000000 \ --decimals 9 GENESIS= # 2. Timestamps NOW=$(date +%s) DEPOSIT_END=$((NOW + 86400)) CLAIM_START=$((DEPOSIT_END + 1)) CLAIM_END=$((NOW + 31536000)) # 3. Add presale bucket: 1M tokens at 100 SOL cap mplx genesis bucket add-presale $GENESIS \ --allocation 1000000000000000 \ --quoteCap 100000000000 \ --bucketIndex 0 \ --depositStart $NOW \ --depositEnd $DEPOSIT_END \ --claimStart $CLAIM_START \ --claimEnd $CLAIM_END # 4. Add unlocked bucket for team to receive SOL mplx genesis bucket add-unlocked $GENESIS \ --recipient $(solana address) \ --claimStart $CLAIM_START \ --allocation 0 # 5. Finalize mplx genesis finalize $GENESIS # 6. Verify mplx genesis fetch $GENESIS mplx genesis bucket fetch $GENESIS --bucketIndex 0 --type presale # 7. Wrap SOL and deposit mplx toolbox sol wrap 1 mplx genesis presale deposit $GENESIS --amount 1000000000 --bucketIndex 0 # 8. After deposit period, claim mplx genesis presale claim $GENESIS --bucketIndex 0 ``` -------------------------------- ### Example Response Structure for Get Assets by Collection Source: https://www.metaplex.com/docs/dev-tools/das-api/core-extension/methods/get-assets-by-collection This is an example of the response when fetching assets for a collection. The array will contain multiple entries if the collection has more than one asset. ```json [ { publicKey: '8VrqN8b8Y7rqWsUXqUw7dxQw9J5UAoVyb6YDJs1mBCCz', header: { executable: false, owner: 'CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d', lamports: [Object], rentEpoch: 18446744073709551616n, exists: true }, pluginHeader: { key: 3, pluginRegistryOffset: 179n }, royalties: { authority: [Object], offset: 138n, basisPoints: 500, creators: [Array], ruleSet: [Object] }, key: 1, updateAuthority: { type: 'Collection', address: 'FgEKkVTSfLQ7a7BFuApypy4KaTLh65oeNRn2jZ6fiBav' }, name: 'Number 1', uri: 'https://arweave.net/TkklLLQKiO9t9_JPmt-eH_S-VBLMcRjFcgyvIrENBzA', content: { '$schema': 'https://schema.metaplex.com/nft1.0.json', json_uri: 'https://arweave.net/TkklLLQKiO9t9_JPmt-eH_S-VBLMcRjFcgyvIrENBzA', files: [Array], metadata: [Object], links: [Object] }, owner: 'AUtnbwWJQfYZjJ5Mc6go9UancufcAuyqUZzR1jSe4esx', seq: { __option: 'None' } } ] ``` -------------------------------- ### Create and Register Launch Source: https://www.metaplex.com/docs/smart-contracts/genesis/sdk/api-client This example demonstrates how to use the `createAndRegisterLaunch` function to set up a new token launch with optional locked allocations. It covers the structure of `CreateLaunchInput`, including token details, launch configuration, and Streamflow lockup schedules. ```APIDOC ## createAndRegisterLaunch ### Description Creates and registers a new launch with the Genesis protocol. This function allows for detailed configuration of token metadata, launch parameters, and optional locked allocations for vesting. ### Method `createAndRegisterLaunch(umi, options, input)` ### Parameters #### `umi` - **umi** (Umi): The Umi instance configured with the genesis plugin. #### `options` - **options** (SignAndSendOptions): Options for sending the transaction. See `SignAndSendOptions` below. #### `input` - **input** (CreateLaunchInput): The configuration object for the launch. ### `CreateLaunchInput` Object #### Fields - **wallet** (PublicKey | string): Required. Creator's wallet (signs transactions). - **token** (TokenMetadata): Required. Token metadata. - **network** (SvmNetwork): Optional. `'solana-mainnet'` (default) or `'solana-devnet'`. - **quoteMint** (QuoteMintInput): Optional. `'SOL'` (default) or `'USDC'`. - **launchType** (CreateLaunchType): Required. `'launchpool'` — the underlying launch mechanism. - **launch** (LaunchpoolLaunchInput): Required. Launch configuration. ### `TokenMetadata` Object #### Fields - **name** (string): Required. Token name, 1–32 characters. - **symbol** (string): Required. Token symbol, 1–10 characters. - **image** (string): Required. Image URL (valid HTTPS URL). - **description** (string): Optional. Max 250 characters. - **externalLinks** (ExternalLinks): Optional. Website, Twitter, Telegram links. ### `ExternalLinks` Object #### Fields - **website** (string?): Optional. Website URL. - **twitter** (string?): Optional. Twitter/X handle (`@mytoken`) or full URL. - **telegram** (string?): Optional. Telegram handle or full URL. ### `LaunchpoolLaunchInput` Object #### Fields - **tokenAllocation** (number): Required. Tokens to sell (portion of 1B total supply). - **depositStartTime** (Date | string): Required. When the deposit period opens (lasts 48 hours). - **raiseGoal** (number): Required. Minimum quote tokens to raise, in whole units (e.g. 250 SOL). Minimum 250 SOL or 5,000 USDC. - **raydiumLiquidityBps** (number): Required. % of raised funds for Raydium LP, in basis points (2000–10000). - **fundsRecipient** (PublicKey | string): Required. Receives the unlocked portion of raised funds. - **lockedAllocations** (LockedAllocation[]): Optional. Array of locked token schedules. ### `LockedAllocation` Object (Streamflow Lockup) #### Fields - **name** (string): Required. Stream name, max 64 characters (e.g. "Team", "Advisors"). - **recipient** (PublicKey | string): Required. Lockup recipient wallet. - **tokenAmount** (number): Required. Total tokens in the locked schedule. - **vestingStartTime** (Date | string): Required. When the unlock schedule begins. Must be after the deposit period ends. - **vestingDuration** ({ value: number, unit: TimeUnit }): Required. Full lockup period. - **unlockSchedule** (TimeUnit): Required. How frequently tokens are released. - **cliff** (object?): Optional cliff with `duration` and `unlockAmount`. ### `TimeUnit` Enum Possible values: `'SECOND'`, `'MINUTE'`, `'HOUR'`, `'DAY'`, `'WEEK'`, `'TWO_WEEKS'`, `'MONTH'`, `'QUARTER'`, `'YEAR'`. ### `SignAndSendOptions` Object Options for `createAndRegisterLaunch` (extends `RpcSendTransactionOptions`): #### Fields - **txSender** ((txs: Transaction[]) => Promise): Optional. Custom transaction sender callback. - **commitment** (string): Optional. Commitment level for confirmation (`'confirmed'` by default). - **preflightCommitment** (string): Optional. Preflight commitment level (`'confirmed'` by default). - **skipPreflight** (boolean): Optional. Skip preflight checks (`false` by default). ### Request Example ```typescript import { createAndRegisterLaunch, CreateLaunchInput, genesis } from '@metaplex-foundation/genesis' import { createUmi } from '@metaplex-foundation/umi-bundle-defaults' import { keypairIdentity } from '@metaplex-foundation/umi' const umi = createUmi('https://api.mainnet-beta.solana.com') .use(genesis()) // Use keypairIdentity to set a wallet when running server-side: // umi.use(keypairIdentity(myKeypair)) const input: CreateLaunchInput = { wallet: umi.identity.publicKey, token: { name: 'My Token', symbol: 'MTK', image: 'https://gateway.irys.xyz/...', description: 'A project token with locked allocations.', externalLinks: { website: 'https://example.com', twitter: '@mytoken', }, }, launchType: 'launchpool', launch: { launchpool: { tokenAllocation: 500_000_000, depositStartTime: new Date('2026-04-01T00:00:00Z'), raiseGoal: 250, raydiumLiquidityBps: 5000, fundsRecipient: 'FundsRecipientWallet...', }, lockedAllocations: [ { name: 'Team', recipient: 'TeamWallet...', tokenAmount: 100_000_000, vestingStartTime: new Date('2026-04-05T00:00:00Z'), vestingDuration: { value: 1, unit: 'YEAR' }, unlockSchedule: 'MONTH', cliff: { duration: { value: 3, unit: 'MONTH' }, unlockAmount: 10_000_000, }, }, ], }, } const result = await createAndRegisterLaunch(umi, {}, input) console.log(`Launch live at: ${result.launch.link}`) ``` ### Response #### Success Response (200) - **result** (object): An object containing the details of the created launch, including a `link` to the launch page. ``` -------------------------------- ### Clone Example Candy Machine Assets Source: https://www.metaplex.com/docs/smart-contracts/candy-machine/guides/create-an-nft-collection-on-solana-with-candy-machine If you have git installed, you can clone the example assets repository to your system. This provides sample images and metadata for creating a Candy Machine. ```bash git clone https://github.com/metaplex-foundation/example-candy-machine-assets.git ``` -------------------------------- ### Install Core SDK and Umi Defaults Source: https://www.metaplex.com/docs/smart-contracts/core/sdk/javascript Install the Metaplex Core SDK and the Umi framework defaults. This is the initial step for using the SDK. ```bash npm install @metaplex-foundation/mpl-core @metaplex-foundation/umi-bundle-defaults ``` -------------------------------- ### Get NFT Editions - Curl Request Source: https://www.metaplex.com/docs/dev-tools/das-api/methods/get-nft-editions This example demonstrates how to call the Get NFT Editions method using cURL. Ensure you replace the placeholder URL with the correct API endpoint. ```curl curl -X POST -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"getNftEditions\",\"params\":{}}" https://api.devnet.solana.com ``` -------------------------------- ### Full Launch Pool Lifecycle Example Source: https://www.metaplex.com/docs/dev-tools/cli/genesis/launch-pool A comprehensive example demonstrating the complete lifecycle of a launch pool, from creation to claiming tokens and revoking mint authority. This includes setting up accounts, buckets, deposits, and transitions. ```bash # 1. Create the Genesis account mplx genesis create \ --name "My Token" \ --symbol "MTK" \ --totalSupply 1000000000000000 \ --decimals 9 # (copy GENESIS_ADDRESS from output) GENESIS= # 2. Timestamps NOW=$(date +%s) DEPOSIT_END=$((NOW + 86400)) CLAIM_START=$((DEPOSIT_END + 1)) CLAIM_END=$((NOW + 31536000)) # 3. Add a launch pool bucket with end behavior mplx genesis bucket add-launch-pool $GENESIS \ --allocation 500000000000000 \ --depositStart $NOW \ --depositEnd $DEPOSIT_END \ --claimStart $CLAIM_START \ --claimEnd $CLAIM_END \ --endBehavior ":10000" # 4. Add an unlocked bucket to receive SOL mplx genesis bucket add-unlocked $GENESIS \ --recipient $(solana address) \ --claimStart $CLAIM_START \ --allocation 0 # 5. Finalize mplx genesis finalize $GENESIS # 6. Wrap SOL and deposit mplx toolbox sol wrap 10 mplx genesis deposit $GENESIS --amount 10000000000 --bucketIndex 0 # 7. After deposit period, transition mplx genesis transition $GENESIS --bucketIndex 0 # 8. Claim tokens mplx genesis claim $GENESIS --bucketIndex 0 # 9. Revoke mint authority mplx genesis revoke $GENESIS --revokeMint ``` -------------------------------- ### Project Dependencies Source: https://www.metaplex.com/docs/smart-contracts/core/guides/javascript/web2-typescript-staking-example List of npm packages required for the staking example. Ensure these are installed in your project. ```json "dependencies": { "@metaplex-foundation/mpl-core": "1.1.0-alpha.0", "@metaplex-foundation/mpl-token-metadata": "^3.2.1", "@metaplex-foundation/umi-bundle-defaults": "^0.9.1", "bs58": "^5.0.0", "typescript": "^5.4.5" } ``` -------------------------------- ### Example Response Structure for Get Assets by Authority Source: https://www.metaplex.com/docs/dev-tools/das-api/core-extension/methods/get-assets-by-authority This is an example of the data structure returned when fetching assets by authority. The array will contain multiple entries if the authority manages more than one Core asset. ```json [ { publicKey: '8VrqN8b8Y7rqWsUXqUw7dxQw9J5UAoVyb6YDJs1mBCCz', header: { executable: false, owner: 'CoREENxT6tW1HoK8ypY1SxRMZTcVPm7R94rH4PZNhX7d', lamports: [Object], rentEpoch: 18446744073709551616n, exists: true }, pluginHeader: { key: 3, pluginRegistryOffset: 179n }, royalties: { authority: [Object], offset: 138n, basisPoints: 500, creators: [Array], ruleSet: [Object] }, key: 1, updateAuthority: { type: 'Collection', address: 'FgEKkVTSfLQ7a7BFuApypy4KaTLh65oeNRn2jZ6fiBav' }, name: 'Number 1', uri: 'https://arweave.net/TkklLLQKiO9t9_JPmt-eH_S-VBLMcRjFcgyvIrENBzA', content: { '$schema': 'https://schema.metaplex.com/nft1.0.json', json_uri: 'https://arweave.net/TkklLLQKiO9t9_JPmt-eH_S-VBLMcRjFcgyvIrENBzA', files: [Array], metadata: [Object], links: [Object] }, owner: 'AUtnbwWJQfYZjJ5Mc6go9UancufcAuyqUZzR1jSe4esx', seq: { __option: 'None' } } ] ``` -------------------------------- ### Setup Umi Environment Source: https://www.metaplex.com/docs/smart-contracts/core/guides/oracle-plugin-example Initializes the Umi client and configures the wallet signer. Ensure your wallet JSON file is correctly placed. ```typescript import { createSignerFromKeypair, signerIdentity } from '@metaplex-foundation/umi' import { createUmi } from '@metaplex-foundation/umi-bundle-defaults' // SecretKey for the wallet you're going to use import wallet from "../wallet.json"; const umi = createUmi("https://api.devnet.solana.com", "finalized") let keyair = umi.eddsa.createKeypairFromSecretKey(new Uint8Array(wallet)); const myKeypairSigner = createSignerFromKeypair(umi, keyair); umi.use(signerIdentity(myKeypairSigner)); ``` -------------------------------- ### Create Tree Config V2 Builder Example Source: https://www.metaplex.com/docs/smart-contracts/bubblegum-v2/sdk/rust Example demonstrating how to use the `CreateTreeConfigV2Builder` for local scripts to create a new merkle tree configuration. Ensure you have the necessary RPC client and transaction setup. ```rust use mpl_bubblegum::{instructions::CreateTreeConfigV2Builder, programs::{SPL_ACCOUNT_COMPRESSION_ID, SPL_NOOP_ID}}; use solana_client::{nonblocking::rpc_client, rpc_config::RpcSendTransactionConfig}; use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey, signature::Keypair, signer::Signer, system_program, transaction::Transaction}; #[tokio::main] pub async fn create_tree(keypair: Keypair) { let rpc_client = rpc_client::RpcClient::new("https://api.devnet.solana.com/".to_string()); let payer = keypair; let asset = Keypair::new(); let merkle_tree = Keypair::new(); let tree_config = Pubkey::find_program_address( &[ &merkle_tree.pubkey().to_bytes(), ], &mpl_bubblegum::ID, ); let create_tree_config_ix = CreateTreeConfigV2Builder::new() .merkle_tree(merkle_tree.pubkey()) .tree_config(tree_config.0) .payer(payer.pubkey()) .max_depth(20) .max_buffer_size(1024) .public(false) .instruction(); let signers = vec![&asset, &payer]; let last_blockhash = rpc_client.get_latest_blockhash().await; let create_tree_config_tx = Transaction::new_signed_with_payer( &[create_tree_config_ix], Some(&payer.pubkey()), &signers, last_blockhash.unwrap(), ); let res = rpc_client .send_transaction_with_config(&create_tree_config_tx, RpcSendTransactionConfig { skip_preflight: false, preflight_commitment: Some(CommitmentConfig::confirmed().commitment), encoding: None, max_retries: None, min_context_slot: None, }) .await .unwrap(); println!("Signature: {:?}", res); } ``` -------------------------------- ### Example: Upload Directory Source: https://www.metaplex.com/docs/dev-tools/cli/toolbox/storage-upload This example shows how to upload all files within an assets directory. ```bash mplx toolbox storage upload ./assets --directory ``` -------------------------------- ### Example: Add Existing Wallet Source: https://www.metaplex.com/docs/dev-tools/cli/config/wallets Demonstrates adding an existing wallet named 'dev1' using its keypair file located at '~/.config/solana/devnet/dev1.json'. ```bash mplx config wallets add dev1 ~/.config/solana/devnet/dev1.json ``` -------------------------------- ### Check CLI Setup Source: https://www.metaplex.com/docs/dev-tools/cli/agents Verify your Metaplex CLI installation and configuration by running the help command for agents. ```bash mplx agents --help ``` -------------------------------- ### Check CLI Setup Source: https://www.metaplex.com/docs/dev-tools/cli/genesis Verify your Metaplex CLI installation and configuration by running the help command for the genesis group. ```bash mplx genesis --help ``` -------------------------------- ### Build and Install Sugar from Source Source: https://www.metaplex.com/docs/smart-contracts/candy-machine/sugar/installation Compile and install the Sugar CLI from the local source code. Ensure the cargo bin directory is in your PATH. ```bash cargo install --path ./ ``` -------------------------------- ### Initialize Project Source: https://www.metaplex.com/docs/smart-contracts/bubblegum/guides/javascript/how-to-create-1000000-nfts-on-solana Use npm to initialize a new Javascript project. This command prompts for project details. ```bash npm init ``` -------------------------------- ### Example cURL Request Source: https://www.metaplex.com/docs/smart-contracts/genesis/integration-apis/get-launches-by-token Use this cURL command to make a request to the API to get launches for a given token address. ```curl curl https://api.metaplex.com/v1/tokens/EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v ``` -------------------------------- ### Setup Umi with an Existing Local Wallet Source: https://www.metaplex.com/docs/smart-contracts/bubblegum/guides/javascript/how-to-create-1000000-nfts-on-solana Initialize Umi with plugins and load an existing wallet from a local JSON file. Ensure the keypair.json file exists in the project's root. ```javascript const umi = createUmi('https://api.devnet.solana.com') .use(mplBubblegum()) .use(mplTokenMetadata()) .use( irysUploader({ // mainnet address: "https://node1.irys.xyz" // devnet address: "https://devnet.irys.xyz" address: 'https://devnet.irys.xyz', }) ) // Generate a new keypair signer. const signer = generateSigner(umi) // You will need to us fs and navigate the filesystem to // load the wallet you wish to use via relative pathing. const walletFile = fs.readFileSync('./keypair.json') // Convert your walletFile onto a keypair. let keypair = umi.eddsa.createKeypairFromSecretKey(new Uint8Array(walletFile)) // Load the keypair into umi. umi.use(keypairIdentity(keypair)) ``` -------------------------------- ### getAssetsByGroup Source: https://www.metaplex.com/docs/dev-tools/das-api/methods Return the list of assets given a group (key, value) pair. For example this can be used to get all assets in a collection. ```APIDOC ## getAssetsByGroup ### Description Retrieves assets belonging to a specific group, identified by a key-value pair. This is commonly used to fetch all assets within a collection or a similar grouping. ### Method POST ### Endpoint /getAssetsByGroup ### Parameters #### Request Body - **groupKey** (string) - Required - The key identifying the group. - **groupValue** (string) - Required - The value identifying the specific group. - **options** (object) - Optional - Additional options for the query. - **limit** (integer) - Optional - The maximum number of assets to return. - **page** (string) - Optional - The pagination token for fetching the next page of results. ``` -------------------------------- ### Create Genesis Account using Interactive Wizard Source: https://www.metaplex.com/docs/dev-tools/cli/genesis/create Run the command with the `--wizard` flag to be guided through the setup process interactively. ```bash mplx genesis create --wizard ``` -------------------------------- ### Setup Umi Instance with Token Metadata Plugin Source: https://www.metaplex.com/docs/smart-contracts/token-metadata/getting-started/umi Initialize a Umi instance and apply the Token Metadata plugin. This sets up the connection to the Solana devnet. ```typescript import { createUmi } from '@metaplex-foundation/umi-bundle-defaults'; import { mplTokenMetadata } from '@metaplex-foundation/mpl-token-metadata'; // Create Umi instance with the Token Metadata plugin const umi = createUmi('https://api.devnet.solana.com') .use(mplTokenMetadata()); ``` -------------------------------- ### Get Assets by Group (JavaScript) Source: https://www.metaplex.com/docs/dev-tools/das-api/guides/get-collection-nfts Use the `getAssetsByGroup` method to retrieve assets belonging to a specific collection. Ensure you have the necessary client setup. ```javascript import { getAssetsByGroup } from '@metaplex-foundation/umi-collection-tools'; const assets = await getAssetsByGroup(umi, { groupType: 'collection', groupValue: 'YOUR_COLLECTION_ADDRESS', // Optional: Specify 'fungible' or 'nonFungible' to filter asset types // assetType: 'nonFungible', }); ``` -------------------------------- ### End-to-End Agent and Token Launch Example Source: https://www.metaplex.com/docs/dev-tools/cli/agents/set-agent-token This example demonstrates the complete process of registering a new agent, launching a bonding curve token linked to that agent, and verifying the link. ```bash # 1. Register a new agent mplx agents register --name "My Agent" \ --description "An autonomous trading agent" \ --image "./avatar.png" # Note the asset address from the output # 2. Launch a bonding curve token linked to the agent mplx genesis launch create --launchType bonding-curve \ --name "Agent Token" --symbol "AGT" \ --image "https://gateway.irys.xyz/abc123" \ --agentAsset --agentSetToken # 3. Verify the agent has a token linked mplx agents fetch ``` -------------------------------- ### Get Token Accounts (cURL) Source: https://www.metaplex.com/docs/dev-tools/das-api/methods/get-token-accounts This example demonstrates how to call the getTokenAccounts method using cURL. It sends a JSON-RPC request to the specified Solana API endpoint. ```curl curl -X POST -H "Content-Type: application/json" -d "{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"getTokenAccounts\",\"params\":{}}" https://api.devnet.solana.com ``` -------------------------------- ### Create Launch with First Buy (CLI) Source: https://www.metaplex.com/docs/agents/create-agent-token Utilize this CLI command to create a new token launch with a specified agent and an initial fee-free purchase. Replace placeholders like with your actual values. ```bash mplx genesis launch create --launchType bonding-curve \ --name "Agent Token" \ --symbol "AGT" \ --image "https://gateway.irys.xyz/your-image-id" \ --agentAsset \ --agentSetToken \ --firstBuyAmount 0.1 ``` -------------------------------- ### Get Asset using UMI Source: https://www.metaplex.com/docs/dev-tools/das-api/methods/get-asset Demonstrates how to fetch asset details using the UMI library. Ensure you have the UMI bundle and DAS API plugin installed. ```javascript import { publicKey } from '@metaplex-foundation/umi' import { createUmi } from '@metaplex-foundation/umi-bundle-defaults' import { dasApi } from '@metaplex-foundation/digital-asset-standard-api' const umi = createUmi('https://api.devnet.solana.com').use(dasApi()) const result = await umi.rpc.getAsset({ id: publicKey('') }) console.log(result) ``` -------------------------------- ### Setup Umi and Import Core Candy Machine Functions Source: https://www.metaplex.com/docs/smart-contracts/core/guides/print-editions Initializes the Umi instance with the Core Candy Machine plugin and sets up the keypair identity. Ensure your RPC endpoint and wallet are correctly configured. ```javascript import { create, mplCandyMachine, } from "@metaplex-foundation/mpl-core-candy-machine"; import { createCollection, ruleSet } from "@metaplex-foundation/mpl-core"; import crypto from "crypto"; import { generateSigner, keypairIdentity, } from "@metaplex-foundation/umi"; import { createUmi } from "@metaplex-foundation/umi-bundle-defaults"; // Use the RPC endpoint of your choice. const umi = createUmi("http://127.0.0.1:8899").use(mplCandyMachine()); // use your keypair or Wallet Adapter here. const keypair = generateSigner(umi); umi.use(keypairIdentity(keypair)); ``` -------------------------------- ### Initialize Project with npm Source: https://www.metaplex.com/docs/smart-contracts/core/guides/javascript/how-to-create-a-core-nft-asset-with-javascript Initialize a new Javascript project using npm. Follow the prompts to fill in the required project details. ```bash npm init ``` -------------------------------- ### Get Account Balance using RPC Source: https://www.metaplex.com/docs/rpc-providers Example of how to retrieve the balance of a Solana account using the `getBalance` RPC method. Ensure you are using a valid account address. ```shell # Get the balance of an account curl https://api.mainnet-beta.solana.com -X POST \ -H "Content-Type: application/json" \ -d '{"jsonrpc":"2.0","id":1,"method":"getBalance","params":["7C4jsPZpht42Tw6MjXWF56Q5RQUocjBBmciEjDa8HRtp"]}' ``` -------------------------------- ### Candy Machine CLI: Manual Setup Steps Source: https://www.metaplex.com/docs/cli/cm For advanced users, this outlines the manual steps to set up a candy machine, including directory creation, asset upload, creation, and item insertion. ```bash # 1. Set up directory and config manually mkdir my-candy-machine && cd my-candy-machine # (create assets/ directory and add your assets) # 2. Upload assets mplx cm upload # 3. Create candy machine mplx cm create # 4. Insert items mplx cm insert # 5. Validate (optional) mplx cm validate ``` -------------------------------- ### GitHub Actions CI/CD Pipeline for Solana Source: https://www.metaplex.com/docs/solana/working-with-devnet-and-testnet Example of a GitHub Actions workflow to start a local validator and run tests. It sets the SOLANA_CLUSTER environment variable for the test environment. ```yaml - name: Start local validator run: | npx amman start & sleep 10 - name: Run tests run: npm test env: SOLANA_CLUSTER: localnet ``` -------------------------------- ### Get Asset Proof with Umi Source: https://www.metaplex.com/docs/dev-tools/das-api/methods/get-asset-proof Use this snippet to fetch the Merkle tree proof for a compressed asset. Ensure you have the Umi library and DAS API plugin installed and configured. ```javascript import { publicKey } from '@metaplex-foundation/umi' import { createUmi } from '@metaplex-foundation/umi-bundle-defaults' import { dasApi } from '@metaplex-foundation/digital-asset-standard-api' const umi = createUmi('https://api.devnet.solana.com').use(dasApi()) const result = await umi.rpc.getAssetProof() console.log(result) ``` -------------------------------- ### Initialize a New Project Source: https://www.metaplex.com/docs/smart-contracts/token-metadata/guides/how-to-add-metadata-to-spl-tokens Initialize a new project using npm. This command sets up a new Node.js project with default settings. ```bash npm init -y ``` -------------------------------- ### Create Merkle Tree Configuration with Builder Source: https://www.metaplex.com/docs/smart-contracts/bubblegum/sdk/rust Example of creating a Merkle tree configuration using the CreateTreeConfigBuilder for local scripts. This builder abstracts away much of the setup for transaction instructions. ```rust use mpl_bubblegum::{instructions::CreateTreeConfigBuilder, programs::{SPL_ACCOUNT_COMPRESSION_ID, SPL_NOOP_ID}}; use solana_client::{nonblocking::rpc_client, rpc_config::RpcSendTransactionConfig}; use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey, signature::Keypair, signer::Signer, system_program, transaction::Transaction}; #[tokio::main] pub async fn create_tree(keypair: Keypair) { let rpc_client = rpc_client::RpcClient::new("https://api.devnet.solana.com/".to_string()); let payer = keypair; let asset = Keypair::new(); let merkle_tree = Keypair::new(); let tree_config = Pubkey::find_program_address( &[ &merkle_tree.pubkey().to_bytes(), ], &mpl_bubblegum::ID, ); let create_tree_config_ix = CreateTreeConfigBuilder::new() .merkle_tree(merkle_tree.pubkey()) .tree_config(tree_config.0) .payer(payer.pubkey()) .log_wrapper(SPL_NOOP_ID) .compression_program(SPL_ACCOUNT_COMPRESSION_ID) .system_program(system_program::ID) .max_depth(20) .max_buffer_size(1024) .public(false) .instruction(); let signers = vec![&asset, &payer]; let last_blockhash = rpc_client.get_latest_blockhash().await; let create_tree_config_tx = Transaction::new_signed_with_payer( &[create_tree_config_ix], Some(&payer.pubkey()), &signers, last_blockhash.unwrap(), ); let res = rpc_client .send_transaction_with_config(&create_tree_config_tx, RpcSendTransactionConfig { skip_preflight: false, preflight_commitment: Some(CommitmentConfig::confirmed().commitment), encoding: None, max_retries: None, min_context_slot: None, }) .await .unwrap(); println!("Signature: {:?}", res) } ``` -------------------------------- ### Create Candy Machine with Wizard Source: https://www.metaplex.com/docs/cli/cm Use the interactive wizard for a guided, step-by-step creation process. This command handles asset validation, upload, and candy machine setup with guard configurations. ```bash mplx cm create --wizard ``` -------------------------------- ### Start Amman with Configuration Source: https://www.metaplex.com/docs/dev-tools/amman/cli-commands Launches the Amman environment using a specified configuration file. If no config is provided, Amman defaults to `.ammanrc.js` or a built-in default. ```bash npx amman start ```