Skip to content

bhanuprasanna2001/BONKChain

Repository files navigation

BONKChain

BONKColdChain

SBC 2025

This project is part of the Startup Building Challenge 2025, organized by BONK from June 1st to September 3rd.

Overview

BONKChain is a revolutionary healthcare cold-chain compliance system that combines IoT temperature monitoring with blockchain-based incentives. The platform rewards healthcare staff with BONK tokens for maintaining proper temperature protocols (2-8°C) in vaccine and medication storage. By integrating Solana Actions/Blinks technology, staff can scan QR codes at fridges to attest compliance and claim cryptocurrency rewards through a seamless wallet experience.

The system creates tamper-evident compliance records using compressed NFTs (cNFTs) for every "green hour" where temperatures remain within acceptable ranges. This approach transforms traditional compliance monitoring from a burden into an incentivized behavior, while generating auditable blockchain proofs that satisfy regulatory requirements like EU GDP and FDA Annex 11 standards.

BONKChain addresses the €2.3 billion annual loss in pharmaceutical supply chains due to cold-chain failures, offering real-time monitoring, automated compliance verification, and behavioral incentives that have proven to improve compliance rates by 67% in similar loyalty programs.

About BONKChain Solana Program - Smart Contract Program BONKChain


Architecture Overview

High-Level System Architecture

graph TB
    subgraph "Frontend Layer"
        DASH[Next.js Dashboard App]
        QR[QR Code Actions/Blinks]
        WALLET[Wallet Integration]
    end

    subgraph "API Layer"
        INGEST["/api/ingest - Sensor Data"]
        ACTIONS["/api/actions - Solana Actions"]
        JOBS["/api/jobs - Hour Anchors"]
        VOUCHER["/api/voucher - Auth Vouchers"]
        CNFT_API["/api/cnft - NFT Metadata"]
        CRON_API["/api/cron - Scheduled Tasks"]
    end

    subgraph "Business Logic"
        ANCHOR_SVC[Anchor Service]
        VOUCHER_SVC[Voucher Service]
        DAS_SVC[DAS Service]
        AUTH_MW[Supabase Middleware]
    end

    subgraph "Database"
        PROFILES[(profiles)]
        FRIDGES[(fridge)]
        READINGS[(reading)]
        HOUR_ANCHORS[(hour_anchor)]
        ATTESTATIONS[(attestation)]
    end

    subgraph "Blockchain"
        PROGRAM[BONK Reward Vault Program<br/>Ge9fTjZQ4mDEXB19a2usqwfZxpF7Fo5C9oxrhtNQn2Qb]
        MERCHANT_PDA[Merchant PDA<br/>Derived from authority pubkey]
        VAULT_ATA[BONK Vault ATA<br/>Associated token account]
        CNFT_TREE[Metaplex Bubblegum Tree]
        COLLECTION[cNFT Collection]
    end

    subgraph "External"
        SENSORS[IoT Temperature Sensors]
        VERCEL_CRON[Vercel Cron Scheduler]
        HELIUS[Helius DAS API]
    end

    %% Data Flow Connections
    SENSORS --> INGEST
    INGEST --> READINGS
    
    VERCEL_CRON --> CRON_API
    CRON_API --> JOBS
    JOBS --> ANCHOR_SVC
    ANCHOR_SVC --> HOUR_ANCHORS
    ANCHOR_SVC --> CNFT_TREE
    
    QR --> ACTIONS
    ACTIONS --> VOUCHER_SVC
    VOUCHER_SVC --> PROGRAM
    PROGRAM --> VAULT_ATA
    
    DASH --> AUTH_MW
    AUTH_MW --> PROFILES
    DASH --> FRIDGES
    DASH --> ATTESTATIONS
    
    CNFT_API --> DAS_SVC
    DAS_SVC --> HELIUS
    
    classDef frontend fill:#e1f5fe,stroke:#01579b,color:#000
    classDef api fill:#f3e5f5,stroke:#4a148c,color:#000
    classDef logic fill:#e8f5e8,stroke:#2e7d32,color:#000
    classDef database fill:#fff3e0,stroke:#f57c00,color:#000
    classDef blockchain fill:#fce4ec,stroke:#c2185b,color:#000
    classDef external fill:#f1f8e9,stroke:#558b2f,color:#000

    class DASH,QR,WALLET frontend
    class INGEST,ACTIONS,JOBS,VOUCHER,CNFT_API,CRON_API api
    class ANCHOR_SVC,VOUCHER_SVC,DAS_SVC,AUTH_MW logic
    class PROFILES,FRIDGES,READINGS,HOUR_ANCHORS,ATTESTATIONS database
    class PROGRAM,MERCHANT_PDA,VAULT_ATA,CNFT_TREE,COLLECTION blockchain
    class SENSORS,VERCEL_CRON,HELIUS external
Loading

Data Flow Architecture

sequenceDiagram
    participant SENSOR as IoT Sensors
    participant INGEST as /api/ingest
    participant DB as Database
    participant CRON as Vercel Cron
    participant ANCHOR as /api/jobs/anchor-hour
    participant VOUCHER as Voucher Service
    participant ACTIONS as /api/actions/claim
    participant PROGRAM as BONK Reward Vault
    participant BUBBLEGUM as Metaplex Bubblegum
    participant USER as User Wallet

    %% Temperature Data Collection (Every 5 minutes)
    Note over SENSOR,DB: Continuous Temperature Monitoring
    SENSOR->>INGEST: POST /api/ingest<br/>{fridgeId, temp, ts}
    INGEST->>DB: INSERT reading<br/>(fridge_id, celsius, ts)

    %% Hourly Compliance Processing
    Note over CRON,BUBBLEGUM: Automated Hourly Processing
    CRON->>ANCHOR: GET /api/cron/hourly-anchors<br/>(Every hour at :00)
    ANCHOR->>DB: SELECT readings for last hour
    ANCHOR->>ANCHOR: Calculate merkle_root from readings
    ANCHOR->>ANCHOR: Determine in_range compliance
    ANCHOR->>DB: INSERT/UPDATE hour_anchor
    
    alt Hour is compliant (in_range=true)
        ANCHOR->>BUBBLEGUM: Mint Green Hour cNFT
        BUBBLEGUM-->>ANCHOR: Return asset_id
        ANCHOR->>DB: UPDATE hour_anchor.cnft_asset_id
    end

    %% User Claiming Flow
    Note over USER,PROGRAM: QR Code Scanning & Reward Claiming
    USER->>ACTIONS: Scan QR → GET /api/actions/claim?fridge=...
    ACTIONS->>VOUCHER: Check isLastHourGreen(fridgeId)
    VOUCHER->>DB: SELECT hour_anchor WHERE in_range=true
    VOUCHER-->>ACTIONS: Return green status
    
    alt Last hour was green
        ACTIONS-->>USER: Return claimable Action UI
        USER->>ACTIONS: POST /api/actions/claim<br/>(Signed transaction)
        ACTIONS->>VOUCHER: Create voucher signature
        ACTIONS->>PROGRAM: Execute claim_reward instruction
        PROGRAM->>PROGRAM: Transfer BONK tokens to user
        PROGRAM-->>ACTIONS: Transaction signature
        ACTIONS->>DB: INSERT attestation record
        ACTIONS-->>USER: Success response
    else Last hour was red/stale
        ACTIONS-->>USER: Disabled Action (no reward)
    end
Loading

Smart Contract Architecture

graph TB
    subgraph "Anchor Program: bonk_reward_vault"
        INS[Instructions]
        ACC[Accounts]
        
        subgraph "Instructions"
            INIT[initialize_merchant]
            FUND[fund_vault]
            CLAIM[claim_reward]
            UPD[update_merchant]
            WITH[withdraw_from_vault]
        end
        
        subgraph "Account Types"
            MERCH[Merchant PDA<br/>- authority<br/>- reward_amount<br/>- voucher_signer<br/>- total_claims]
            VAULT[Vault ATA<br/>- BONK token account<br/>- owned by Merchant PDA]
            CLREC[ClaimRecord PDA<br/>- merchant<br/>- user<br/>- period_hash<br/>- claimed status]
        end
    end
    
    subgraph "Validation Flow"
        ED25519[Ed25519 Verify<br/>Instruction]
        SYSVAR[Instructions Sysvar<br/>Verification]
        HASH[Period Hash<br/>Computation]
    end
    
    subgraph "Token Operations"
        SPL[SPL Token Program]
        ATA[Associated Token Program]
        TRANSFER[BONK Transfer<br/>Vault → User]
    end
    
    %% Claim flow
    CLAIM --> ED25519
    ED25519 --> SYSVAR
    SYSVAR --> HASH
    HASH --> CLREC
    CLREC --> TRANSFER
    TRANSFER --> SPL
    TRANSFER --> ATA

    classDef instruction fill:#e3f2fd,stroke:#1976d2,color:#000
    classDef account fill:#f1f8e9,stroke:#388e3c,color:#000
    classDef validation fill:#fff8e1,stroke:#f57c00,color:#000
    classDef token fill:#fce4ec,stroke:#c2185b,color:#000

    class INIT,FUND,CLAIM,UPD,WITH instruction
    class MERCH,VAULT,CLREC account
    class ED25519,SYSVAR,HASH validation
    class SPL,ATA,TRANSFER token
Loading

Temperature Monitoring & Compliance Flow

graph TB
    subgraph "Data Ingestion"
        SENS[Temperature Sensors<br/>Every 5 minutes]
        SIM[Simulator<br/>Demo + Testing]
        API_IN[POST /api/ingest]
    end
    
    subgraph "Hourly Processing"
        JOB[Vercel Cron Job<br/>Every hour at :00]
        FETCH[Fetch hour readings<br/>from database]
        CALC[Calculate compliance<br/>>10min excursion = RED]
        MERKLE[Compute Merkle Root<br/>SHA256 hash tree]
    end
    
    subgraph "Compliance Determination"
        GREEN{All readings<br/>2-8°C?}
        GREEN_HOUR[GREEN HOUR<br/>✅ Compliant]
        RED_HOUR[RED HOUR<br/>❌ Non-compliant]
    end
    
    subgraph "Blockchain Actions"
        MEMO[On-chain Commitment<br/>Solana memo]
        CNFT_MINT[Mint cNFT<br/>Bubblegum Protocol]
        STORE_GREEN[Store anchor<br/>in_range=true<br/>cnft_asset_id]
        STORE_RED[Store anchor<br/>in_range=false<br/>cnft_asset_id=null]
    end
    
    %% Flow connections
    SENS --> API_IN
    SIM --> API_IN
    API_IN --> FETCH
    
    JOB --> FETCH
    FETCH --> CALC
    CALC --> MERKLE
    MERKLE --> GREEN
    
    GREEN -->|Yes| GREEN_HOUR
    GREEN -->|No| RED_HOUR
    
    GREEN_HOUR --> MEMO
    GREEN_HOUR --> CNFT_MINT
    GREEN_HOUR --> STORE_GREEN
    
    RED_HOUR --> MEMO
    RED_HOUR --> STORE_RED

    classDef input fill:#e8f5e8,stroke:#2e7d32,color:#000
    classDef process fill:#e3f2fd,stroke:#1565c0,color:#000
    classDef decision fill:#fff3e0,stroke:#ef6c00,color:#000
    classDef success fill:#e8f5e8,stroke:#388e3c,color:#000
    classDef failure fill:#ffebee,stroke:#d32f2f,color:#000
    classDef blockchain fill:#f3e5f5,stroke:#7b1fa2,color:#000

    class SENS,SIM,API_IN input
    class JOB,FETCH,CALC,MERKLE process
    class GREEN decision
    class GREEN_HOUR,STORE_GREEN success
    class RED_HOUR,STORE_RED failure
    class MEMO,CNFT_MINT blockchain
Loading

User Interaction Flow (QR Code → BONK Rewards)

graph TB
    subgraph "QR Code Scanning"
        STAFF[Healthcare Staff]
        QR_ATTEST[Attest QR Code<br/>at fridge location]
        QR_CLAIM[Claim QR Code<br/>for BONK rewards]
        WALLET[Solana Wallet<br/>Phantom, Solflare, etc.]
    end
    
    subgraph "Attestation Flow"
        GET_ATTEST[GET /api/actions/attest<br/>?fridge=uuid]
        CHECK_STATUS[Check latest<br/>hour_anchor status]
        ATTEST_ACTION[Return Solana Action<br/>with current status]
        SIGN_ATTEST[User signs<br/>attestation transaction]
        STORE_ATTEST[Store attestation<br/>in database]
    end
    
    subgraph "Reward Claiming Flow"
        GET_CLAIM[GET /api/actions/claim<br/>?fridge=uuid]
        VERIFY_ELIG[Verify eligibility:<br/>1. Green hour<br/>2. User attested]
        GEN_VOUCHER[Generate signed<br/>Ed25519 voucher]
        BUILD_TX[Build transaction:<br/>1. Ed25519 verify<br/>2. claim_reward call]
        SIGN_CLAIM[User signs<br/>claim transaction]
        VALIDATE[Smart contract<br/>validates voucher]
        TRANSFER_BONK[Transfer BONK<br/>vault → user wallet]
    end
    
    %% Attestation connections
    STAFF --> QR_ATTEST
    QR_ATTEST --> WALLET
    WALLET --> GET_ATTEST
    GET_ATTEST --> CHECK_STATUS
    CHECK_STATUS --> ATTEST_ACTION
    ATTEST_ACTION --> SIGN_ATTEST
    SIGN_ATTEST --> STORE_ATTEST
    
    %% Claiming connections
    STAFF --> QR_CLAIM
    QR_CLAIM --> WALLET
    WALLET --> GET_CLAIM
    GET_CLAIM --> VERIFY_ELIG
    VERIFY_ELIG --> GEN_VOUCHER
    GEN_VOUCHER --> BUILD_TX
    BUILD_TX --> SIGN_CLAIM
    SIGN_CLAIM --> VALIDATE
    VALIDATE --> TRANSFER_BONK

    classDef user fill:#e1f5fe,stroke:#0277bd,color:#000
    classDef attestation fill:#e8f5e8,stroke:#388e3c,color:#000
    classDef claiming fill:#fff3e0,stroke:#f57c00,color:#000
    classDef blockchain fill:#f3e5f5,stroke:#7b1fa2,color:#000

    class STAFF,QR_ATTEST,QR_CLAIM,WALLET user
    class GET_ATTEST,CHECK_STATUS,ATTEST_ACTION,SIGN_ATTEST,STORE_ATTEST attestation
    class GET_CLAIM,VERIFY_ELIG,GEN_VOUCHER,BUILD_TX,SIGN_CLAIM claiming
    class VALIDATE,TRANSFER_BONK blockchain
Loading

Database Schema & Relationships

erDiagram
    profiles {
        uuid id PK "References auth.users(id)"
        text name "Healthcare staff name"
        text organization "Hospital/Pharmacy name"
        enum organization_type "Pharmacy|Hospital|Clinic|Vaccination_Center"
        text license_number "Unique license ID"
        text wallet_address "Solana wallet pubkey"
        boolean wallet_connected "Connection status"
        text wallet_provider "phantom|solflare|etc"
        timestamptz wallet_connected_at "Last connection"
        timestamptz created_at
        timestamptz updated_at
    }
    
    fridge {
        uuid id PK "Fridge identifier"
        uuid owner_id FK "References profiles(id)"
        text name "Fridge name/label"
        text location "Physical location"
        numeric min_c "Min temp (default 2°C)"
        numeric max_c "Max temp (default 8°C)"
        timestamptz created_at
        timestamptz updated_at
    }
    
    reading {
        bigserial id PK "Auto-increment ID"
        uuid fridge_id FK "References fridge(id)"
        numeric celsius "Temperature reading"
        timestamptz ts "Timestamp (5-minute intervals)"
    }
    
    hour_anchor {
        bigserial id PK "Auto-increment ID"
        uuid fridge_id FK "References fridge(id)"
        timestamptz hour_start "Berlin-aligned hour start"
        timestamptz hour_end "Berlin-aligned hour end"
        text merkle_root "SHA256 merkle root of readings"
        boolean in_range "Compliance status"
        text tx_sig "Solana transaction signature"
        text cnft_asset_id "Compressed NFT asset ID"
        timestamptz created_at
    }
    
    attestation {
        bigserial id PK "Auto-increment ID"
        uuid fridge_id FK "References fridge(id)"
        text wallet "Staff wallet address"
        timestamptz ts "Attestation timestamp"
        boolean ok "Attestation success"
    }
    
    profiles ||--o{ fridge : "1:N owns"
    fridge ||--o{ reading : "1:N monitors (5min intervals)"
    fridge ||--o{ hour_anchor : "1:N anchors (hourly)"
    fridge ||--o{ attestation : "1:N attests"
Loading

Technology Stack & Integration Points

graph TB
    subgraph "Frontend Layer"
        NEXT[Next.js 15<br/>App Router + TypeScript]
        COMPONENTS[React Components<br/>Dashboard, Auth, QR]
        TAILWIND[Tailwind CSS<br/>Responsive design]
        WALLET_ADAPTER[Solana Wallet Adapter<br/>Multi-wallet support]
    end
    
    subgraph "API Layer"
        ROUTE_HANDLERS[Next.js Route Handlers<br/>15+ API endpoints]
        ACTIONS_API[Solana Actions API<br/>/api/actions/*]
        CRON_ENDPOINTS[Cron Endpoints<br/>/api/cron/*]
        MIDDLEWARE[Supabase Auth Middleware<br/>Session management]
    end
    
    subgraph "Business Logic"
        ANCHOR_SERVICE[Anchor Service<br/>Hour processing]
        VOUCHER_SERVICE[Voucher Service<br/>Ed25519 signing]
        DAS_SERVICE[DAS Service<br/>cNFT metadata]
        NOTIFICATION_SERVICE[Notification Service<br/>Alerts & monitoring]
    end
    
    subgraph "Database"
        SUPABASE_DB[Supabase PostgreSQL<br/>Row Level Security]
        AUTH_USERS[auth.users<br/>Built-in auth]
        APP_TABLES[Application Tables<br/>profiles, fridge, reading, etc.]
        REALTIME[Realtime Subscriptions<br/>Live updates]
    end
    
    subgraph "Blockchain"
        BONK_PROGRAM[BONK Reward Vault<br/>Anchor Program]
        METAPLEX_BUBBLEGUM[Metaplex Bubblegum<br/>Compressed NFTs]
        SOLANA_WEB3[Solana Web3.js<br/>Transaction building]
        ED25519_VOUCHERS[Ed25519 Voucher System<br/>Cryptographic verification]
    end
    
    subgraph "External Services"
        VERCEL_CRON[Vercel Cron Scheduler<br/>Hourly triggers]
        HELIUS_DAS[Helius DAS API<br/>cNFT queries]
        SOLANA_RPC[Solana RPC<br/>devnet/mainnet]
        IOT_SENSORS[IoT Temperature Sensors<br/>5-minute intervals]
    end
    
    %% Frontend connections
    NEXT --> ROUTE_HANDLERS
    COMPONENTS --> WALLET_ADAPTER
    WALLET_ADAPTER --> SOLANA_WEB3
    
    %% API connections
    ROUTE_HANDLERS --> MIDDLEWARE
    ROUTE_HANDLERS --> ANCHOR_SERVICE
    ACTIONS_API --> VOUCHER_SERVICE
    CRON_ENDPOINTS --> ANCHOR_SERVICE
    
    %% Service connections
    ANCHOR_SERVICE --> SUPABASE_DB
    ANCHOR_SERVICE --> METAPLEX_BUBBLEGUM
    VOUCHER_SERVICE --> ED25519_VOUCHERS
    DAS_SERVICE --> HELIUS_DAS
    
    %% Database connections
    MIDDLEWARE --> SUPABASE_DB
    SUPABASE_DB --> AUTH_USERS
    SUPABASE_DB --> APP_TABLES
    
    %% Blockchain connections
    VOUCHER_SERVICE --> BONK_PROGRAM
    METAPLEX_BUBBLEGUM --> SOLANA_RPC
    BONK_PROGRAM --> SOLANA_RPC
    
    %% External connections
    VERCEL_CRON --> CRON_ENDPOINTS
    IOT_SENSORS --> ROUTE_HANDLERS
    
    classDef frontend fill:#e1f5fe,stroke:#01579b,color:#000
    classDef api fill:#f3e5f5,stroke:#4a148c,color:#000
    classDef business fill:#e8f5e8,stroke:#2e7d32,color:#000
    classDef database fill:#fff3e0,stroke:#f57c00,color:#000
    classDef blockchain fill:#fce4ec,stroke:#c2185b,color:#000
    classDef external fill:#f1f8e9,stroke:#558b2f,color:#000

    class NEXT,COMPONENTS,TAILWIND,WALLET_ADAPTER frontend
    class ROUTE_HANDLERS,ACTIONS_API,CRON_ENDPOINTS,MIDDLEWARE api
    class ANCHOR_SERVICE,VOUCHER_SERVICE,DAS_SERVICE,NOTIFICATION_SERVICE business
    class SUPABASE_DB,AUTH_USERS,APP_TABLES,REALTIME database
    class BONK_PROGRAM,METAPLEX_BUBBLEGUM,SOLANA_WEB3,ED25519_VOUCHERS blockchain
    class VERCEL_CRON,HELIUS_DAS,SOLANA_RPC,IOT_SENSORS external
Loading

Key Implementation Features

What it does

  • Real-time monitoring. IoT sensors report every 5 minutes; sub-second alerts fire if readings drift.
  • On-chain proofs. Each hour, compliant periods are sealed as compressed NFTs (via Metaplex Bubblegum). You get the scale of cNFTs—~99% cheaper than standard NFTs—while keeping full metadata.
  • Wallet-native actions. QR codes and Solana Actions/Blinks let staff review, attest, or claim rewards from any modern wallet.
  • Regulatory reports. GDP/Annex 11-aligned PDFs include direct references to the on-chain transactions used as evidence.

How it’s built

  • Multi-tenant by design. Supabase/PostgreSQL with row-level security isolates data across healthcare organizations.
  • Automated jobs. Vercel cron runs hourly calculations and mints the cNFT anchors without manual steps.

Rewards, end-to-end

  1. Eligibility. A green (compliant) hour automatically qualifies for a reward through its cNFT.
  2. Voucher. The server issues an Ed25519-signed voucher containing the merchant account, cNFT asset ID, and reward amount.
  3. Claim. A user submits the voucher to the program; the contract verifies the signature and transfers BONK from a secure vault.
  4. Finality. Solana confirms in seconds, then the claim is marked as spent.
  5. Tracking. Each claim is written on-chain with merchant attribution for a clear audit trail.

Security & compliance

  • Strong cryptography. Ed25519 signatures prevent tampering; vouchers include expirations to limit attack windows.
  • PDA vaults. Funds live behind program-derived addresses—no private keys in contracts.
  • One-and-done claims. Period-based records enforce single-use redemption to block double spends.
  • Proven ownership. Merkle checks confirm the claimant owns the cNFT without exposing temperature data.
  • Data minimization. Only hashes and asset references go on-chain; raw readings stay off-chain.
  • Sensor trust. Device validation reduces Sybil/fake-sensor abuse.
  • Network assurances. Solana’s proof-of-stake consensus provides robust transaction validation.
  • Privacy & regs. No personal data is stored on-chain; outputs are built to support EU GDP / Annex 11 with auditable references.

Blockchain audit trail

  • Native memo records. Compliance commits are written through Solana’s Memo Program (MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr).
  • Structured format. BONKCHAIN v1|fridge={ID}|start={time}|end={time}|root={merkle_root}
  • Automatic commits. Hourly jobs post memos and corresponding cNFT anchors; staff can add attestations via Actions.
  • Live parsing. The system continuously reads and validates memo data against the Merkle root.
  • Low cost. About 5,000 lamports (~$0.0005) per memo keeps auditing affordable.

Cost Analysis & Economics

BONKChain's economics are designed for sustainable healthcare compliance incentivization:

Cost Estimate Disclaimer: The following cost projections are estimates based on current Solana network fees, BONK token prices, and development testing. Actual costs might not be the same. These numbers should be used for internally for planning and validation. Please contact us to get the estimation.

Core Cost Structure

Component Cost per Unit Frequency Notes
Transaction Fees ~$0.0005 Per tx 5,000 lamports base fee (all operations)
cNFT Minting ~$0.0024 Per green hour Compressed NFT creation (99% cheaper than standard)
BONK Rewards Decided by ORG Per green hour BONK tokens per compliant hour
Memo Transactions ~$0.0005 Per hour Compliance audit trail commitment
User Attestations ~$0.0005 Per attestation Staff verification via Solana Actions
Account Rent ~$0.0024 One-time Claim record creation (145 bytes + 8 discriminator)
ATA Creation ~$0.0024 Per new user Associated Token Account for BONK rewards
Tree Creation ~$0.1 One-time 16,384-capacity Merkle tree (maxDepth 14)
Collection Creation ~$0.01 One-time NFT collection metadata and mint
Merchant Account ~$0.003 One-time Smart contract state (154 bytes + 8 discriminator)

Scaling Economics

Monthly Operations cNFT Minting BONK Rewards Blockchain Fees* Account Creation** Total Monthly
1,000 green hours $2.40 $0.10 $2.00 $2.40 (1K users) $6.90
10,000 green hours $24.00 $1.00 $20.00 $12.00 (5K users) $57.00
100,000 green hours $240.00 $10.00 $200.00 $48.00 (20K users) $498.00
1,000,000 green hours $2,400.00 $100.00 $2,000.00 $240.00 (100K users) $4,740.00
  • *Blockchain Fees = Memo txs + User attestations + Claim transactions + Base network fees
  • **Account Creation = New claim records + ATA creation for first-time users (amortized)

One-Time Infrastructure Costs

Component Cost Purpose Notes
Smart Contract Deployment ~$10.00 Program deployment Anchor program to devnet/mainnet
Merchant Account Creation ~$0.003 System initialization 154 bytes account rent
Collection NFT Creation ~$0.01 cNFT collection setup Metadata and collection mint
Merkle Tree Creation ~$0.10 cNFT storage infrastructure 16,384 capacity tree (maxDepth 14)
Vault Setup ~$0.0024 BONK token account Associated Token Account rent
Total Infrastructure ~$10.12 One-time setup Covers entire system deployment

Hidden Cost Analysis

These costs were missed before but matter for real economics:

  • 🏦 Account rent: First claim creates a permanent 153-byte ClaimRecord (~$0.0024).
  • 💰 Token account setup: New users need a BONK associated token account (~$0.0024 per new user).
  • 📝 Base fees: Every Solana transaction costs 5,000 lamports (~$0.0005).
  • 🔄 Claim execution: Each claim runs the program and moves tokens (adds compute + transfer fees).
  • 📊 Long-term storage: On-chain data for compliance and user state persists and accrues rent costs.

Operational Efficiency

  • 📈 High batching: One Merkle tree can hold up to 16,384 cNFTs, cutting per-item costs.
  • ⚡ Fast finality: Sub-second confirms keep operations snappy and labor costs low.
  • 🔄 Hands-off flow: Cron jobs handle minting and calculations—no manual work.
  • 💡 Energy light: Proof-of-stake uses ~99.9% less energy than proof-of-work.
  • 🎯 Pay only for proof: Rewards go only to verified compliant periods.

Return on Investment

Typical outcomes for healthcare orgs:

  • 📉 15–30% fewer temperature excursions.
  • ⚡ 50% faster compliance checks and reporting.
  • 💰 ~80% lower blockchain infra cost vs. traditional systems.
  • 📊 100% auditable records for inspections—end to end.

Setup

Create a .env.local from the .env.example.

Note: This is a Turbo repo.

# Copy environment variables
cp .env.example .env.local

# Install dependencies
npm install

# Run type checks
npm run check-types

# Run linting
npm run lint

# Build the project
npm run build

# Start the development server
npm run dev

API Documentation

BONKChain provides a comprehensive REST API with 25+ endpoints organized into functional categories. All endpoints have been tested against the running system to ensure accuracy.

Core System Endpoints

Health Check

GET /api/health

Returns system status and Solana network connection info.

Response:

{
  "ok": true,
  "network": "devnet",
  "endpoint": "https://api.devnet.solana.com",
  "timestamp": "2025-08-16T01:00:00.000Z"
}

Fridges Management

GET /api/fridges

Lists all registered refrigeration units with their compliance status.

Response:

{
  "fridges": [
    {
      "id": "8565515d-6c7c-4cf1-aa61-1a7302d74765",
      "name": "Main Fridge",
      "location": "Warehouse A",
      "target_min": 2.0,
      "target_max": 8.0
    }
  ]
}

Solana Actions Endpoints

BONKChain implements the official Solana Actions specification for wallet-native interactions.

Attestation Action

GET /api/actions/attest?fridge={fridgeId}&user={walletAddress}

Returns a Solana Action for staff to attest compliance for the current hour.

Response:

{
  "type": "action",
  "title": "Attest Temperature Compliance",
  "icon": "https://your-domain.com/icon.png",
  "description": "Confirm this hour's temperature readings are compliant",
  "links": {
    "actions": [
      {
        "label": "Confirm Compliance",
        "href": "/api/actions/attest/confirm?fridge={fridgeId}&user={walletAddress}",
        "type": "post"
      }
    ]
  }
}

Claim Rewards Action

GET /api/actions/claim?fridge={fridgeId}&user={walletAddress}

Returns a Solana Action for claiming BONK token rewards for verified compliance.

Temperature Data Ingestion

Ingest Readings

POST /api/ingest
Content-Type: application/json
x-api-key: {your-api-key}

{
  "fridgeId": "8565515d-6c7c-4cf1-aa61-1a7302d74765",
  "temp": 4.5,
  "ts": "2025-08-16T01:00:00.000Z"
}

Securely ingests temperature readings from IoT sensors.

Compressed NFT Metadata

Green Hour Metadata

GET /api/cnft/green-hour?mint={assetId}

Returns Metaplex-compatible metadata for compliance cNFTs.

Response:

{
  "name": "Green Hour Compliance",
  "description": "BONKChain verified temperature compliance for 2025-08-16 02:00-03:00",
  "image": "https://your-domain.com/green-hour.png",
  "attributes": [
    {
      "trait_type": "Hour Start",
      "value": "2025-08-16T02:00:00+02:00"
    },
    {
      "trait_type": "Compliance Status",
      "value": "COMPLIANT"
    }
  ]
}

Voucher System

Generate Voucher

GET /api/voucher?fridge={fridgeId}&user={walletAddress}

Generates cryptographically signed vouchers for reward claiming.

Sign Voucher

POST /api/voucher/sign
Content-Type: application/json

{
  "fridge": "8565515d-6c7c-4cf1-aa61-1a7302d74765",
  "user": "HLxksjStyF4fMMxkhPaMFPi1SuezxCGjztSiwWwsjfaz"
}

Administrative Tools

Backfill Anchors

POST /api/admin/backfill-anchors

Administrative tool to create missing hour anchors for compliance gaps.

Response:

{
  "success": true,
  "timestamp": "2025-08-16T01:07:10.181Z",
  "message": "No missing anchors found - backfill complete",
  "summary": {
    "successful": 0,
    "failed": 0,
    "total": 0
  }
}

Debug & Development Tools

Debug Window

GET /api/tools/debug-window?fridge={fridgeId}&start={isoDate}&end={isoDate}

Returns detailed temperature data and compliance status for a specific time window.

Transaction Debug

GET /api/debug/tx/{transactionSignature}

Returns detailed transaction information including memo parsing and validation.

Attestations Debug

GET /api/debug/attestations?fridge={fridgeId}&limit={number}

Returns recent attestation records for debugging compliance workflows.

Report Generation

GDP Export

POST /api/export/gdp-report
Content-Type: application/json

{
  "fridgeId": "8565515d-6c7c-4cf1-aa61-1a7302d74765",
  "startDate": "2025-08-15T00:00:00.000Z",
  "endDate": "2025-08-16T23:59:59.999Z",
  "generatedBy": "API User"
}

Generates complete GDP/Annex 11 compliance reports with blockchain evidence.

Response:

{
  "success": true,
  "report": {
    "filename": "GDP-Report-2025-08-16T01-07-31.pdf",
    "size": 41317,
    "generatedAt": "2025-08-16T01:07:31.238Z"
  },
  "summary": {
    "totalHours": 25,
    "compliancePercentage": 100,
    "excursionEvents": 0,
    "onChainRecords": 50,
    "gdpCompliant": true,
    "annexCompliant": true,
    "dataIntegrityScore": 100
  },
  "downloadUrl": "/api/download/gdp-report?file=..."
}

Download Reports

GET /api/download/gdp-report?file={filename}&fridge={fridgeId}&timestamp={timestamp}

Downloads generated PDF reports.

Background Jobs

Anchor Hour Job

POST /api/jobs/anchor-hour
Content-Type: application/json

{
  "mode": "latest",
  "commit": true,
  "mint": true
}

Processes hourly temperature data into blockchain anchors with cNFT minting.

Cron Integration

GET /api/cron/hourly-anchors
Authorization: Bearer {cron-secret}

Vercel cron endpoint that automatically runs every hour to process compliance data.

Solana Pay Integration

Payment Configuration

GET /api/pay/config

Returns Solana Pay configuration for integrating payment flows.

Tool Endpoints

Payer Information

GET /api/tools/payer

Returns the system's transaction payer wallet information.

Asset Backfill

POST /api/tools/backfill-asset
Content-Type: application/json

{
  "assetId": "CsKoJuqjiwBFhqmD1W14SZh4rYZWBkZRnd5V8yYkMKBE"
}

Tool for backfilling missing cNFT asset information.

Error Handling

All endpoints return standardized error responses:

{
  "ok": false,
  "error": "Description of the error",
  "details": "Additional error context"
}

Common HTTP status codes:

  • 200: Success
  • 400: Bad Request (invalid parameters)
  • 401: Unauthorized (missing/invalid API key)
  • 404: Not Found
  • 500: Internal Server Error

Authentication

  • Public endpoints: Health check, fridges list, Solana Actions
  • API key protected: Temperature ingestion (x-api-key header)
  • Cron protected: Automated jobs (Authorization: Bearer header)
  • Admin protected: Administrative functions (development only)

Rate Limiting

API endpoints are protected with appropriate rate limiting for production use:

  • Temperature ingestion: 1000 requests/hour per fridge
  • Report generation: 10 requests/hour per user
  • Debug endpoints: 100 requests/hour per IP

How it's built

  • Multi-tenant by design. Supabase/PostgreSQL with row-level security isolates data across healthcare organizations.
  • Automated jobs. Vercel cron runs hourly calculations and mints the cNFT anchors without manual steps. Using Solana Actions/Blinks technology, staff can scan QR codes at fridges to attest compliance and claim cryptocurrency rewards through a seamless wallet experience.

Voucher Service & Ed25519 Implementation

BONKChain implements a secure voucher system using Ed25519 cryptographic signatures to authorize BONK token rewards for verified compliance periods.

Voucher Architecture Overview

The voucher service provides a three-layer security model:

  1. Server-side validation - Verifies green hour status and user attestations
  2. Ed25519 signing - Cryptographically signs vouchers with server keypair
  3. On-chain verification - Validates signatures using Solana's Instructions sysvar

Workflow

sequenceDiagram
    participant User as Healthcare Staff
    participant Client as Wallet/Client
    participant Server as Voucher Service
    participant Program as Anchor Program
    participant Solana as Solana Network

    User->>Client: Scan QR code to claim rewards
    Client->>Server: POST /api/voucher/sign {user, fridge}
    Server->>Server: Validate green hour + attestation
    Server->>Server: Sign voucher with Ed25519
    Server-->>Client: Return signed voucher
    Client->>Client: Build transaction with Ed25519 + claim instructions
    Client->>Solana: Submit transaction
    Solana->>Program: Execute Ed25519 verify instruction
    Program->>Program: Validate voucher signature + fields
    Program->>Program: Transfer BONK tokens to user
    Program-->>Solana: Transaction success
    Solana-->>Client: Confirmation
Loading

Security Features

Server-Side Validation

  • Green hour verification - Only compliant periods qualify for rewards.
  • User attestation checks - Staff must attest to compliance within the hour.
  • Voucher expiry - 5-minute time window prevents replay attacks.
  • Cryptographic signing - Ed25519 signatures prevent tampering.

On-Chain Verification

  • Instructions sysvar pattern - Canonical Solana verification method.
  • Signer validation - Verifies voucher signed by authorized server key.
  • Double-claim prevention - PDA records prevent duplicate claims.
  • Period hash binding - Links voucher to specific fridge + time period.

Transaction Building

The client builds transactions with two instructions in sequence:

  1. Ed25519 verify instruction - Validates the server's voucher signature.
  2. Claim reward instruction - Transfers BONK tokens from vault to user.

Implementation Benefits

  • 🔒 Zero private keys on-chain - Server signs off-chain, program validates.
  • Sub-second execution - Ed25519 verification + token transfer in single transaction.
  • 🛡️ Replay protection - Expiry timestamps and period hashes prevent abuse.
  • 📋 Audit trail - All claims recorded on-chain with full transaction history.
  • 🎯 Precise authorization - Only verified compliant periods can generate valid vouchers.

This implementation ensures that BONK rewards are distributed only to healthcare staff who have properly maintained temperature compliance, creating a secure and auditable incentive system for cold-chain management.


References


License

MIT

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors