DOCS / QUICKSTART: PROGRAM

Your program. Your signing rules.

Your program defines the rules. PairKey evaluates them before two independent signers produce the signature.

When to use a program

Choose this source when authorization depends on application state or governance rather than one person approving directly. Common uses include organization treasuries, protocol vaults, customer-specific custody, automated strategies, payroll and cross-chain settlement.

The program ID, controller PDA and owner establish the stable authority. A named namespace separates purposes, and a numeric path selects a subaccount. The PDA contains no destination private key: it authorizes PairKey's two signers to use their shares for an exact request.

What runs where

The Solana program cannot call PairKey’s HTTP API, provision secret shares or synchronously receive a signature. It defines a stable authority PDA and checks whether an exact request is allowed. The frontend obtains the public namespace and derived key from hosted signers, asks the wallet to authenticate the exact request, submits a signing job, and retrieves the result. The application can then broadcast supported Solana, EVM, NEAR or Sui transactions through its own destination client.

StepWho calls whatWhat persists
1. AuthorityFrontend calls connect with a named namespace. The SDK verifies the program’s ["controller", owner] PDA and both namespace attestations.Public namespace metadata. No Solana registration transaction.
2. RulesOwner calls setPolicy. The safer default sends pairkey_policy/v2 with the exact namespace digest.Program-owned ["pairkey-policy", owner, namespace_digest] PDA. Shared v1 policy remains available explicitly.
3. KeyFrontend calls deriveKey. PairKey’s signers lazily derive or enroll the key; the program never receives a private share.Public key and certificate. Namespace, destination, and path select the same key deterministically.
4. Exact approvalsignMessage or signTransaction prepares and authenticates the request. Onchain mode sends pairkey_approve_commit/v1; offchain mode has each signer simulate pairkey_approve/v1.Onchain mode records an exact approval and consumes the example allowance. Offchain mode makes no approval write.
5. Signature and deliveryBoth signers independently check authority and sign. The frontend retrieves, verifies, assembles, and optionally broadcasts supported transaction bytes.A recoverable hosted job, signature, two receipts, and optional destination transaction status.

There is no pairkey_policy_commit instruction. pairkey_policy/v2 creates or edits namespace-scoped application rules; pairkey_policy/v1 remains available for an intentionally shared scope. pairkey_approve_commit/v1 consumes state and commits one exact approval. These are separate transactions at different points in the flow.

Try the example program

Use the deployment’s example program or enter a program built with the v2 template below. Each wallet controls its own ["controller", owner] authority PDA and policy account. No namespace registration transaction is needed.

Policy setup needs devnet SOL. Off-chain approval has no per-request transaction. On-chain approval also needs transaction fees and approval-account rent for each message. The hosted example selects on-chain approval so its code can remain upgradeable.

Choose a program and connect your wallet.

The policy permits the selected destination and path prefix, with up to 1,232 canonical payload bytes. Updating it replaces the previous scope and allowance. Off-chain mode ignores this counter.

Derived public key

Your key will appear here.

Signature

Your signature will appear here.

Connect your application

Start with the runnable browser example on GitHub. The released package exposes the unified client at @pairkey/sdk and the controller-specific helper at @pairkey/sdk/program. Install @pairkey/sdk and @solana/web3.js.

import * as web3 from '@solana/web3.js';
import {ProgramClient} from '@pairkey/sdk/program';

const program = new ProgramClient({
  web3, wallet: window.phantom.solana,
  programId: 'YOUR_DEPLOYED_EXAMPLE_CONTROLLER_ID',
  mode: 'Onchain', policyScope: 'namespace', storage: localStorage,
});
await program.connect({namespace:'org/acme/treasury'});
// Explicit owner transaction when creating or changing rules:
await program.setPolicy({chain:'solana',pathPrefix:[0],remainingApprovals:5});
const key = await program.deriveKey({chain:'solana',path:[0]});
const signed = await program.signMessage({
  chain:'solana',path:[0],message:'Approved by my program.'
});
console.log(key.public_key_hex, signed.signatureHex, signed.jobId);
// Download signed.transcript as JSON for independent verification.
// After a reload, read the same job without another wallet prompt or commit:
const recovered = await program.recover(signed.jobId);
// Optional Solana transaction: verify this message signature on chain.
const proof = await program.verifyOnSolana(recovered);

