| light-token -> light-token Account |
|
| SPL token -> light-token Account |
|
| light-token -> SPL Account |
|
- TypeScript Client
- Rust Client
- Program Guide
The
transferInterface function transfers tokens between token accounts (SPL, Token-2022, or Light) in a single call.Compare to SPL:Find the source code
here.
1
Transfer Interface
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@alpha \
@lightprotocol/compressed-token@alpha
Report incorrect code
Copy
Ask AI
npm install -g @lightprotocol/zk-compression-cli@alpha
Install packages in your working directory:Install the CLI globally:
Report incorrect code
Copy
Ask AI
yarn add @lightprotocol/stateless.js@alpha \
@lightprotocol/compressed-token@alpha
Report incorrect code
Copy
Ask AI
yarn global add @lightprotocol/zk-compression-cli@alpha
Install packages in your working directory:Install the CLI globally:
Report incorrect code
Copy
Ask AI
pnpm add @lightprotocol/stateless.js@alpha \
@lightprotocol/compressed-token@alpha
Report incorrect code
Copy
Ask AI
pnpm add -g @lightprotocol/zk-compression-cli@alpha
- 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,
transferInterface,
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!}`;
// localnet:
// const RPC_URL = undefined;
const payer = Keypair.fromSecretKey(
new Uint8Array(
JSON.parse(readFileSync(`${homedir()}/.config/solana/id.json`, "utf8"))
)
);
(async function () {
// devnet:
const rpc = createRpc(RPC_URL);
// localnet:
// const rpc = createRpc();
const { mint } = await createMintInterface(rpc, payer, payer, null, 9);
const sender = Keypair.generate();
await createAtaInterface(rpc, payer, mint, sender.publicKey);
const senderAta = getAssociatedTokenAddressInterface(mint, sender.publicKey);
await mintToInterface(rpc, payer, mint, senderAta, payer, 1_000_000_000);
const recipient = Keypair.generate();
await createAtaInterface(rpc, payer, mint, recipient.publicKey);
const recipientAta = getAssociatedTokenAddressInterface(mint, recipient.publicKey);
const tx = await transferInterface(rpc, payer, senderAta, mint, recipientAta, sender, 500_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 } from "@lightprotocol/stateless.js";
import {
createMintInterface,
createAtaInterface,
mintToInterface,
createTransferInterfaceInstruction,
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 sender = Keypair.generate();
await createAtaInterface(rpc, payer, mint, sender.publicKey);
const senderAta = getAssociatedTokenAddressInterface(
mint,
sender.publicKey
);
await mintToInterface(rpc, payer, mint, senderAta, payer, 1_000_000_000);
const recipient = Keypair.generate();
await createAtaInterface(rpc, payer, mint, recipient.publicKey);
const recipientAta = getAssociatedTokenAddressInterface(
mint,
recipient.publicKey
);
const ix = createTransferInterfaceInstruction(
senderAta,
recipientAta,
sender.publicKey,
500_000_000
);
const tx = new Transaction().add(ix);
const signature = await sendAndConfirmTransaction(rpc, tx, [payer, sender]);
console.log("Tx:", signature);
})();
Use the unified
TransferInterface to transfer tokens between token accounts (SPL, Token-2022, or Light) in a single call.1
Prerequisites
Dependencies
Dependencies
Cargo.toml
Report incorrect code
Copy
Ask AI
[dependencies]
light-compressed-token-sdk = "0.1"
light-client = "0.1"
light-token-types = "0.1"
solana-sdk = "2.2"
borsh = "0.10"
tokio = { version = "1.36", features = ["full"] }
[dev-dependencies]
light-program-test = "0.1" # For in-memory tests with LiteSVM
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@alpha
Report incorrect code
Copy
Ask AI
yarn global add @lightprotocol/zk-compression-cli@alpha
Report incorrect code
Copy
Ask AI
pnpm add -g @lightprotocol/zk-compression-cli@alpha
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(())
}
2
Transfer Interface
The example transfers- SPL token -> light-token,
- light-token -> light-token, and
- light-token -> SPL token.
View Source Code or find full examples with tests: examples-light-token.
Report incorrect code
Copy
Ask AI
mod shared;
use anchor_spl::token::spl_token;
use light_client::rpc::Rpc;
use light_program_test::{LightProgramTest, ProgramTestConfig};
use light_token_sdk::{
spl_interface::find_spl_interface_pda_with_index,
token::{
get_associated_token_address, CreateAssociatedTokenAccount, SplInterface,
TransferInterface, LIGHT_TOKEN_PROGRAM_ID,
},
};
use solana_sdk::{signature::Keypair, signer::Signer};
#[tokio::test(flavor = "multi_thread")]
async fn transfer_interface() {
let mut rpc = LightProgramTest::new(ProgramTestConfig::new_v2(true, None))
.await
.unwrap();
let payer = rpc.get_payer().insecure_clone();
let recipient = Keypair::new();
let decimals = 2u8;
let amount = 10_000u64;
// Setup creates mint, mints tokens and creates SPL ATA
let mint = shared::setup_spl_mint(&mut rpc, &payer, decimals).await;
let spl_ata = shared::setup_spl_ata(&mut rpc, &payer, &mint, &payer.pubkey(), amount).await;
let (interface_pda, interface_bump) = find_spl_interface_pda_with_index(&mint, 0, false);
// Create Light ATA
let light_ata_a = get_associated_token_address(&payer.pubkey(), &mint);
let create_ata_a_ix = CreateAssociatedTokenAccount::new(payer.pubkey(), payer.pubkey(), mint)
.instruction()
.unwrap();
rpc.create_and_send_transaction(&[create_ata_a_ix], &payer.pubkey(), &[&payer])
.await
.unwrap();
// Create SPL interface PDA (holds SPL tokens when transferred to Light Token)
let spl_interface = SplInterface {
mint,
spl_token_program: spl_token::ID,
spl_interface_pda: interface_pda,
spl_interface_pda_bump: interface_bump,
};
// 1. Transfer SPL tokens to Light ATA
let spl_to_light_ix = TransferInterface {
source: spl_ata,
destination: light_ata_a,
amount,
decimals,
authority: payer.pubkey(),
payer: payer.pubkey(),
spl_interface: Some(spl_interface.clone()),
max_top_up: None,
source_owner: spl_token::ID,
destination_owner: LIGHT_TOKEN_PROGRAM_ID,
}
.instruction()
.unwrap();
rpc.create_and_send_transaction(&[spl_to_light_ix], &payer.pubkey(), &[&payer])
.await
.unwrap();
// Create Second Light ATA
let light_ata_b = get_associated_token_address(&recipient.pubkey(), &mint);
let create_ata_b_ix =
CreateAssociatedTokenAccount::new(payer.pubkey(), recipient.pubkey(), mint)
.instruction()
.unwrap();
rpc.create_and_send_transaction(&[create_ata_b_ix], &payer.pubkey(), &[&payer])
.await
.unwrap();
// 2. Transfer Light-Tokens to Light ATA
let light_to_light_ix = TransferInterface {
source: light_ata_a,
destination: light_ata_b,
amount: amount / 2,
decimals,
authority: payer.pubkey(),
payer: payer.pubkey(),
spl_interface: None,
max_top_up: None,
source_owner: LIGHT_TOKEN_PROGRAM_ID,
destination_owner: LIGHT_TOKEN_PROGRAM_ID,
}
.instruction()
.unwrap();
rpc.create_and_send_transaction(&[light_to_light_ix], &payer.pubkey(), &[&payer])
.await
.unwrap();
// 3. Transfer Light-Tokens from Light ATA to SPL
let light_to_spl_ix = TransferInterface {
source: light_ata_b,
destination: spl_ata,
amount: amount / 4,
decimals,
authority: recipient.pubkey(),
payer: payer.pubkey(),
spl_interface: Some(spl_interface),
max_top_up: None,
source_owner: LIGHT_TOKEN_PROGRAM_ID,
destination_owner: spl_token::ID,
}
.instruction()
.unwrap();
rpc.create_and_send_transaction(&[light_to_spl_ix], &payer.pubkey(), &[&payer, &recipient])
.await
.unwrap();
}
1
Build Account Infos and CPI
- invoke (External signer)
- invoke_signed (PDA is signer)
Report incorrect code
Copy
Ask AI
use light_token_sdk::token::TransferInterfaceCpi;
TransferInterfaceCpi::new(
amount,
decimals,
source.clone(),
destination.clone(),
authority.clone(),
payer.clone(),
ctoken_authority.clone(),
system_program.clone(),
)
.invoke()
Report incorrect code
Copy
Ask AI
use light_token_sdk::token::TransferInterfaceCpi;
let signer_seeds = authority_seeds!(bump);
TransferInterfaceCpi::new(
amount,
decimals,
source.clone(),
destination.clone(),
authority.clone(),
payer.clone(),
ctoken_authority.clone(),
system_program.clone(),
)
.invoke_signed(&[signer_seeds])
light-token Interface Accounts
light-token Interface Accounts
| mutable | The source account (SPL token account or light-token account). | |
| mutable | The destination account (SPL token account or light-token account). | |
| signer* |
| |
| signer, mutable | Pays transaction fees. | |
| - | The light token program authority PDA. |
Full Code Example
View Source Code or full examples with tests: examples-light-token.
- Anchor
- Native
Report incorrect code
Copy
Ask AI
#![allow(unexpected_cfgs)]
use anchor_lang::prelude::*;
use light_token_sdk::token::TransferInterfaceCpi;
declare_id!("ChkDqFsvNNT5CGrV2YCkmK4DiVSATnXc98mNozPbhC6u");
#[program]
pub mod light_token_anchor_transfer_interface {
use super::*;
pub fn transfer<'info>(
ctx: Context<'_, '_, '_, 'info, TransferAccounts<'info>>,
amount: u64,
decimals: u8,
) -> Result<()> {
TransferInterfaceCpi::new(
amount,
decimals,
ctx.accounts.source.to_account_info(),
ctx.accounts.destination.to_account_info(),
ctx.accounts.authority.to_account_info(),
ctx.accounts.payer.to_account_info(),
ctx.accounts.cpi_authority.to_account_info(),
ctx.accounts.system_program.to_account_info(),
)
.invoke()?;
Ok(())
}
}
#[derive(Accounts)]
pub struct TransferAccounts<'info> {
/// CHECK: Validated by light-token CPI
#[account(mut)]
pub source: AccountInfo<'info>,
/// CHECK: Validated by light-token CPI
#[account(mut)]
pub destination: AccountInfo<'info>,
pub authority: Signer<'info>,
#[account(mut)]
pub payer: Signer<'info>,
/// CHECK: Validated by light-token CPI
pub cpi_authority: AccountInfo<'info>,
pub system_program: Program<'info, System>,
/// CHECK: Light token program for CPI
pub light_token_program: AccountInfo<'info>,
}
Report incorrect code
Copy
Ask AI
use super::authority_seeds;
use light_token_sdk::token::TransferInterfaceCpi;
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult,
program_error::ProgramError,
};
pub fn transfer_invoke(accounts: &[AccountInfo], data: &[u8]) -> ProgramResult {
let [source, destination, authority, payer, ctoken_authority, system_program, _token_program] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
if data.len() < 9 {
return Err(ProgramError::InvalidInstructionData);
}
let amount = u64::from_le_bytes(data[0..8].try_into().unwrap());
let decimals = data[8];
TransferInterfaceCpi::new(
amount,
decimals,
source.clone(),
destination.clone(),
authority.clone(),
payer.clone(),
ctoken_authority.clone(),
system_program.clone(),
)
.invoke()
}
pub fn transfer_invoke_signed(accounts: &[AccountInfo], data: &[u8]) -> ProgramResult {
let [source, destination, authority, payer, ctoken_authority, system_program, _token_program] =
accounts
else {
return Err(ProgramError::NotEnoughAccountKeys);
};
if data.len() < 10 {
return Err(ProgramError::InvalidInstructionData);
}
let amount = u64::from_le_bytes(data[0..8].try_into().unwrap());
let decimals = data[8];
let bump = data[9];
let signer_seeds = authority_seeds!(bump);
TransferInterfaceCpi::new(
amount,
decimals,
source.clone(),
destination.clone(),
authority.clone(),
payer.clone(),
ctoken_authority.clone(),
system_program.clone(),
)
.invoke_signed(&[signer_seeds])
}