//! The gate: a Token-2022 transfer hook that makes a coin tradable only with //! the launchpad's signature. //! //! Every coin launched on Hidden names this program as its transfer hook, so //! Token-2022 calls it on every transfer of the coin. The transfer goes //! through only when the transaction carries a signature from the gate signer, //! a key the launchpad's server holds. A trade built anywhere else has no such //! signature and fails. //! //! What this does not do: it does not hide token accounts. Who holds how much //! is still public; the gate only decides which transactions may move a coin. #![no_std] use pinocchio::{ cpi::{Seed, Signer}, error::ProgramError, no_allocator, nostd_panic_handler, program_entrypoint, sysvars::{instructions::Instructions, rent::Rent, Sysvar}, AccountView, Address, ProgramResult, }; use pinocchio_system::instructions::{Allocate, Assign, CreateAccount, Transfer}; program_entrypoint!(process_instruction, 16); no_allocator!(); nostd_panic_handler!(); /// `sha256("spl-transfer-hook-interface:execute")[..8]`: how Token-2022 addresses the hook. const EXECUTE: [u8; 8] = [105, 37, 101, 197, 75, 251, 102, 26]; const CONFIGURE: u8 = 0; const INIT_MINT: u8 = 1; const PERMIT: u8 = 2; const CONFIG_SEED: &[u8] = b"gate"; /// Fixed by the transfer hook interface: Token-2022 looks the account up under this seed and the mint. const METAS_SEED: &[u8] = b"extra-account-metas"; const CONFIG_VERSION: u8 = 1; /// version (1) + admin (32) + gate signer (32) const CONFIG_LEN: usize = 65; /// The accounts Token-2022 must hand the hook on top of the transfer's own: the config and the instructions sysvar. const EXTRA_ACCOUNTS: usize = 2; /// One entry: kind (1) + address (32) + is signer (1) + is writable (1) const META_LEN: usize = 35; /// discriminator (8) + length (4) + count (4) + entries const METAS_LEN: usize = 16 + EXTRA_ACCOUNTS * META_LEN; const UPGRADEABLE_LOADER: Address = Address::from_str_const("BPFLoaderUpgradeab1e11111111111111111111111"); const INSTRUCTIONS_SYSVAR: Address = Address::from_str_const("Sysvar1nstructions1111111111111111111111111"); /// The transaction does not carry the gate signer's signature. const NOT_PERMITTED: u32 = 0x1001; /// Only the admin (at first: the program's upgrade authority) may configure the gate. const NOT_ADMIN: u32 = 0x1002; pub fn process_instruction(program_id: &Address, accounts: &mut [AccountView], data: &[u8]) -> ProgramResult { if data.len() >= 8 && data[..8] == EXECUTE { return execute(program_id, accounts); } match data.split_first() { Some((&CONFIGURE, rest)) => configure(program_id, accounts, rest), Some((&INIT_MINT, _)) => init_mint(program_id, accounts), Some((&PERMIT, _)) => permit(accounts), _ => Err(ProgramError::InvalidInstructionData), } } /// Called by Token-2022 on every transfer of a gated coin. /// /// Accounts: source, mint, destination, authority, extra-account-metas, config, instructions sysvar. #[inline(never)] fn execute(program_id: &Address, accounts: &[AccountView]) -> ProgramResult { let [_source, _mint, _destination, _authority, _metas, config, instructions, ..] = accounts else { return Err(ProgramError::NotEnoughAccountKeys); }; let gate_signer = read_config(program_id, config)?.1; // `try_from` refuses any account but the real sysvar, so the list below is the transaction's own. let instructions = Instructions::try_from(instructions)?; for index in 0..instructions.num_instructions() { let instruction = instructions.load_instruction_at(index)?; for position in 0..instruction.num_account_metas() { let account = instruction.get_instruction_account_at(position)?; if account.is_signer() && account.key == gate_signer { return Ok(()); } } } Err(ProgramError::Custom(NOT_PERMITTED)) } /// Gives the gate signer a place in a transaction. It has to sign for the instruction to be accepted at all. /// /// Accounts: gate signer (signer). fn permit(accounts: &[AccountView]) -> ProgramResult { match accounts.first() { Some(signer) if signer.is_signer() => Ok(()), _ => Err(ProgramError::MissingRequiredSignature), } } /// Sets the admin and the gate signer. The first call must be signed by the /// program's upgrade authority; later ones by the admin it named. /// /// Accounts: authority (signer, writable), config (writable), system program, program data (first call only). /// Data: admin (32) + gate signer (32). #[inline(never)] fn configure(program_id: &Address, accounts: &mut [AccountView], data: &[u8]) -> ProgramResult { if data.len() != 64 { return Err(ProgramError::InvalidInstructionData); } let [authority, config, _system_program, rest @ ..] = accounts else { return Err(ProgramError::NotEnoughAccountKeys); }; if !authority.is_signer() { return Err(ProgramError::MissingRequiredSignature); } let (address, bump) = Address::find_program_address(&[CONFIG_SEED], program_id); if config.address() != &address { return Err(ProgramError::InvalidSeeds); } if config.owned_by(program_id) { let admin = read_config(program_id, config)?.0; if authority.address() != &admin { return Err(ProgramError::Custom(NOT_ADMIN)); } } else { let Some(program_data) = rest.first() else { return Err(ProgramError::NotEnoughAccountKeys); }; if authority.address() != &upgrade_authority(program_id, program_data)? { return Err(ProgramError::Custom(NOT_ADMIN)); } let bump = [bump]; create(authority, config, CONFIG_LEN, program_id, &[Seed::from(CONFIG_SEED), Seed::from(&bump)])?; } let mut stored = config.try_borrow_mut()?; stored[0] = CONFIG_VERSION; stored[1..CONFIG_LEN].copy_from_slice(data); Ok(()) } /// Creates the account that tells Token-2022 which extra accounts the hook /// needs for one mint. Anyone may do this for any mint: the content is fixed. /// /// Accounts: payer (signer, writable), mint, extra-account-metas (writable), system program. #[inline(never)] fn init_mint(program_id: &Address, accounts: &mut [AccountView]) -> ProgramResult { let [payer, mint, metas, _system_program, ..] = accounts else { return Err(ProgramError::NotEnoughAccountKeys); }; let (address, bump) = Address::find_program_address(&[METAS_SEED, mint.address().as_array()], program_id); if metas.address() != &address { return Err(ProgramError::InvalidSeeds); } if metas.owned_by(program_id) { return Ok(()); } let bump = [bump]; let seeds = [Seed::from(METAS_SEED), Seed::from(mint.address().as_array()), Seed::from(&bump)]; create(payer, metas, METAS_LEN, program_id, &seeds)?; let config = Address::find_program_address(&[CONFIG_SEED], program_id).0; let mut stored = metas.try_borrow_mut()?; stored[..8].copy_from_slice(&EXECUTE); stored[8..12].copy_from_slice(&((4 + EXTRA_ACCOUNTS * META_LEN) as u32).to_le_bytes()); stored[12..16].copy_from_slice(&(EXTRA_ACCOUNTS as u32).to_le_bytes()); // Kind 0 is a fixed address; neither account signs or is written to. for (index, extra) in [config, INSTRUCTIONS_SYSVAR].iter().enumerate() { let start = 16 + index * META_LEN; stored[start] = 0; stored[start + 1..start + 33].copy_from_slice(extra.as_array()); stored[start + 33] = 0; stored[start + 34] = 0; } Ok(()) } /// (admin, gate signer). Only this program can own an account, and the config is the only one it makes this size. fn read_config(program_id: &Address, config: &AccountView) -> Result<(Address, Address), ProgramError> { if !config.owned_by(program_id) { return Err(ProgramError::InvalidAccountOwner); } let stored = config.try_borrow()?; if stored.len() != CONFIG_LEN || stored[0] != CONFIG_VERSION { return Err(ProgramError::InvalidAccountData); } let mut admin = [0u8; 32]; let mut gate_signer = [0u8; 32]; admin.copy_from_slice(&stored[1..33]); gate_signer.copy_from_slice(&stored[33..65]); Ok((Address::new_from_array(admin), Address::new_from_array(gate_signer))) } /// Who may upgrade this program, read from the loader's own record of it. fn upgrade_authority(program_id: &Address, program_data: &AccountView) -> Result
{ let expected = Address::find_program_address(&[program_id.as_array()], &UPGRADEABLE_LOADER).0; if program_data.address() != &expected || !program_data.owned_by(&UPGRADEABLE_LOADER) { return Err(ProgramError::InvalidAccountOwner); } let stored = program_data.try_borrow()?; // Layout: account kind (u32, 3 = program data), deploy slot (u64), has authority (u8), authority (32). if stored.len() < 45 || stored[..4] != [3, 0, 0, 0] || stored[12] != 1 { return Err(ProgramError::Custom(NOT_ADMIN)); } let mut authority = [0u8; 32]; authority.copy_from_slice(&stored[13..45]); Ok(Address::new_from_array(authority)) } /// Creates a program-owned account at a derived address. If someone sent /// lamports there first, a plain create would fail, so it is topped up, /// sized and assigned instead. fn create(payer: &AccountView, account: &AccountView, space: usize, owner: &Address, seeds: &[Seed]) -> ProgramResult { let signer = [Signer::from(seeds)]; let rent = Rent::get()?.try_minimum_balance(space)?; if account.lamports() == 0 { return CreateAccount { from: payer, to: account, lamports: rent, space: space as u64, owner }.invoke_signed(&signer); } let missing = rent.saturating_sub(account.lamports()); if missing > 0 { Transfer { from: payer, to: account, lamports: missing }.invoke()?; } Allocate { account, space: space as u64 }.invoke_signed(&signer)?; Assign { account, owner }.invoke_signed(&signer) }