- Mint To creates new tokens of a mint and deposits them to a specified token account.
- Before we can mint any tokens, we need an initialized mint account (SPL, Token 2022 or Light) for which we hold the mint authority.
- TypeScript Client
- Rust Client
- Program
mintToInterface mints tokens to token accounts in a single call.The function auto-detects the token program (SPL, Token 2022, or Light) from the mint address.Compare to SPL:Find the source code
here.
Mint Tokens to Light Token Account
Installation
Installation
- npm
- yarn
- pnpm
Install packages in your working directory:Install the CLI globally:
Report incorrect code
Copy
Ask AI
npm install @lightprotocol/stateless.js@beta \
@lightprotocol/compressed-token@beta
Report incorrect code
Copy
Ask AI
npm install -g @lightprotocol/zk-compression-cli@beta
Install packages in your working directory:Install the CLI globally:
Report incorrect code
Copy
Ask AI
yarn add @lightprotocol/stateless.js@beta \
@lightprotocol/compressed-token@beta
Report incorrect code
Copy
Ask AI
yarn global add @lightprotocol/zk-compression-cli@beta
Install packages in your working directory:Install the CLI globally:
Report incorrect code
Copy
Ask AI
pnpm add @lightprotocol/stateless.js@beta \
@lightprotocol/compressed-token@beta
Report incorrect code
Copy
Ask AI
pnpm add -g @lightprotocol/zk-compression-cli@beta
- Localnet
- Devnet
Report incorrect code
Copy
Ask AI
# start local test-validator in a separate terminal
light test-validator
In the code examples, use
createRpc() without arguments for localnet.Get an API key from Helius and add to
.env:.env
Report incorrect code
Copy
Ask AI
API_KEY=<your-helius-api-key>
In the code examples, use
createRpc(RPC_URL) with the devnet URL.- Action
- Instruction
Report incorrect code
Copy
Ask AI
import "dotenv/config";
import { Keypair } from "@solana/web3.js";
import { createRpc } from "@lightprotocol/stateless.js";
import {
createMintInterface,
createAtaInterface,
mintToInterface,
getAssociatedTokenAddressInterface,
} from "@lightprotocol/compressed-token";
import { homedir } from "os";
import { readFileSync } from "fs";
// devnet:
const RPC_URL = `https://devnet.helius-rpc.com?api-key=${process.env.API_KEY!}`;
const rpc = createRpc(RPC_URL);
// localnet:
// const rpc = createRpc();
const payer = Keypair.fromSecretKey(
new Uint8Array(
JSON.parse(readFileSync(`${homedir()}/.config/solana/id.json`, "utf8"))
)
);
(async function () {
const { mint } = await createMintInterface(rpc, payer, payer, null, 9);
const recipient = Keypair.generate();
await createAtaInterface(rpc, payer, mint, recipient.publicKey);
const destination = getAssociatedTokenAddressInterface(mint, recipient.publicKey);
const tx = await mintToInterface(rpc, payer, mint, destination, payer, 1_000_000_000);
console.log("Tx:", tx);
})();
Report incorrect code
Copy
Ask AI
import "dotenv/config";
import {
Keypair,
ComputeBudgetProgram,
Transaction,
sendAndConfirmTransaction,
} from "@solana/web3.js";
import { createRpc, bn, DerivationMode } from "@lightprotocol/stateless.js";
import {
createMintInterface,
createAtaInterface,
createMintToInterfaceInstruction,
getMintInterface,
getAssociatedTokenAddressInterface,
} from "@lightprotocol/compressed-token";
import { homedir } from "os";
import { readFileSync } from "fs";
// devnet:
// const RPC_URL = `https://devnet.helius-rpc.com?api-key=${process.env.API_KEY!}`;
// const rpc = createRpc(RPC_URL);
// localnet:
const rpc = createRpc();
const payer = Keypair.fromSecretKey(
new Uint8Array(
JSON.parse(readFileSync(`${homedir()}/.config/solana/id.json`, "utf8")),
),
);
(async function () {
const { mint } = await createMintInterface(rpc, payer, payer, null, 9);
const recipient = Keypair.generate();
await createAtaInterface(rpc, payer, mint, recipient.publicKey);
const destination = getAssociatedTokenAddressInterface(
mint,
recipient.publicKey,
);
const mintInterface = await getMintInterface(rpc, mint);
let validityProof;
if (mintInterface.merkleContext) {
validityProof = await rpc.getValidityProofV2(
[
{
hash: bn(mintInterface.merkleContext.hash),
leafIndex: mintInterface.merkleContext.leafIndex,
treeInfo: mintInterface.merkleContext.treeInfo,
proveByIndex: mintInterface.merkleContext.proveByIndex,
},
],
[],
DerivationMode.compressible,
);
}
const ix = createMintToInterfaceInstruction(
mintInterface,
destination,
payer.publicKey,
payer.publicKey,
1_000_000_000,
validityProof,
);
const tx = new Transaction().add(
ComputeBudgetProgram.setComputeUnitLimit({ units: 500_000 }),
ix,
);
const signature = await sendAndConfirmTransaction(rpc, tx, [payer]);
console.log("Tx:", signature);
})();
Use
MintTo to mint tokens to a Light Token account.Compare to SPL:Prerequisites
Dependencies
Dependencies
Cargo.toml
Report incorrect code
Copy
Ask AI
[dependencies]
light-token = "0.4.0"
light-client = { version = "0.19.0", features = ["v2"] }
solana-sdk = "2"
borsh = "0.10.4"
tokio = { version = "1", features = ["full"] }
Developer Environment
Developer Environment
- In-Memory (LightProgramTest)
- Localnet (LightClient)
- Devnet (LightClient)
Test with Lite-SVM (…)
Report incorrect code
Copy
Ask AI
# Initialize project
cargo init my-light-project
cd my-light-project
# Run tests
cargo test
Report incorrect code
Copy
Ask AI
use light_program_test::{LightProgramTest, ProgramTestConfig};
use solana_sdk::signer::Signer;
#[tokio::test]
async fn test_example() {
// In-memory test environment
let mut rpc = LightProgramTest::new(ProgramTestConfig::default())
.await
.unwrap();
let payer = rpc.get_payer().insecure_clone();
println!("Payer: {}", payer.pubkey());
}
Connects to a local test validator.
- npm
- yarn
- pnpm
Report incorrect code
Copy
Ask AI
npm install -g @lightprotocol/zk-compression-cli@beta
Report incorrect code
Copy
Ask AI
yarn global add @lightprotocol/zk-compression-cli@beta
Report incorrect code
Copy
Ask AI
pnpm add -g @lightprotocol/zk-compression-cli@beta
Report incorrect code
Copy
Ask AI
# Initialize project
cargo init my-light-project
cd my-light-project
# Start local test validator (in separate terminal)
light test-validator
Report incorrect code
Copy
Ask AI
use light_client::rpc::{LightClient, LightClientConfig, Rpc};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Connects to http://localhost:8899
let rpc = LightClient::new(LightClientConfig::local()).await?;
let slot = rpc.get_slot().await?;
println!("Current slot: {}", slot);
Ok(())
}
Replace
<your-api-key> with your actual API key. Get your API key here.Report incorrect code
Copy
Ask AI
use light_client::rpc::{LightClient, LightClientConfig, Rpc};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let rpc_url = "https://devnet.helius-rpc.com?api-key=<your_api_key>";
let rpc = LightClient::new(
LightClientConfig::new(rpc_url.to_string(), None, None)
).await?;
println!("Connected to Devnet");
Ok(())
}
Mint to Light Token Accounts
View the source code and full example with shared test utilities.
- Action
- Instruction
Report incorrect code
Copy
Ask AI
use borsh::BorshDeserialize;
use light_client::rpc::Rpc;
use light_token_client::actions::{CreateAta, CreateMint, MintTo};
use rust_client::setup_rpc_and_payer;
use solana_sdk::signer::Signer;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let (mut rpc, payer) = setup_rpc_and_payer().await;
// Create mint (payer is also mint authority)
let (_signature, mint) = CreateMint {
decimals: 9,
freeze_authority: None,
token_metadata: None,
seed: None,
}
.execute(&mut rpc, &payer, &payer)
.await?;
// Create associated token account
let (_signature, associated_token_account) = CreateAta {
mint,
owner: payer.pubkey(),
idempotent: true,
}
.execute(&mut rpc, &payer)
.await?;
// Mint tokens (payer is mint authority)
let sig = MintTo {
mint,
destination: associated_token_account,
amount: 1_000_000,
}
.execute(&mut rpc, &payer, &payer)
.await?;
let data = rpc.get_account(associated_token_account).await?.ok_or("Account not found")?;
let token = light_token_interface::state::Token::deserialize(&mut &data.data[..])?;
println!("Balance: {} Tx: {sig}", token.amount);
Ok(())
}
Report incorrect code
Copy
Ask AI
use borsh::BorshDeserialize;
use light_client::rpc::Rpc;
use light_token::instruction::MintTo;
use rust_client::{setup_empty_associated_token_account, SetupContext};
use solana_sdk::signer::Signer;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
// Setup creates mint and empty associated token account
let SetupContext {
mut rpc,
payer,
mint,
associated_token_account,
..
} = setup_empty_associated_token_account().await;
let mint_amount = 1_000_000_000u64;
let mint_to_instruction = MintTo {
mint,
destination: associated_token_account,
amount: mint_amount,
authority: payer.pubkey(),
max_top_up: None,
fee_payer: None,
}
.instruction()?;
let sig = rpc
.create_and_send_transaction(&[mint_to_instruction], &payer.pubkey(), &[&payer])
.await?;
let data = rpc.get_account(associated_token_account).await?.ok_or("Account not found")?;
let token = light_token_interface::state::Token::deserialize(&mut &data.data[..])?;
println!("Balance: {} Tx: {sig}", token.amount);
Ok(())
}
Build Account Infos and CPI the Light Token Program
Useinvoke for external signers or invoke_signed when the authority is a PDA.- invoke (External signer)
- invoke_signed (PDA authority)
Report incorrect code
Copy
Ask AI
use light_token::instruction::MintToCpi;
MintToCpi {
mint: mint.clone(),
destination: destination.clone(),
amount,
authority: authority.clone(),
system_program: system_program.clone(),
fee_payer: None,
max_top_up: None,
}
.invoke()
Report incorrect code
Copy
Ask AI
use light_token::instruction::MintToCpi;
let signer_seeds: &[&[u8]] = &[MINT_AUTHORITY_SEED, &[bump]];
MintToCpi {
mint: mint.clone(),
destination: destination.clone(),
amount,
authority: authority.clone(),
system_program: system_program.clone(),
fee_payer: None,
max_top_up: None,
}
.invoke_signed(&[signer_seeds])
fee_payer and max_top_up are optional fields to customize rent top-ups.
Set to None to use defaults.Full Code Example
View the source code and full example with shared test utilities.
Report incorrect code
Copy
Ask AI
#![allow(unexpected_cfgs, deprecated)]
use anchor_lang::prelude::*;
use light_token::instruction::MintToCpi;
declare_id!("8bXEVmHLtAVqDLJp1dYWAZ61WQmqQKoTQ8LpPbRoUDCp");
#[program]
pub mod light_token_anchor_mint_to {
use super::*;
pub fn mint_to(ctx: Context<MintToAccounts>, amount: u64) -> Result<()> {
MintToCpi {
mint: ctx.accounts.mint.to_account_info(),
destination: ctx.accounts.destination.to_account_info(),
amount,
authority: ctx.accounts.authority.to_account_info(),
system_program: ctx.accounts.system_program.to_account_info(),
max_top_up: None,
fee_payer: None,
}
.invoke()?;
Ok(())
}
}
#[derive(Accounts)]
pub struct MintToAccounts<'info> {
/// CHECK: Light token program for CPI
pub light_token_program: AccountInfo<'info>,
/// CHECK: Validated by light-token CPI
#[account(mut)]
pub mint: AccountInfo<'info>,
/// CHECK: Validated by light-token CPI
#[account(mut)]
pub destination: AccountInfo<'info>,
pub authority: Signer<'info>,
pub system_program: Program<'info, System>,
}