ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all \u003cpre\u003e\u003ccode\u003e blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks"); } } catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); } })(); (function(){ try { var __m = "github.com"; var __re = new RegExp('^' + "github\\.com" + '
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length \u003e 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

ResQ Programs

CILicense: Apache-2.0

ResQ Programs is the decentralized coordination layer for autonomous aerospace and delivery operations built on Solana.

Overview

ResQ Programs provide the trust-minimized substrate for physical automation. By offloading rule enforcement to the Solana blockchain, the ResQ ecosystem ensures that air traffic protocols and delivery missions are immutable, transparent, and verifiable.

Key Components

  • resq-airspace: Governs physical airspace access. It manages zone registration, access policies (Open, Permit, Deny, Auction), and cryptographic permit issuance.
  • resq-delivery: Manages the mission-critical state of autonomous delivery vehicles, including immutable proof-of-delivery logging and coordinate validation.

Features

  • Proof-of-Permit: Cryptographically enforce that only authorized drones operate in restricted airspace.
  • Autonomous Lifecycle: Atomic state transitions for delivery missions.
  • Policy-as-Code: Airspace policies (altitude, geofencing, proximity) are enforced by on-chain logic.
  • Auditable History: Every crossing and delivery is recorded on-chain for regulatory compliance.

Architecture

The system utilizes Program-Derived Addresses (PDAs) for state management. Permissions are granted via PDA-based Permit accounts, which are checked by the resq-airspace program before processing crossing events.

C4Context
title System Context Diagram
Person(operator, "Authority/Operator")
System_Boundary(solana, "Solana Network") {
System(airspace, "resq-airspace", "Zone & Permit Logic")
System(delivery, "resq-delivery", "Mission & Proof Logic")
System_Ext(state, "Solana State Accounts", "PDAs & Account Data")
}
Rel(operator, airspace, "Initializes Property/Grants Permit")
Rel(operator, delivery, "Records Delivery Mission")
Rel(airspace, state, "Writes AirspaceAccount/Permit")
Rel(delivery, state, "Writes DeliveryRecord")
Rel(delivery, airspace, "Verifies Permit via CPI")
Loading

Installation

Prerequisites

  • Rust: stable (via rustup)
  • Solana CLI: 2.1.0 (ensure you have this specific version by running solana-install-toolchain --version 2.1.0 if needed)
  • Anchor CLI: 0.30.1 (managed via avm, required for SBF builds and deploys)

Environment Setup

This project uses Nix to manage its development environment, ensuring consistent tooling across all developers.

  1. Install Nix: If you don't have Nix installed, follow the instructions at nixos.org/download.html. This script will attempt to install Nix if it's not found.
  2. Enter the Dev Shell: Navigate to the project root and run:
    nix develop
    This command will download and set up all necessary dependencies, including Rust, Node.js, Bun, Solana CLI, and the specified Anchor version.

Building the Programs

Once your environment is set up (either manually or via nix develop), build the programs:

# Clone the repository
git clone https://github.com/resq-software/programs.git
cd programs
# Bootstrap environment (installs dependencies/hooks)
./bootstrap.sh
# Build programs
anchor build

Quick Start

Run the default repository validation workflow:

# Build the workspace, compile integration targets, and run library tests
bash ./scripts/test.sh

Usage

Registering Airspace

To initialize a restricted zone, an owner must provide a unique 32-byte identifier and define altitude bounds.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";// Assuming types are generatedconstprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constwallet=anchor.Wallet.local();// Get local wallet from Anchor configurationconstpropertyIdBytes=[...Buffer.from("zone-nyc-01").padEnd(32,'\0')];constminAltitude=10;// meters AGLconstmaxAltitude=150;// meters AGLconstpolygonVertices=[[0,0];8];// Example polygon, typically derived from geojsonconstvertexCount=1;// Number of valid verticesconstaccessPolicy={permit: {}};// Or { open: {}}, { deny: {}}, { auction: {}}constcrossingFee=1000;// Lamportsconsttreasury=newanchor.web3.Keypair().publicKey;// Address to receive feesconsttx=awaitprogram.methods.initializeProperty(propertyIdBytes,newanchor.BN(minAltitude),newanchor.BN(maxAltitude),polygonVertices,vertexCount,accessPolicy,newanchor.BN(crossingFee),treasury).accounts({owner: wallet.publicKey}).rpc();console.log("Airspace property initialized:",tx);

Granting a Permit