setPolicy is separate from signing and advances the selected policy revision once per deliberate edit. Use the unified PairKeyClient when you want signTransaction, signAndSend, and recoverAndSend with this same program authority. The proof transaction above only verifies a returned message signature on Solana. The browser and service checks are not full independent verification of both signer receipts. Save the transcript for the Rust verifier and pin trusted signer identities.

See the lower-level signing sequence

The released @pairkey/sdk package exports ProgramClient and PairKeyClient, not the low-level PairKey class. Use the package example above for an application. For a custom integration, read the low-level implementation and recovery flow together.

  1. Resolve the program source and namespace, then derive the destination key.
  2. Prepare one exact request and save its public recovery record before authorization.
  3. Authenticate the caller; in on-chain mode, commit that same prepared request through the program.
  4. Submit the job, verify the result, and recover the original job ID after an interruption.

Keep the prepared request unchanged between commit and submit. Preparing again can change its expiry and digest. Recovery reads existing evidence; an unknown or uncertain job needs investigation before another allowance is consumed.

How the program authorizes signing

The example has three instructions. The policy update requires the owner’s transaction signature. Read-only approval authenticates the signer-attested caller and exact request, then returns a decision bound to that input. On-chain approval authenticates the wallet, checks the same rules, decrements an allowance and approves the exact request through gateway CPI in one atomic Solana transaction.

pairkey_policy/v1           // create or edit this owner's rules
pairkey_approve/v1          // evaluate rules; return an input-bound decision
pairkey_approve_commit/v1   // consume allowance + approve through PDA CPI

These shortened excerpts follow the actual example program and show its decision points. They are reading aids, not standalone handlers. The complete source also validates account counts and PDAs, allocates the policy account, checks the gateway, and handles errors.

1. Define what the program permits

AppPolicy::allows is the application rule. This example accepts only its owner as caller, the configured destination and path prefix, and a nonempty payload within the size limit. Replace or extend this rule for your application.

fn allows(&self, caller: [u8; 32], account: &AccountPath, payload: &[u8]) -> bool {
    self.enabled
        && self.owner == caller
        && account.destination == self.destination
        && account.path.starts_with(&self.path_prefix)
        && !payload.is_empty()
        && payload.len() <= self.max_payload_bytes as usize
}

2. Store or update the rules

The owner signs the policy update. pairkey_policy/v2 can derive ["pairkey-policy", owner, namespace_digest]; pairkey_policy/v1 retains the compatible shared ["pairkey-policy", owner] account. The first write to either account uses revision 1 and every edit increments that account by exactly one. The full handler on GitHub performs account creation, rent funding, PDA selection, and serialization.

let p = AppPolicy::try_from_slice(bytes).map_err(|_| bad())?;
p.validate()?;
let [owner, target, system] = accounts else { return Err(bad()) };
let (pda, _bump) = policy_address(program, owner.key);
if !owner.is_signer || p.owner != owner.key.to_bytes() || *target.key != pda {
    return Err(bad());
}
if target.owner == program {
    let old = policy(program, target)?;
    if old.revision.checked_add(1) != Some(p.revision) { return Err(bad()); }
} else if p.revision != 1 {
    return Err(bad());
}
// Full handler creates or resizes the PDA, then writes the encoded policy.

3. Authorize one exact request

For immutable, read-only rules, each signer simulates pairkey_approve/v1. The program authenticates that signer’s input, checks the authority and application rule, then returns a decision bound to the exact input digest. No allowance changes.

let input = Input::try_from_slice(bytes).map_err(|_| bad())?;
let p = policy(program, &accounts[2])?;
pair_registry::program_approval::authenticate_input(
    accounts, &input,
    &pair_registry::set_address(&pair_registry::id(), &p.enclave_set).0,
)?;
let allowed = input.authority
    == authority(program, &Pubkey::new_from_array(p.owner)).0.to_bytes()
    && !p.require_commit
    && p.allows(input.caller, &input.account, &input.payload);
set_return_data(&borsh::to_vec(&Output {
    input_digest: input.digest(), allowed,
}).map_err(|_| bad())?);

For state-changing rules, the wallet instead sends pairkey_approve_commit/v1. The program authenticates the caller and source, checks the same rule, decrements the example allowance, then signs the gateway’s ApproveProgram CPI with its authority PDA. The allowance decrement and exact approval succeed or fail together.

let call = CommitCall::try_from_slice(bytes).map_err(|_| bad())?;
let source = call.validate(Clock::get()?.unix_timestamp).map_err(|_| bad())?;
// Full handler verifies owner signature, source, authority PDA, gateway,
// namespace, enclave set and ordered application accounts before this point.
let mut p = policy(program, policy_info, &call.namespace.digest())?;
if !p.allows(owner.key.to_bytes(), &call.request.commit.account, &call.payload)
    || p.remaining_approvals == 0
{
    return Err(bad());
}
p.remaining_approvals -= 1;
policy_info.try_borrow_mut_data()?.copy_from_slice(&borsh::to_vec(&p).map_err(|_| bad())?);
let ix = instruction(*registry.key, gateway_accounts, RegistryInstruction::ApproveProgram {
    approval: call.approval(),
});
invoke_signed(&ix, gateway_account_infos,
    &[&[AUTHORITY_SEED, owner.key.as_ref(), &[bump]]])?;

gateway_accounts and gateway_account_infos above stand for the exact account lists in the complete handler. The excerpt is for reading the flow; use the complete source on GitHub when implementing it.

View the complete application policy implementation
//! Example application rules: designated caller, destination/path scope and an optional
//! persistent approval counter. Developers can replace these rules with their own logic.
use super::*;
use pairkey_types::program_approval::{CommitCall, Input, Output, APPROVE_PREFIX, COMMIT_PREFIX};
use solana_program::{program::set_return_data, rent::Rent, sysvar::Sysvar};
pub const POLICY_PREFIX: &[u8] = b"pairkey_policy/v1\0";
pub const SCOPED_POLICY_PREFIX: &[u8] = b"pairkey_policy/v2\0";
pub const POLICY_SEED: &[u8] = b"pairkey-policy";
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize)]
pub struct AppPolicy {
    pub owner: [u8; 32],
    pub enclave_set: [u8; 32],
    pub revision: u64,
    pub enabled: bool,
    pub destination: [u8; 32],
    pub path_prefix: Vec<u32>,
    pub max_payload_bytes: u16,
    pub require_commit: bool,
    pub remaining_approvals: u64,
}
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize)]
pub struct ScopedPolicyUpdate {
    pub namespace_scope: Option<[u8; 32]>,
    pub policy: AppPolicy,
}
pub fn policy_address(program: &Pubkey, owner: &Pubkey) -> (Pubkey, u8) {
    Pubkey::find_program_address(&[POLICY_SEED, owner.as_ref()], program)
}
pub fn scoped_policy_address(
    program: &Pubkey,
    owner: &Pubkey,
    namespace_digest: &[u8; 32],
) -> (Pubkey, u8) {
    Pubkey::find_program_address(&[POLICY_SEED, owner.as_ref(), namespace_digest], program)
}
fn selected_policy_address(
    program: &Pubkey,
    owner: &Pubkey,
    scope: Option<&[u8; 32]>,
) -> (Pubkey, u8) {
    scope.map_or_else(
        || policy_address(program, owner),
        |digest| scoped_policy_address(program, owner, digest),
    )
}
fn bad() -> ProgramError {
    ProgramError::InvalidArgument
}
fn policy(
    program: &Pubkey,
    info: &AccountInfo,
    namespace_digest: &[u8; 32],
) -> Result<AppPolicy, ProgramError> {
    let p: AppPolicy = pair_registry::read(info, program)?;
    let owner = Pubkey::new_from_array(p.owner);
    if policy_address(program, &owner).0 != *info.key
        && scoped_policy_address(program, &owner, namespace_digest).0 != *info.key
    {
        return Err(bad());
    }
    Ok(p)
}
impl AppPolicy {
    fn validate(&self) -> ProgramResult {
        if self.owner == [0; 32]
            || self.revision == 0
            || self.path_prefix.len() > pairkey_types::MAX_PATH
            || self.max_payload_bytes == 0
            || self.max_payload_bytes as usize > pairkey_types::MAX_MESSAGE
        {
            return Err(bad());
        }
        Ok(())
    }
    fn allows(
        &self,
        caller: [u8; 32],
        account: &pairkey_types::AccountPath,
        payload: &[u8],
    ) -> bool {
        self.enabled
            && self.owner == caller
            && account.destination == self.destination
            && account.path.starts_with(&self.path_prefix)
            && !payload.is_empty()
            && payload.len() <= self.max_payload_bytes as usize
    }
}
pub fn process(program: &Pubkey, accounts: &[AccountInfo], data: &[u8]) -> ProgramResult {
    if let Some(bytes) = data.strip_prefix(SCOPED_POLICY_PREFIX) {
        let update = ScopedPolicyUpdate::try_from_slice(bytes).map_err(|_| bad())?;
        let scope = update.namespace_scope.ok_or_else(bad)?;
        return set_policy(program, accounts, update.policy, Some(scope));
    }
    if let Some(bytes) = data.strip_prefix(POLICY_PREFIX) {
        let policy = AppPolicy::try_from_slice(bytes).map_err(|_| bad())?;
        return set_policy(program, accounts, policy, None);
    }
    if let Some(bytes) = data.strip_prefix(APPROVE_PREFIX) {
        let input = Input::try_from_slice(bytes).map_err(|_| bad())?;
        if accounts.len() != 3 {
            return Err(bad());
        }
        let p = policy(program, &accounts[2], &input.namespace_digest)?;
        pair_registry::program_approval::authenticate_input(
            accounts,
            &input,
            &pair_registry::set_address(&pair_registry::id(), &p.enclave_set).0,
        )?;
        let allowed = input.authority
            == authority(program, &Pubkey::new_from_array(p.owner))
                .0
                .to_bytes()
            && !p.require_commit
            && p.allows(input.caller, &input.account, &input.payload);
        set_return_data(
            &borsh::to_vec(&Output {
                input_digest: input.digest(),
                allowed,
            })
            .map_err(|_| bad())?,
        );
        return Ok(());
    }
    let bytes = data.strip_prefix(COMMIT_PREFIX).ok_or_else(bad)?;
    let call = CommitCall::try_from_slice(bytes).map_err(|_| bad())?;
    let source = call
        .validate(solana_program::clock::Clock::get()?.unix_timestamp)
        .map_err(|_| bad())?;
    if accounts.len() != 8 {
        return Err(bad());
    }
    let [owner, authority_info, policy_info, registry, set, namespace, target, system] = accounts
    else {
        return Err(bad());
    };
    if !owner.is_signer || *registry.key != pair_registry::id() || !registry.executable {
        return Err(ProgramError::MissingRequiredSignature);
    }
    let (pda, bump) = authority(program, owner.key);
    if source.program != program.to_bytes()
        || source.authority != pda.to_bytes()
        || pair_registry::program_approval::validate_source(source)? != pda
        || *authority_info.key != pda
        || source.accounts != vec![policy_info.key.to_bytes()]
    {
        return Err(bad());
    }
    let mut p = policy(program, policy_info, &call.namespace.digest())?;
    if p.enclave_set != call.namespace.enclave_set {
        return Err(bad());
    }
    if !p.allows(
        owner.key.to_bytes(),
        &call.request.commit.account,
        &call.payload,
    ) || p.remaining_approvals == 0
    {
        return Err(bad());
    }
    p.remaining_approvals -= 1;
    let bytes = borsh::to_vec(&p).map_err(|_| bad())?;
    policy_info.try_borrow_mut_data()?.copy_from_slice(&bytes);
    let ix = instruction(
        *registry.key,
        vec![
            AccountMeta::new(*owner.key, true),
            AccountMeta::new_readonly(pda, true),
            AccountMeta::new_readonly(*set.key, false),
            AccountMeta::new_readonly(*namespace.key, false),
            AccountMeta::new(*target.key, false),
            AccountMeta::new_readonly(*system.key, false),
        ],
        RegistryInstruction::ApproveProgram {
            approval: call.approval(),
        },
    );
    invoke_signed(
        &ix,
        &[
            owner.clone(),
            authority_info.clone(),
            set.clone(),
            namespace.clone(),
            target.clone(),
            system.clone(),
            registry.clone(),
        ],
        &[&[AUTHORITY_SEED, owner.key.as_ref(), &[bump]]],
    )
}
fn set_policy(
    program: &Pubkey,
    accounts: &[AccountInfo],
    p: AppPolicy,
    namespace_scope: Option<[u8; 32]>,
) -> ProgramResult {
    p.validate()?;
    if namespace_scope == Some([0; 32]) {
        return Err(bad());
    }
    let [owner, target, system] = accounts else {
        return Err(bad());
    };
    let (pda, bump) = selected_policy_address(program, owner.key, namespace_scope.as_ref());
    if !owner.is_signer
        || p.owner != owner.key.to_bytes()
        || *target.key != pda
        || *system.key != solana_program::system_program::id()
    {
        return Err(bad());
    }
    let encoded = borsh::to_vec(&p).map_err(|_| bad())?;
    let rent = Rent::get()?.minimum_balance(encoded.len());
    if target.owner == program {
        let old: AppPolicy = pair_registry::read(target, program)?;
        if old.owner != p.owner || old.revision.checked_add(1) != Some(p.revision) {
            return Err(bad());
        }
        if target.lamports() < rent {
            solana_program::program::invoke(
                &solana_program::system_instruction::transfer(
                    owner.key,
                    target.key,
                    rent - target.lamports(),
                ),
                &[owner.clone(), target.clone(), system.clone()],
            )?;
        }
        target.realloc(encoded.len(), false)?;
    } else {
        if p.revision != 1
            || target.owner != &solana_program::system_program::id()
            || !target.data_is_empty()
        {
            return Err(bad());
        }
        let bump_seed = [bump];
        let mut seeds: Vec<&[u8]> = vec![POLICY_SEED, owner.key.as_ref()];
        if let Some(scope) = namespace_scope.as_ref() {
            seeds.push(scope);
        }
        seeds.push(&bump_seed);
        if target.lamports() == 0 {
            invoke_signed(
                &solana_program::system_instruction::create_account(
                    owner.key,
                    target.key,
                    rent,
                    encoded.len() as u64,
                    program,
                ),
                &[owner.clone(), target.clone(), system.clone()],
                &[&seeds],
            )?;
        } else {
            if target.lamports() < rent {
                solana_program::program::invoke(
                    &solana_program::system_instruction::transfer(
                        owner.key,
                        target.key,
                        rent - target.lamports(),
                    ),
                    &[owner.clone(), target.clone(), system.clone()],
                )?;
            }
            invoke_signed(
                &solana_program::system_instruction::allocate(target.key, encoded.len() as u64),
                &[target.clone(), system.clone()],
                &[&seeds],
            )?;
            invoke_signed(
                &solana_program::system_instruction::assign(target.key, program),
                &[target.clone(), system.clone()],
                &[&seeds],
            )?;
        }
    }
    target.try_borrow_mut_data()?.copy_from_slice(&encoded);
    Ok(())
}

Deploy your application logic

Browse the program template on GitHub and its policy implementation. Clone the repository and edit programs/example-controller/src/approval.rs. You deploy only your application program; PairKey runs the signers and gateway.

git clone https://github.com/yinscode/pairkey.git
cd pairkey
# Copy registry from your hosted /api/v2/config and pin it at build time.
PAIRKEY_REGISTRY_ID=YOUR_HOSTED_GATEWAY cargo build-sbf \
  --manifest-path programs/example-controller/Cargo.toml -- --locked
solana program deploy --url devnet --keypair YOUR_DEVNET_WALLET.json \
  target/deploy/pairkey_hosted_controller_example.so

Start with on-chain approval while developing an upgradeable program. Off-chain evaluation currently requires immutable deployed code. Removing upgrade authority is irreversible: test and review your program first. Standard RPC cannot simulate code stored only on your server.

Integrate another program

The example helpers use the template’s PDA seeds, accounts and ABI. For another program, supply an explicit Program identity containing its program ID, authority PDA and seeds, application accounts, approval mode and pinned code hash for off-chain evaluation. Implement the typed pairkey_approve ABI or your own instruction that invokes the gateway’s ApproveProgram through invoke_signed. The generic path must validate your program’s own exact operation; the example helper cannot wrap arbitrary programs.

Both signers independently verify the caller proof. Each signer authenticates its own simulation context; an unsigned simulated transaction’s signer flags are not accepted as proof of a wallet signature. See Solana program integration for the ABI and trust model.

Choose policy scope and approval mode

Use pairkey_approve for read-only rules such as destinations, paths, membership, or current application state. Both signers run the evaluation independently. Use pairkey_approve_commit for one-time allowances, cumulative budgets, and nonce consumption. A later signing or delivery failure does not refund committed state automatically.

Choose policyScope: 'namespace' when named namespaces need independent rules and revisions. Choose 'shared' only when every namespace for this program owner should intentionally use the same policy account. Standard PairKey rules are also namespace-specific and apply in addition. Policy updates are explicit owner transactions.

Verify and recover

The Verify button asks the service to verify the displayed message and signature. The browser also checks exact approval context and Ed25519 signatures locally. Use the offline Rust verifier for independent verification of all signature suites, key certificates and both signer receipts; service verification alone does not provide that independence.

// Save this public transcript for the offline Rust verifier.
// Check signer identities against a trusted deployment configuration.
const transcript = { request: prepared.signing_request, approval: prepared.request,
  key, result, identities: namespace.config.signer_identities };
// cargo run -p pairkey-sdk --example verify_hosted -- transcript.json

The client saves the public prepared request, key, deployment and deterministic job ID before submission. Keep that recovery record; it contains no wallet signature, JWT or passkey assertion, but it does contain your message. “Recover last job” only retrieves the original attempt. It never asks for another approval, submits another job or consumes another allowance. If the original submission never reached the service, recovery reports an unknown job. An uncertain outcome is not proof that no signature exists.

How addresses are scoped

The program authority and namespace label scope the namespace. Labels such as org/acme/treasury map deterministically to the existing 32-byte namespace ID. Destination, signature scheme and numeric path select keys inside it. Policy edits and approval mode changes preserve the authority; changing the label selects a different key family.

The SDK exposes Solana, restricted EVM legacy-transfer, and NEAR transaction adapters. Zcash currently exposes a message-signing public key. SDK 0.2.1 has a restricted testnet Taproot PSBT client adapter; the public service still offers message signing only.

Compare with NEAR Chain Signatures

NEAR’s Chain Signatures flow derives a foreign address from a NEAR account, derivation path and MPC public key. A NEAR account or contract calls the MPC contract’s sign method; the contract waits for the MPC service and returns a signature, which the client assembles into and broadcasts as a destination transaction. Its getting-started guide shows derive → build transaction → request signature → relay.

QuestionPairKey hosted v2NEAR Chain Signatures
Who controls the key?A Solana account or program authority PDA, plus exact caller proof and current rules.A NEAR account or contract, identified by the account calling the MPC contract.
How do I get an address?Call connect, then key({chain,path}). Named namespace plus numeric path provide app-friendly and deterministic scopes.Derive from the NEAR account ID, string path and MPC public key.
How does the program request signing?It authorizes an exact request through read-only evaluation or a finalized gateway CPI. The frontend submits the later HTTP signing job.The NEAR contract calls the MPC sign method from an onchain transaction and awaits its result.
Where is the signature returned?From the recoverable hosted job to the client, outside Solana CPI.Through the NEAR contract call or promise result after MPC signing.
Who sends it to the destination?signAndSend, your client, or a relayer using an application-supplied destination RPC.Your client or relayer after destination-specific assembly.

PairKey now supports Solana, restricted EVM legacy-transfer, NEAR and Sui transaction signing. SDK 0.2.1 includes a restricted Bitcoin Taproot PSBT client adapter, pending service support. Zcash Ironwood PCZT signing is a testnet library alpha without a hosted flow or ZIP 2005 recovery guarantee. NEAR’s contract-return pattern still cannot be copied directly to Solana because this integration authorizes on Solana and returns the later signer result through a hosted job.