1. Create the mint
A mint with metadata, pause, a permanent delegate, permissioned burn, an
onchain allowlist, and frozen-by-default accounts, with the operational
authorities on different keys.
2. Gate the holders
Put an address on the allowlist, watch its account thaw, and confirm that
an address which is not on the list cannot hold the token.
3. Operate the token
Freeze one account, pause the token, force a transfer, burn with and
without the holder, and offboard a wallet.
~/.config/solana and
the mint’s addresses from environment variables, so you run them one after
another from a terminal. Every code block on these pages is tested. Most steps
are shown in all four implementations; where a step is shown only for some of
them, the page says so. The output under it is what that script printed on a local
test network (Surfpool).
Before you start
You need the Solana CLI for key files and transfers, and Node.js 20.18 or later for the TypeScript implementations or a Rust toolchain for the Rust one.1. Create the project
- Mosaic SDK
- Kit
- Web3.js v3
- Rust
The scripts use top-level
await, so the project must be an ES module
project. The Mosaic SDK and the Token ACL clients it uses declare
@solana/kit 6 and older Token-2022 clients; the overrides keep the
project on one copy of Kit 8 and its @solana/sysvars, and give the Token
ACL client the Token-2022 client built for Kit 8.Terminal
mkdir gated-token && cd gated-token
npm init -y && npm pkg set type=module
npm pkg set 'overrides[@solana/kit]=$@solana/kit' \
'overrides[@solana/sysvars]=$@solana/kit' \
'overrides[@solana/token-acl-sdk][@solana-program/token-2022]=^0.19.0'
npm install @solana/kit@8 @solana/mosaic-sdk@0.2.0
npm install --save-dev tsx
The scripts use top-level
await, so the project must be an ES module
project. The Token ACL clients declare @solana/kit 6 and an older
@solana-program/token-2022; the overrides keep the project on one copy
of each.Terminal
mkdir gated-token && cd gated-token
npm init -y && npm pkg set type=module
npm pkg set 'overrides[@solana/kit]=$@solana/kit' \
'overrides[@solana/token-acl-sdk][@solana-program/token-2022]=$@solana-program/token-2022'
npm install @solana/kit@8 @solana-program/system@0.15 \
@solana-program/token-2022@0.19 @solana/token-acl-sdk @solana/token-acl-gate-sdk
npm install --save-dev tsx
The scripts use top-level
await, so the project must be an ES module
project. The Token ACL clients declare @solana/kit 6 and an older
@solana-program/token-2022; the overrides keep the project on the copy
of Kit that web3.js v3 uses, and on one copy of the Token-2022 client.Terminal
mkdir gated-token && cd gated-token
npm init -y && npm pkg set type=module
npm pkg set 'overrides[@solana/kit]=$@solana/kit' \
'overrides[@solana/token-acl-sdk][@solana-program/token-2022]=$@solana-program/token-2022'
npm install @solana/web3.js @solana/kit@8 @solana-program/system@0.15 \
@solana-program/token-2022@0.19 @solana/token-acl-sdk @solana/token-acl-gate-sdk
npm install --save-dev tsx
The published Rust clients for Token ACL and its gate program pin
Each step is a binary in
spl-token-2022-interface 2.x, which predates the Permissioned Burn
extension this mint uses, so the crate builds those instructions itself
(src/acl.rs, below).Terminal
cargo new --lib gated-token && cd gated-token && mkdir src/bin
cargo add anyhow tokio --features tokio/full
cargo add solana-client@=4.2.2 solana-sdk@4 solana-commitment-config@3 \
solana-system-interface@3 solana-account-decoder-client-types@4 \
spl-token-2022-interface@3 spl-token-metadata-interface@1
src/bin, run with
cargo run --release --bin <step> -- <arguments>.The Mosaic SDK and the Token ACL clients are pre-1.0, and a minor release can
change their APIs. These tutorials are tested against
@solana/mosaic-sdk
0.2.0, @solana/token-acl-sdk 0.4.0, and @solana/token-acl-gate-sdk 0.3.1.
Keep those versions pinned in anything that depends on them, and check the
Mosaic and
Token ACL repositories
before you upgrade.2. Generate the issuer’s keys
The fee payer,tokenization-demo.json, creates the mint and holds the mint
authority. Create the four operational keys now as well; the next page explains
what each one controls.
Terminal
solana-keygen new --no-bip39-passphrase --silent \
--outfile ~/.config/solana/tokenization-demo.json
mkdir -p ~/.config/solana/demo-authorities
for role in metadata pause delegate burn; do
solana-keygen new --no-bip39-passphrase --silent \
--outfile ~/.config/solana/demo-authorities/$role.json
done
3. Pick a network
The scripts read the network from two environment variables and use devnet when they are unset.-
Local: install the
Surfpool CLI
(1.6 or later) and run
surfpool start. In the terminal you run the scripts from, set the two variables:Terminalexport RPC_URL=http://127.0.0.1:8899 RPC_SUBSCRIPTIONS_URL=ws://127.0.0.1:8900 - Devnet: leave both unset.
-
Local: airdrop SOL from Surfpool:
Terminal
solana airdrop 2 $(solana-keygen pubkey ~/.config/solana/tokenization-demo.json) \ --url $RPC_URL -
Devnet: the public devnet RPC no longer serves airdrops. Print the fee
payer’s address with
solana-keygen pubkey ~/.config/solana/tokenization-demo.jsonand request devnet SOL for it from the Solana Faucet.
4. Add the shared helpers
Save this ascommon.ts (in Rust, src/lib.rs). Every script imports it: it
creates the connection, loads key files, reads $MINT and $LIST, and sends
transactions. When a transaction is rejected, it prints the failing program’s
error and exits with a non-zero code.
// common.ts: the connection, key files, and send helper every script imports.
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import {
assertIsTransactionWithBlockhashLifetime,
createKeyPairSignerFromBytes,
createSolanaRpc,
createSolanaRpcSubscriptions,
getSignatureFromTransaction,
isSolanaError,
sendAndConfirmTransactionFactory,
signTransactionMessageWithSigners,
SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,
} from "@solana/kit";
// Devnet unless RPC_URL and RPC_SUBSCRIPTIONS_URL point somewhere else, for
// example a local Surfpool at http://127.0.0.1:8899 and ws://127.0.0.1:8900.
export const rpc = createSolanaRpc(
process.env.RPC_URL ?? "https://api.devnet.solana.com",
);
export const rpcSubscriptions = createSolanaRpcSubscriptions(
process.env.RPC_SUBSCRIPTIONS_URL ?? "wss://api.devnet.solana.com",
);
// Key files live in ~/.config/solana, as solana-keygen writes them.
export async function loadSigner(name: string) {
const path = join(homedir(), ".config", "solana", `${name}.json`);
const bytes = JSON.parse(await readFile(path, "utf8")) as number[];
return createKeyPairSignerFromBytes(new Uint8Array(bytes));
}
export function env(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`export ${name} before running this script`);
return value;
}
export function arg(index: number, name: string): string {
const value = process.argv[index + 1];
if (!value) throw new Error(`pass ${name} as argument ${index}`);
return value;
}
const sendAndConfirm = sendAndConfirmTransactionFactory({
rpc,
rpcSubscriptions,
});
// Signs a transaction message with every signer it references, sends it, and
// waits for "confirmed". A rejected transaction prints the program error and
// sets a non-zero exit code instead of throwing.
export async function sendMessage(
message: Parameters<typeof signTransactionMessageWithSigners>[0],
) {
const transaction = await signTransactionMessageWithSigners(message);
assertIsTransactionWithBlockhashLifetime(transaction);
try {
await sendAndConfirm(transaction, { commitment: "confirmed" });
console.log("Signature:", getSignatureFromTransaction(transaction));
} catch (error) {
const logs = isSolanaError(
error,
SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,
)
? (error.context.logs ?? [])
: [];
// The first failing program in the log is where the transaction stopped.
const failed = logs.find((line) => line.includes(" failed: "));
console.log("Failed:", failed ?? (error as Error).message);
process.exitCode = 1;
}
}
// common.ts: the connection, key files, and send helper every script imports.
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import {
appendTransactionMessageInstructions,
assertIsTransactionWithBlockhashLifetime,
createKeyPairSignerFromBytes,
createSolanaRpc,
createSolanaRpcSubscriptions,
createTransactionMessage,
getSignatureFromTransaction,
isSolanaError,
pipe,
sendAndConfirmTransactionFactory,
setTransactionMessageFeePayerSigner,
setTransactionMessageLifetimeUsingBlockhash,
signTransactionMessageWithSigners,
SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,
type Instruction,
type TransactionSigner,
} from "@solana/kit";
// Devnet unless RPC_URL and RPC_SUBSCRIPTIONS_URL point somewhere else, for
// example a local Surfpool at http://127.0.0.1:8899 and ws://127.0.0.1:8900.
export const rpc = createSolanaRpc(
process.env.RPC_URL ?? "https://api.devnet.solana.com",
);
export const rpcSubscriptions = createSolanaRpcSubscriptions(
process.env.RPC_SUBSCRIPTIONS_URL ?? "wss://api.devnet.solana.com",
);
// Key files live in ~/.config/solana, as solana-keygen writes them.
export async function loadSigner(name: string) {
const path = join(homedir(), ".config", "solana", `${name}.json`);
const bytes = JSON.parse(await readFile(path, "utf8")) as number[];
return createKeyPairSignerFromBytes(new Uint8Array(bytes));
}
export function env(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`export ${name} before running this script`);
return value;
}
export function arg(index: number, name: string): string {
const value = process.argv[index + 1];
if (!value) throw new Error(`pass ${name} as argument ${index}`);
return value;
}
const sendAndConfirm = sendAndConfirmTransactionFactory({
rpc,
rpcSubscriptions,
});
// Builds one transaction from the instructions, signs it with every signer
// they reference, sends it, and waits for "confirmed". A rejected transaction
// prints the program error and sets a non-zero exit code instead of throwing.
export async function send(
feePayer: TransactionSigner,
instructions: Instruction[],
) {
const { value: latestBlockhash } = await rpc.getLatestBlockhash().send();
const message = pipe(
createTransactionMessage({ version: 0 }),
(m) => setTransactionMessageFeePayerSigner(feePayer, m),
(m) => setTransactionMessageLifetimeUsingBlockhash(latestBlockhash, m),
(m) => appendTransactionMessageInstructions(instructions, m),
);
const transaction = await signTransactionMessageWithSigners(message);
assertIsTransactionWithBlockhashLifetime(transaction);
try {
await sendAndConfirm(transaction, { commitment: "confirmed" });
console.log("Signature:", getSignatureFromTransaction(transaction));
} catch (error) {
const logs = isSolanaError(
error,
SOLANA_ERROR__JSON_RPC__SERVER_ERROR_SEND_TRANSACTION_PREFLIGHT_FAILURE,
)
? (error.context.logs ?? [])
: [];
// The first failing program in the log is where the transaction stopped.
const failed = logs.find((line) => line.includes(" failed: "));
console.log("Failed:", failed ?? (error as Error).message);
process.exitCode = 1;
}
}
// Scales a decimal amount such as "1.5" to base units without a float.
export function toBaseUnits(amount: string, decimals: number): bigint {
const [whole, fraction = ""] = amount.split(".");
return BigInt(whole + fraction.padEnd(decimals, "0").slice(0, decimals));
}
// common.ts: the connection, key files, and send helper every script imports.
import { readFile } from "node:fs/promises";
import { homedir } from "node:os";
import { join } from "node:path";
import {
Connection,
Keypair,
PublicKey,
sendAndConfirmTransaction,
SendTransactionError,
Transaction,
} from "@solana/web3.js";
// Devnet unless RPC_URL and RPC_SUBSCRIPTIONS_URL point somewhere else, for
// example a local Surfpool at http://127.0.0.1:8899 and ws://127.0.0.1:8900.
export const connection = new Connection(
process.env.RPC_URL ?? "https://api.devnet.solana.com",
{
commitment: "confirmed",
wsEndpoint: process.env.RPC_SUBSCRIPTIONS_URL,
},
);
// Key files live in ~/.config/solana, as solana-keygen writes them.
export async function loadKeypair(name: string) {
const path = join(homedir(), ".config", "solana", `${name}.json`);
const bytes = JSON.parse(await readFile(path, "utf8")) as number[];
return Keypair.fromSecretKey(new Uint8Array(bytes));
}
export function env(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`export ${name} before running this script`);
return value;
}
export function arg(index: number, name: string): string {
const value = process.argv[index + 1];
if (!value) throw new Error(`pass ${name} as argument ${index}`);
return value;
}
// The program clients take addresses, which toBase58() returns in v3.
export const addressOf = (value: string) => new PublicKey(value).toBase58();
// Sends the instructions in one transaction, paid by the first signer, and
// waits for "confirmed". A rejected transaction prints the program error and
// sets a non-zero exit code instead of throwing.
export async function send(
signers: Keypair[],
instructions: Parameters<Transaction["add"]>,
) {
try {
const signature = await sendAndConfirmTransaction(
connection,
new Transaction().add(...instructions),
signers,
);
console.log("Signature:", signature);
} catch (error) {
if (!(error instanceof SendTransactionError)) throw error;
// The first failing program in the log is where the transaction stopped.
const failed = error.logs?.find((line) => line.includes(" failed: "));
console.log("Failed:", failed ?? error.transactionError.message);
process.exitCode = 1;
}
}
// Scales a decimal amount such as "1.5" to base units without a float.
export function toBaseUnits(amount: string, decimals: number): bigint {
const [whole, fraction = ""] = amount.split(".");
return BigInt(whole + fraction.padEnd(decimals, "0").slice(0, decimals));
}
// src/lib.rs: the connection, key files, and send helper every binary uses.
pub mod acl;
use anyhow::{anyhow, Context, Result};
use solana_client::rpc_request::{RpcError, RpcResponseErrorData};
use solana_client::{client_error::ClientErrorKind, nonblocking::rpc_client::RpcClient};
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{
instruction::Instruction,
pubkey::Pubkey,
signature::{read_keypair_file, Keypair, Signer},
transaction::Transaction,
};
use spl_token_2022_interface::{
extension::StateWithExtensions,
state::{Account, AccountState, Mint},
};
pub const TOKEN_2022: Pubkey = spl_token_2022_interface::ID;
// Devnet unless RPC_URL points somewhere else, for example a local Surfpool at
// http://127.0.0.1:8899.
pub fn rpc_with(commitment: CommitmentConfig) -> RpcClient {
let url =
std::env::var("RPC_URL").unwrap_or_else(|_| "https://api.devnet.solana.com".to_string());
RpcClient::new_with_commitment(url, commitment)
}
pub fn rpc() -> RpcClient {
rpc_with(CommitmentConfig::confirmed())
}
// Key files live in ~/.config/solana, as solana-keygen writes them.
pub fn load_keypair(name: &str) -> Result<Keypair> {
let home = std::env::var("HOME").context("HOME is not set")?;
let path = std::path::Path::new(&home)
.join(".config/solana")
.join(format!("{name}.json"));
read_keypair_file(&path).map_err(|e| anyhow!("{}: {e}", path.display()))
}
pub fn env(name: &str) -> Result<Pubkey> {
let value =
std::env::var(name).map_err(|_| anyhow!("export {name} before running this binary"))?;
value
.parse()
.with_context(|| format!("${name} is not an address"))
}
pub fn arg(index: usize, name: &str) -> Result<String> {
std::env::args()
.nth(index)
.ok_or_else(|| anyhow!("pass {name} as argument {index}"))
}
pub fn arg_pubkey(index: usize, name: &str) -> Result<Pubkey> {
arg(index, name)?
.parse()
.with_context(|| format!("{name} is not an address"))
}
// Sends the instructions in one transaction, paid by the first signer, and
// waits for "confirmed". A rejected transaction prints the program error and
// sets a non-zero exit code instead of returning an error.
pub async fn send(
rpc: &RpcClient,
signers: &[&Keypair],
instructions: &[Instruction],
) -> Result<()> {
let blockhash = rpc.get_latest_blockhash().await?;
let transaction = Transaction::new_signed_with_payer(
instructions,
Some(&signers[0].pubkey()),
signers,
blockhash,
);
match rpc.send_and_confirm_transaction(&transaction).await {
Ok(signature) => println!("Signature: {signature}"),
Err(error) => {
// The first failing program in the log is where the transaction stopped.
let logs = match error.kind() {
ClientErrorKind::RpcError(RpcError::RpcResponseError {
data: RpcResponseErrorData::SendTransactionPreflightFailure(result),
..
}) => result.logs.clone().unwrap_or_default(),
_ => vec![],
};
match logs.iter().find(|line| line.contains(" failed: ")) {
Some(line) => println!("Failed: {line}"),
None => println!("Failed: {error}"),
}
std::process::exit(1);
}
}
Ok(())
}
// The associated token account of an owner for this Token-2022 mint.
pub fn ata(mint: &Pubkey, owner: &Pubkey) -> Pubkey {
acl::pda(
&acl::ATA_PROGRAM,
&[owner.as_ref(), TOKEN_2022.as_ref(), mint.as_ref()],
)
}
pub async fn mint_decimals(rpc: &RpcClient, mint: &Pubkey) -> Result<u8> {
let data = rpc.get_account_data(mint).await?;
Ok(StateWithExtensions::<Mint>::unpack(&data)?.base.decimals)
}
// Whether a token account exists and whether it is frozen.
pub async fn token_account_state(
rpc: &RpcClient,
address: &Pubkey,
) -> Result<Option<AccountState>> {
let account = rpc
.get_account_with_commitment(address, rpc.commitment())
.await?
.value;
match account {
Some(account) => Ok(Some(
StateWithExtensions::<Account>::unpack(&account.data)?
.base
.state,
)),
None => Ok(None),
}
}
// Scales a decimal amount such as "1.5" to base units without a float.
pub fn to_base_units(amount: &str, decimals: u8) -> Result<u64> {
let (whole, fraction) = amount.split_once('.').unwrap_or((amount, ""));
let width = decimals as usize;
let mut digits = format!("{whole}{fraction:0<width$}");
digits.truncate(whole.len() + width);
digits
.parse()
.with_context(|| format!("invalid amount {amount}"))
}
gate.ts
(in Rust, src/acl.rs). New accounts on the mint start frozen, and
openThroughGate (open_through_gate in Rust) returns the instructions that
create a holder’s account and thaw it through the gate. The thaw is permissionless: anyone can send it, and
the gate program approves it only for a wallet on the allowlist. The Mosaic SDK
does the same inside its transaction builders.
// gate.ts: open a holder's token account and thaw it through the gate.
import {
AccountRole,
type Address,
type Instruction,
type TransactionSigner,
} from "@solana/kit";
import {
AccountState,
fetchMaybeToken,
findAssociatedTokenPda,
getCreateAssociatedTokenIdempotentInstruction,
TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import {
fetchMintConfig,
findFlagAccountPda,
findMintConfigPda,
findThawExtraMetasAccountPda,
getThawPermissionlessInstruction,
} from "@solana/token-acl-sdk";
import { findWalletEntryPda } from "@solana/token-acl-gate-sdk";
import { rpc } from "./common";
// Token ACL thaws a frozen account only when the gate program approves the
// owner. The gate reads three extra accounts: its extra-metas record for the
// mint, the allowlist ($LIST), and the owner's entry on that list.
export async function thawThroughGate(
payer: TransactionSigner,
mint: Address,
tokenAccount: Address,
owner: Address,
listConfig: Address,
): Promise<Instruction> {
const [mintConfig] = await findMintConfigPda({ mint });
const { data: config } = await fetchMintConfig(rpc, mintConfig);
const gate = { programAddress: config.gatingProgram };
const [flagAccount] = await findFlagAccountPda({ tokenAccount });
const [extraMetas] = await findThawExtraMetasAccountPda({ mint }, gate);
const [walletEntry] = await findWalletEntryPda(
{ listConfig, wallet: owner },
gate,
);
const instruction = getThawPermissionlessInstruction({
authority: payer,
mint,
tokenAccount,
flagAccount,
tokenAccountOwner: owner,
mintConfig,
gatingProgram: config.gatingProgram,
});
const extra = [extraMetas, listConfig, walletEntry].map((address) => ({
address,
role: AccountRole.READONLY,
}));
return { ...instruction, accounts: [...instruction.accounts, ...extra] };
}
// New accounts on this mint start frozen. Returns the owner's token account
// and the instructions that create it (if missing) and thaw it (if frozen).
export async function openThroughGate(
payer: TransactionSigner,
mint: Address,
owner: Address,
listConfig: Address,
) {
const [tokenAccount] = await findAssociatedTokenPda({
mint,
owner,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
});
const account = await fetchMaybeToken(rpc, tokenAccount);
const instructions: Instruction[] = [];
if (!account.exists) {
instructions.push(
getCreateAssociatedTokenIdempotentInstruction({
payer,
ata: tokenAccount,
owner,
mint,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
}),
);
}
if (!account.exists || account.data.state === AccountState.Frozen) {
instructions.push(
await thawThroughGate(payer, mint, tokenAccount, owner, listConfig),
);
}
return { tokenAccount, instructions };
}
// gate.ts: open a holder's token account and thaw it through the gate.
import { AccountRole, type Address, type Instruction } from "@solana/kit";
import { type Keypair, PublicKey } from "@solana/web3.js";
import {
AccountState,
findAssociatedTokenPda,
getCreateAssociatedTokenIdempotentInstruction,
getTokenDecoder,
TOKEN_2022_PROGRAM_ADDRESS,
} from "@solana-program/token-2022";
import {
findFlagAccountPda,
findMintConfigPda,
findThawExtraMetasAccountPda,
getMintConfigDecoder,
getThawPermissionlessInstruction,
} from "@solana/token-acl-sdk";
import { findWalletEntryPda } from "@solana/token-acl-gate-sdk";
import { connection } from "./common";
// Token ACL thaws a frozen account only when the gate program approves the
// owner. The gate reads three extra accounts: its extra-metas record for the
// mint, the allowlist ($LIST), and the owner's entry on that list.
export async function thawThroughGate(
payer: Keypair,
mint: Address,
tokenAccount: Address,
owner: Address,
listConfig: Address,
): Promise<Instruction> {
const [mintConfig] = await findMintConfigPda({ mint });
const configAccount = await connection.getAccountInfo(
new PublicKey(mintConfig),
);
const config = getMintConfigDecoder().decode(configAccount!.data);
const gate = { programAddress: config.gatingProgram };
const [flagAccount] = await findFlagAccountPda({ tokenAccount });
const [extraMetas] = await findThawExtraMetasAccountPda({ mint }, gate);
const [walletEntry] = await findWalletEntryPda(
{ listConfig, wallet: owner },
gate,
);
const instruction = getThawPermissionlessInstruction({
authority: payer,
mint,
tokenAccount,
flagAccount,
tokenAccountOwner: owner,
mintConfig,
gatingProgram: config.gatingProgram,
});
const extra = [extraMetas, listConfig, walletEntry].map((address) => ({
address,
role: AccountRole.READONLY,
}));
return { ...instruction, accounts: [...instruction.accounts, ...extra] };
}
// New accounts on this mint start frozen. Returns the owner's token account
// and the instructions that create it (if missing) and thaw it (if frozen).
export async function openThroughGate(
payer: Keypair,
mint: Address,
owner: Address,
listConfig: Address,
) {
const [tokenAccount] = await findAssociatedTokenPda({
mint,
owner,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
});
const info = await connection.getAccountInfo(new PublicKey(tokenAccount));
const frozen =
info !== null &&
getTokenDecoder().decode(info.data).state === AccountState.Frozen;
const instructions: Instruction[] = [];
if (!info) {
instructions.push(
getCreateAssociatedTokenIdempotentInstruction({
payer,
ata: tokenAccount,
owner,
mint,
tokenProgram: TOKEN_2022_PROGRAM_ADDRESS,
}),
);
}
if (!info || frozen) {
instructions.push(
await thawThroughGate(payer, mint, tokenAccount, owner, listConfig),
);
}
return { tokenAccount, instructions };
}
// src/acl.rs: Token ACL and gate program instructions, built by hand.
//
// The published Rust clients for both programs pin spl-token-2022-interface
// 2.x, which predates the Permissioned Burn extension this mint carries. Each
// instruction is a one-byte discriminator followed by an account list.
use solana_sdk::{
instruction::{AccountMeta, Instruction},
pubkey::Pubkey,
};
use crate::{ata, token_account_state, TOKEN_2022};
use solana_client::nonblocking::rpc_client::RpcClient;
use spl_token_2022_interface::state::AccountState;
pub const TOKEN_ACL: Pubkey = Pubkey::from_str_const("TACLkU6CiCdkQN2MjoyDkVg2yAH9zkxiHDsiztQ52TP");
pub const GATE: Pubkey = Pubkey::from_str_const("GATEzzqxhJnsWF6vHRsgtixxSB8PaQdcqGEVTEHWiULz");
pub const ATA_PROGRAM: Pubkey =
Pubkey::from_str_const("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
const SYSTEM_PROGRAM: Pubkey = solana_system_interface::program::ID;
pub fn pda(program: &Pubkey, seeds: &[&[u8]]) -> Pubkey {
Pubkey::find_program_address(seeds, program).0
}
pub fn mint_config(mint: &Pubkey) -> Pubkey {
pda(&TOKEN_ACL, &[b"MINT_CONFIG", mint.as_ref()])
}
// The allowlist, keyed by its authority (the key that created the mint) and
// the mint, and one entry account per approved wallet.
pub fn list_config(authority: &Pubkey, mint: &Pubkey) -> Pubkey {
pda(&GATE, &[b"list_config", authority.as_ref(), mint.as_ref()])
}
pub fn wallet_entry(list: &Pubkey, wallet: &Pubkey) -> Pubkey {
pda(&GATE, &[b"wallet_entry", list.as_ref(), wallet.as_ref()])
}
// Token ACL createConfig (0): takes the mint's freeze authority, which must
// sign, and points the config at the gate program.
pub fn create_config(payer: &Pubkey, authority: &Pubkey, mint: &Pubkey) -> Instruction {
Instruction {
program_id: TOKEN_ACL,
accounts: vec![
AccountMeta::new(*payer, true),
AccountMeta::new_readonly(*authority, true),
AccountMeta::new(*mint, false),
AccountMeta::new(mint_config(mint), false),
AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
AccountMeta::new_readonly(TOKEN_2022, false),
],
data: [vec![0], GATE.to_bytes().to_vec()].concat(),
}
}
// Token ACL togglePermissionlessInstructions (8): freeze off, thaw on.
pub fn enable_permissionless_thaw(authority: &Pubkey, mint: &Pubkey) -> Instruction {
Instruction {
program_id: TOKEN_ACL,
accounts: vec![
AccountMeta::new_readonly(*authority, true),
AccountMeta::new(mint_config(mint), false),
],
data: vec![8, 0, 1],
}
}
// Gate createList (1): mode 0 is an allowlist; the seed is the mint.
pub fn create_allowlist(authority: &Pubkey, mint: &Pubkey) -> Instruction {
Instruction {
program_id: GATE,
accounts: vec![
AccountMeta::new_readonly(*authority, true),
AccountMeta::new(*authority, true),
AccountMeta::new(list_config(authority, mint), false),
AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
],
data: [vec![1, 0], mint.to_bytes().to_vec()].concat(),
}
}
// Gate setupExtraMetas (4): records the list as an account the gate reads on
// every thaw.
pub fn setup_extra_metas(authority: &Pubkey, mint: &Pubkey) -> Instruction {
Instruction {
program_id: GATE,
accounts: vec![
AccountMeta::new_readonly(*authority, true),
AccountMeta::new(*authority, true),
AccountMeta::new_readonly(mint_config(mint), false),
AccountMeta::new_readonly(*mint, false),
AccountMeta::new(
pda(&GATE, &[b"thaw_extra_account_metas", mint.as_ref()]),
false,
),
AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
AccountMeta::new_readonly(list_config(authority, mint), false),
],
data: vec![4],
}
}
// Gate addWallet (2) and removeWallet (3).
pub fn add_wallet(authority: &Pubkey, list: &Pubkey, wallet: &Pubkey) -> Instruction {
Instruction {
program_id: GATE,
accounts: vec![
AccountMeta::new_readonly(*authority, true),
AccountMeta::new(*authority, true),
AccountMeta::new(*list, false),
AccountMeta::new_readonly(*wallet, false),
AccountMeta::new(wallet_entry(list, wallet), false),
AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
],
data: vec![2],
}
}
pub fn remove_wallet(authority: &Pubkey, list: &Pubkey, wallet: &Pubkey) -> Instruction {
Instruction {
program_id: GATE,
accounts: vec![
AccountMeta::new(*authority, true),
AccountMeta::new(*list, false),
AccountMeta::new(wallet_entry(list, wallet), false),
],
data: vec![3],
}
}
// Token ACL freeze (5) and thaw (4), signed by the config authority. Token ACL
// holds the mint's freeze authority.
pub fn freeze(authority: &Pubkey, mint: &Pubkey, token_account: &Pubkey) -> Instruction {
freeze_or_thaw(5, authority, mint, token_account)
}
pub fn thaw(authority: &Pubkey, mint: &Pubkey, token_account: &Pubkey) -> Instruction {
freeze_or_thaw(4, authority, mint, token_account)
}
fn freeze_or_thaw(
discriminator: u8,
authority: &Pubkey,
mint: &Pubkey,
token_account: &Pubkey,
) -> Instruction {
Instruction {
program_id: TOKEN_ACL,
accounts: vec![
AccountMeta::new_readonly(*authority, true),
AccountMeta::new_readonly(*mint, false),
AccountMeta::new(*token_account, false),
AccountMeta::new_readonly(mint_config(mint), false),
AccountMeta::new_readonly(TOKEN_2022, false),
],
data: vec![discriminator],
}
}
// Token ACL thawPermissionless (6). Token ACL asks the gate program, which
// reads three extra accounts: its extra-metas record for the mint, the
// allowlist ($LIST), and the owner's entry on that list.
pub fn thaw_through_gate(
payer: &Pubkey,
mint: &Pubkey,
token_account: &Pubkey,
owner: &Pubkey,
list: &Pubkey,
) -> Instruction {
Instruction {
program_id: TOKEN_ACL,
accounts: vec![
AccountMeta::new(*payer, true),
AccountMeta::new_readonly(*mint, false),
AccountMeta::new(*token_account, false),
AccountMeta::new(
pda(&TOKEN_ACL, &[b"FLAG_ACCOUNT", token_account.as_ref()]),
false,
),
AccountMeta::new_readonly(*owner, false),
AccountMeta::new_readonly(mint_config(mint), false),
AccountMeta::new_readonly(TOKEN_2022, false),
AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
AccountMeta::new_readonly(GATE, false),
AccountMeta::new_readonly(
pda(&GATE, &[b"thaw_extra_account_metas", mint.as_ref()]),
false,
),
AccountMeta::new_readonly(*list, false),
AccountMeta::new_readonly(wallet_entry(list, owner), false),
],
data: vec![6],
}
}
// New accounts on this mint start frozen. Returns the owner's token account
// and the instructions that create it (if missing) and thaw it (if frozen).
pub async fn open_through_gate(
rpc: &RpcClient,
payer: &Pubkey,
mint: &Pubkey,
owner: &Pubkey,
list: &Pubkey,
) -> anyhow::Result<(Pubkey, Vec<Instruction>)> {
let token_account = ata(mint, owner);
let state = token_account_state(rpc, &token_account).await?;
let mut instructions = Vec::new();
if state.is_none() {
// Associated Token Account program, create idempotent (1).
instructions.push(Instruction {
program_id: ATA_PROGRAM,
accounts: vec![
AccountMeta::new(*payer, true),
AccountMeta::new(token_account, false),
AccountMeta::new_readonly(*owner, false),
AccountMeta::new_readonly(*mint, false),
AccountMeta::new_readonly(SYSTEM_PROGRAM, false),
AccountMeta::new_readonly(TOKEN_2022, false),
],
data: vec![1],
});
}
if state.is_none() || state == Some(AccountState::Frozen) {
instructions.push(thaw_through_gate(payer, mint, &token_account, owner, list));
}
Ok((token_account, instructions))
}
Mosaic also publishes a CLI,
@solana/mosaic-cli. Its write commands do not
send transactions in version 0.2.0 (October 2026), so these tutorials use the
SDK.Next steps
- Create the mint: a Token-2022 mint with its operational authorities on separate keys