Program Logic
Hinkal Protocol — Solana Program Overview
This page summarizes the on-chain Anchor program that powers Hinkal on Solana. The program is a single Anchor program (hinkal) responsible for Groth16 proof verification, commitment Merkle tree maintenance, nullifier tracking, access-token gating, and execution of arbitrary external instructions for private swaps.
State and logic live together in one program. Persistent data is split across PDAs (program-derived accounts), and the instructions in lib.rs operate on those PDAs, deriving them from a fixed original_deployer key and per-domain seeds.
Core Orchestration
hinkalprogram (lib.rs)Entry point for all user, relayer, and admin actions. Declares the program ID and registers every instruction handler (
initialize,proofless_deposit,transact,transfer,prepare_swap,swap, plus admin instructions).Each transaction-style instruction (
transact,transfer,swap) verifies a Groth16 proof, asserts Merkle root membership, validates nullifiers, inserts new commitments, and emits indexer events.
process_proof_and_state(proof_processing.rs)The shared core for every proof-bearing instruction. Performs a 10-step pipeline:
verify_proof(Groth16 over BN254 viagroth16-solana).Parse public signals into a
ParsedPublicSignalsview.Recompute
expected_hashed_calldata(recipient, signer, encrypted outputs, fees, instructions, remaining accounts) and compare with the in-proofcalldata_hash.Confirm the Merkle root referenced by the proof exists in the on-chain root window.
Validate amount-change ranges and
on_chain_creationarray length.Insert nullifiers (or reject if reused).
Insert new commitments into the Merkle tree and emit
NewCommitmentevents.Enforce that withdrawals only run with a whitelisted relayer (or zero fee).
Verify the stealth-address structure has non-zero randomization.
Verify each supplied mint matches the mint encoded in the proof.
State Layer (PDAs)
State is held in PDAs declared in hinkal_accounts.rs and types.rs and derived using the seeds in seed_constants.rs. All PDAs are seeded by original_deployer.key() so multiple deployments can co-exist.
StorageAccount-seeds = ["hinkal", original_deployer]. Holds the relayer whitelist (Vec<Pubkey>, max 10), theowner, andpending_owner(two-step ownership).Merkle(zero-copy,merkle.rs) -seeds = ["hinkal_merkle", original_deployer]. Append-only commitment tree with up to 200 levels and a sliding window of the last 100 root hashes (MAX_ROOT_NUMBER). Providesinsert,insert_many,get_root_hash,root_hash_exists, all using Poseidon.Merkle(access-token tree) -seeds = ["hinkal_merkle_access_token", original_deployer]. A second tree dedicated to access keys; access-token ZK proofs are checked against it during gated flows.Storage vault -
seeds = ["hinkal_vault", original_deployer]. ASystemAccountPDA that custodies all shielded SOL and is the authority for shielded SPL token ATAs.AccessTokenStorageAccount-seeds = ["hinkal_access_token", original_deployer]. Stores theaccess_token_owner_key(the only signer that can mint new access tokens).AccesskeyAccount-seeds = ["hinkal_access_keys", original_deployer, access_key]. One PDA per access key;is_addedprevents duplicate insertion.TokenLimitStorageAccount-seeds = ["hinkal_token_limit", original_deployer, mint](mint = 32 zero bytes for SOL). Per-token deposit/withdrawal threshold above which an access token is required.NullifierAccount-seeds = ["hinkal_nullifier", original_deployer, nullifier]. One PDA per nullifier withis_used: bool. Created withinit_if_neededand flipped totrueby the spending instruction, in the same transaction.SwapStagingAccount-seeds = ["hinkal_swap_staging", original_deployer, signer, id]. Written byprepare_swapwith the proof, public signals, encrypted outputs, on-chain encrypted output and CPI batch, then read and closed byswap. Needed because a swap's proof, outputs and router calldata do not fit in one transaction together with the route accounts.transactandtransfercarry the proof in their instruction data and need no staging.Swapper PDA -
seeds = ["hinkal_swapper", original_deployer, swapper_account_additional_seed]. A SystemAccount PDA used as the CPI signer for routed external swaps;swapper_account_additional_seedis bound into the proof to prevent cross-swap reuse.
All account types include a version: u8 field and is_latest_version() constraint, enforced via the declare_versioned! macro in versions.rs so old layouts are rejected after upgrades.
Logic & Execution Layer
Transact (deposit/withdraw) -
instructions/transact.rsplus sharedtransact_common.rs,perform_transact_funds.rs(SOL), andperform_transact_tokens.rs(SPL). Routes between SOL and SPL leg based on whethermintisSome, runsprocess_proof_and_state, then either deposits funds into the storage vault (positive amount change) or withdraws to the recipient + pays the relayer fee to the signer (negative amount change). Theforbid_depositflag rejects any non-negative net change. Dimensions:1×2×1or1×6×1.Transfer (shielded → shielded) -
instructions/transfer.rsplustransfer_common.rs. Same proof pipeline as transact, butforbid_deposit = true, recipient pinned to the system program, and the only on-chain fund movement is payingrelayer_feefrom the storage vault to the signer. Dimensions:1×2×2or1×6×2.Swap (shielded → external DEX → shielded) -
instructions/prepare_swap.rs,instructions/swap.rs,swap_common.rs,swap_utils.rs,perform_swap.rs, anddetermine_swap_mode.rs. After the proof pipeline:validate_swap_ataschecks that the supplied source/destination ATAs match the configured mints.determine_swap_modeclassifies the leg pair asTokenToToken,TokenToSol, orSolToToken.Funds move from the storage vault to the swapper PDA, which then signs CPI calls to the configured router using the CPI batch staged in
SwapStagingAccount. The instructions come from the off-chain quote (OKX for shielded swaps, which itself routes through Jupiter / Raydium / etc.).perform_swapmeasuresbalance_after - balance_beforeon the destination ATA (or swapper SOL balance) to compute the realized output.calculate_total_fee=relayer_fee + output * variable_rate / 10000. The fee is paid to the signer; the remainder forms a single output UTXO whose commitment is inserted on-chain (insert_onchain_commitment) and emitted viaemit_cpi!. Dimensions:2×2×1or2×6×1.
Proofless deposit -
instructions/proofless_deposit.rs(callsproofless_deposit_common.rs). Lets a user deposit SOL or an SPL token into the vault and have the program build the resulting commitments on-chain from 1..NStealthAddressStructures (no ZK proof). Below the per-token threshold (TokenLimitStorageAccount), no access token is required; otherwise a signature from the access-token owner is mandatory. EmitsBlockedUtxosCreatedwhencreate_blocked_utxos = true.
Policy / Validation
Relayer policy (
process_proof_and_statestep 8 +transfer_common/swap_common) - for any flow that pays a fee, the signer must be a member ofStorageAccount.whitelisted_relayers, otherwise the instruction reverts withRelayerNotWhitelisted.update_relayer_status(owner-only) maintains the list.Access tokens (
validate_access_token.rs,is_access_token_required.rs) - for amounts above the per-token limit, the proof must reference an access-key Merkle root from the access-token tree. New access keys are added throughadd_access_token, which requires theaccess_token_ownersigner; the owner key itself can be rotated viachange_access_token_owner_key.Token limits (
init_token_limit,update_token_limit) - owner-only, sets the threshold above which access tokens become mandatory for the (mint, deployer) pair.Calldata hash (
get_hashed_calldata.rs) - every proof commits to the recipient, signer, encrypted outputs, fees, CPI instructions, and remaining accounts via a Poseidon hash. The instruction handler recomputes this and rejects on mismatch (CalldataHashMismatch).Balance equation (
validate_balance_diff.rs) - after every fund movement, the actualbalance_after - balance_beforeon the storage vault (or its ATA) must equalamount_change + utxo_amount(or justutxo_amountwhen the commitment was created on-chain). Mismatches abort the instruction withBalanceDiffMismatch.Nullifier validation (
validate_nullifiers.rs,process_tokens::process_nullifiers, Anchorseedsconstraints) - instruction-supplied nullifiers must match the public signals; their PDAs must be derived from those exact bytes; each PDA must not already beis_used = true.Self-CPI guard (
perform_swap.rs) - every CPI target must be a different program; calling back into Hinkal is rejected withSelfCPIForbidden.Versioning (
versions.rs+declare_versioned!) - every PDA carries aversionbyte. Old versions are rejected by anis_latest_version()constraint, allowing forward migrations.Two-step ownership (
transfer_ownership+accept_ownership) - only the current owner can nominate apending_owner; the pending owner must accept before the transfer takes effect.
Events (for indexers)
Defined in hinkal_events.rs:
NewCommitment { commitment, index, encrypted_output, on_chain_data: [Bytes32; 8] }- emitted on every commitment insert.on_chain_datais non-zero for proofless / on-chain UTXO creation and lets indexers reconstruct the UTXO without an off-chain encrypted output.swapemits this viaemit_cpi!(event-CPI) so a router CPI that fills the log buffer cannot truncate it.Nullified { nullifier }- every successful nullifier spend.NewAccessKeyAdded { access_key, index, sender_address }.BlockedUtxosCreated { sender, mint, amounts }-proofless_depositonly (whencreate_blocked_utxos = true).RelayerStatusUpdated,TokenLimitUpdated,AccessTokenOwnerChanged,OwnershipTransferred,OwnershipAccepted.
Typical Flow (private swap)
Off-chain: client builds
CircomData, generates a Groth16 proof, encrypts new UTXO outputs, and prepares the CPI instruction list for the chosen router.Stage:
prepare_swapwrites the per-idSwapStagingAccount.Submit:
swapis called withdimensions,in_nullifiers,relayer_fee,variable_rate, and the swapper-additional-seed; nullifier accounts are created in this transaction.Verify:
process_proof_and_stateruns the 10-step pipeline (proof, calldata hash, root membership, nullifiers, commitments, relayer/access-token rules, mint binding).Move funds: the vault transfers input liquidity to the swapper PDA;
perform_swapinvokes the staged CPI batch againstremaining_accounts; output is measured via balance delta.Settle: relayer + variable fee are paid to the signer; the net output forms a UTXO whose commitment is inserted into the Merkle tree;
validate_*_balance_diffenforces the closing balance equation.Emit:
NewCommitment(and any swap-specific event) is published for the indexer.
transact and transfer follow the same shape in a single transaction, minus the staging and CPI steps.
Source Map
Program entry / instruction registration
lib.rs
Account / PDA layouts
hinkal_accounts.rs, types.rs
Seeds
seed_constants.rs
Merkle tree
merkle.rs
Groth16 verification
verify_proof.rs, verifying_key.rs, basic_solana_*_verification_key.rs
Proof pipeline
proof_processing.rs, process_tokens.rs, public_signals.rs, get_hashed_calldata.rs
Transact (SOL/SPL)
instructions/transact.rs, transact_common.rs, perform_transact_funds.rs, perform_transact_tokens.rs
Transfer
instructions/transfer.rs, transfer_common.rs
Swap
instructions/prepare_swap.rs, instructions/swap.rs, swap_common.rs, swap_utils.rs, perform_swap.rs, determine_swap_mode.rs, validate_swap_atas.rs
Proofless deposits
instructions/proofless_deposit.rs, proofless_deposit_common.rs, build_on_chain_utxo.rs
Swap staging
instructions/prepare_swap.rs, account_space.rs
Nullifiers
validate_nullifiers.rs, process_tokens.rs
Access tokens
instructions/add_access_token.rs, instructions/change_access_token_owner_key.rs, validate_access_token.rs, validate_access_token_owner.rs, is_access_token_required.rs
Admin
instructions/initialize.rs, transfer_ownership.rs, accept_ownership.rs, update_relayer_status.rs, init_token_limit.rs, update_token_limit.rs
Balance & ATA validation
validate_balance_diff.rs, validate_ata.rs, get_sol_balance.rs, get_token_balance.rs
Errors / events
error.rs, hinkal_events.rs
Last updated