An owner can grant a permit to a specific drone PDA for a defined period.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqAirspace}from"../target/types/resq_airspace";constprogram=anchor.workspace.ResqAirspaceasProgram<ResqAirspace>;constownerWallet=anchor.Wallet.local();constairspacePda=newanchor.web3.PublicKey("...");// Address of the AirspaceAccountconstdronePda=newanchor.web3.PublicKey("...");// PDA of the droneconstexpiresAt=Math.floor(Date.now()/1000)+3600;// Permit expires in 1 hour (Unix timestamp)consttx=awaitprogram.methods.grantPermit(dronePda,newanchor.BN(expiresAt)).accounts({owner: ownerWallet.publicKey,airspace: airspacePda,// The permit PDA will be derived by Anchor}).rpc();console.log("Permit granted:",tx);

Recording a Delivery

Finalize a mission by logging the proof-of-delivery CID and GPS coordinates.

import*asanchorfrom"@coral-xyz/anchor";import{Program}from"@coral-xyz/anchor";import{ResqDelivery}from"../target/types/resq_delivery";// Assuming types are generatedconstprogram=anchor.workspace.ResqDeliveryasProgram<ResqDelivery>;constdroneWallet=anchor.Wallet.local();// Assuming this is the drone's authority keypairconstdeliveryTargetAirspacePda=newanchor.web3.PublicKey("...");// Target airspace accountconstipfsCid="QmResQTestCID1234567890abcdefghijklmnopqrstuvwxyz";// IPFS CID of proofconstlatitude=407128000;// 40.7128000 * 1e7constlongitude=-740060000;// -74.0060000 * 1e7constaltitude=50;// metersconstdeliveredTimestamp=Math.floor(Date.now()/1000);// Unix timestamp// Convert CID to byte array (must be 64 bytes, null-padded)constcidBytes=newUint8Array(64);Buffer.from(ipfsCid).copy(cidBytes);consttx=awaitprogram.methods.recordDelivery(cidBytes,newanchor.BN(latitude),newanchor.BN(longitude),newanchor.BN(altitude),newanchor.BN(deliveredTimestamp)).accounts({drone: droneWallet.publicKey,airspace: deliveryTargetAirspacePda,// The delivery_record PDA will be derived by Anchor}).rpc();console.log("Delivery recorded:",tx);

Configuration

Configuration for local development and deployments is managed in Anchor.toml.

  • [programs.localnet] / [programs.devnet]: Defines custom Program IDs for each cluster. Ensure these match the declare_id!("...") macro in your Rust code.
  • [provider]: Configures the default cluster URL and wallet keypair for Anchor commands.
  • Environment Overrides:
    • SOLANA_VERSION: Ensure the solana-cli version matches dependencies.
    • ANCHOR_VERSION: Managed by avm (via Nix).

API Reference

resq-airspace Program

  • initialize_property: Creates a new AirspaceAccount for a specific property, defining its geographic bounds, altitude restrictions, and access policy.
    • Arguments: property_id, min_alt_m, max_alt_m, poly, vertex_count, policy, fee_lamports, treasury.
    • Accounts: owner (mut), airspace (init), system_program.
  • update_policy: Modifies the AccessPolicy and fee_lamports of an existing AirspaceAccount.
    • Arguments: policy, fee_lamports.
    • Accounts: owner (mut), airspace (mut).
  • grant_permit: Issues a Permit PDA for a specific drone, granting it access under certain airspace policies.
    • Arguments: drone_pda, expires_at.
    • Accounts: owner (mut), airspace, permit (init), system_program.
  • record_crossing: Logs a drone's passage through an airspace. If the policy requires a permit, it verifies the Permit PDA. Collects crossing fees if configured.
    • Arguments: lat, lon, alt_m, crossed_at.
    • Accounts: drone (mut), airspace, permit (optional, required for Permit policy), treasury (mut), system_program.

resq-delivery Program

  • record_delivery: Creates an immutable DeliveryRecord PDA. This serves as proof-of-delivery, storing an IPFS CID of evidence and delivery coordinates.
    • Arguments: ipfs_cid, lat, lon, alt_m, delivered_at.
    • Accounts: drone (mut), airspace (account info), delivery_record (init), system_program.

Configuration

Configuration is primarily handled via Anchor.toml and environment variables.

  • Anchor.toml: Specifies program IDs for different clusters (localnet, devnet), default provider settings (cluster URL, wallet), and script commands.
  • Environment Variables:
    • SOLANA_CLI_VERSION: Not directly used, but bootstrap.sh and flake.nix pin specific versions.
    • ANCHOR_VERSION: Managed by avm for cross-version compatibility.

Development

Error Handling

Errors are defined using Anchor's #[error_code] enum within each program's error.rs file.

  • Constraint Violations: Anchor macros (has_one, constraint, seeds) automatically return standard Anchor errors (e.g., AccountNotFound, ConstraintViolation) if validation fails.
  • Custom Logic: Use the require! and require_keys_eq! macros to enforce business logic rules and return descriptive, actionable errors to the client.

Cross-Program Interaction (CPI)

Interactions between resq-airspace and resq-delivery are primarily through Cross-Program Invocations (CPI) or by simply referencing account addresses.

  • The resq-delivery program reads the airspace_pda to associate a delivery with a property, but it does not directly invoke resq-airspace instructions. Instead, off-chain logic or a separate "aggregator" program would typically coordinate these calls.
  • The resq-airspace program's record_crossing instruction checks the drone PDA and its associated Permit account. This ensures that while resq-delivery logs the mission, resq-airspace enforces access rules independently.

.claude AI-Assisted Development Workflow

This repository integrates with the .claude AI tooling for enhanced development. The .claude/ directory mirrors the structure of .github/ and contains AI agents, commands, rules, and skills.

  • Agents (.claude/agents/): Define AI personas tailored to specific development roles (e.g., anchor-engineer, solana-architect). These agents provide context-aware assistance based on the project's codebase and Solana/Anchor best practices.
  • Commands (.claude/commands/): Define AI-driven commands for common development tasks, such as audit, build, deploy, and test. These commands can trigger specific AI analyses or actions.
  • Rules (.claude/rules/): Contain security and testing guidelines that the AI should adhere to. The security.md and testing.md files outline critical principles for on-chain development.
  • Skills (.claude/skills/): Provide specialized AI capabilities, such as feynman-auditor for deep logic analysis and state-inconsistency-auditor for identifying state synchronization issues.

When the AI is invoked (e.g., through an integrated chat interface or specific command execution), it leverages these configurations to provide relevant insights, code suggestions, or perform analyses aligned with the project's specific needs and architectural patterns.

Security Assumptions and Threat Model

  • Core Assumption: Solana's network security and consensus mechanisms are robust. Program logic is the primary attack surface.
  • Key Threats:
    • Logic Flaws: Bugs in instruction handlers leading to incorrect state transitions, unauthorized access, or financial exploits. This is addressed by rigorous testing, secure coding practices, and AI-assisted auditing.
    • Account Exploitation: Issues with PDA derivation, incorrect account constraints, or missing PDA bump seed validation. Addressed by strict Anchor usage and explicit seed checks.
    • Cross-Program Interaction Misuse: Improper validation of CPIs, trusting external program states implicitly, or race conditions between programs. Addressed by unidirectional validation where possible and explicit cross-program checks (e.g., resq-airspace verifying Permit accounts).
    • Economic Exploits: Manipulation of fees, race conditions around permit issuance/expiry, or exploitation of policy parameters. Addressed by well-defined fee structures and clear expiry logic.
    • Client-Side Vulnerabilities: Malicious actors manipulating transaction construction or submitting outdated state. Mitigated by immutability on-chain and robust off-chain client validation.
  • Mitigation Strategies:
    • Formal Verification (Future): Exploring tools for formal verification of critical smart contract logic.
    • Economic Audits: Specific focus on incentive alignment and potential economic attack vectors.
    • Access Control: Strict adherence to owner-only mutations, PDA authority checks, and role-based permissions.

Development

Repository Validation

The default project gate is bash ./scripts/test.sh. It intentionally stays on the host toolchain and verifies:

  • Workspace builds succeed.
  • Integration targets still compile.
  • Library tests remain green.

Testing

Rust integration coverage currently lives under the crate-local tests/ directories, including:

  • resq-airspace/tests/integration.rs
  • resq-delivery/tests/integration.rs

The default validation workflow compiles those targets in CI, but does not execute the current runtime harness. Full validator-backed or SBF-backed execution should be treated as a separate, explicitly maintained harness.

Comprehensive tests should still include:

  • Happy-path scenarios for all instructions.
  • Error condition tests for each #[error_code].
  • Edge case testing for values, bounds, and state transitions.
  • Concurrency and race condition simulation where applicable (though Solana's transaction model simplifies this compared to traditional multi-threaded systems).

Contributing

We follow the Conventional Commits specification for commit messages.

  1. Feature Branch: Create branches using prefixes like feat/ or fix/ (e.g., feat/add-new-policy-type).
  2. Code Quality: Ensure all code passes cargo fmt --all and cargo clippy -- --D warnings.
  3. Security: Run cargo audit and adhere to the security rules outlined in .github/rules/security.md.
  4. Testing: All new functionality must be accompanied by comprehensive unit and integration tests.
  5. Pull Request: Submit a Pull Request detailing the changes, referencing any relevant issues. PRs must pass all CI checks.

License

Copyright 2026 ResQ. Distributed under the Apache License, Version 2.0. See LICENSE for full details.

About

ResQ Programs is a decentralized coordination layer built on Solana for autonomous aerospace and delivery operations, featuring on-chain airspace access control, permit enforcement, and delivery tracking.

Topics

Resources

Code of conduct

Contributing

Security policy

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages