DePIN Infrastructure Library
What happens when the device that feeds the AI also closes the loop?
The Gap
The destination is built. The on-ramp isn't.
Smart contracts know what a device IS — identity, state, capabilities, performance, rewards. TypeScript clients can call those contracts. But between a physical sensor and the blockchain sits nothing. The HardwareAdapter interface has the right shape (start(), stop(), onEvent()). Its only implementation is InMemoryHardwareAdapter — a test double.
PHYSICAL DEVICE (sensor, actuator, gateway)
│
│ ← THE GAP: No MQTT, no HTTP webhook, no WebSocket, no BLE, no LoRa
│ Zero real transport implementations
│
▼
libs/infrastructure/hardware/ ← InMemoryAdapter only
│
│ ← PARTIAL: DePIN data adapters pull project analytics
│ (DefiLlama, TokenTerminal, on-chain metrics)
│ NOT device telemetry
▼
libs/infrastructure/blockchain/ ← TS clients call contracts ✓
│
▼
libs/blockchain/ ← Move + Anchor contracts ✓
(device_registry, depin_core, depin_incentives, data_oracle)
The contracts handle on-chain identity and rewards. The data-api adapters handle DePIN project analytics (revenue, tokenomics). Nothing speaks to actual physical devices. The Raspberry Pi led_control experiment proved the concept — physical device → blockchain transaction — but it was a direct experiment, not an infrastructure pattern.
This PRD builds the road between physical devices and on-chain settlement.
Demand-Side Jobs
Five jobs, ordered by the data flow from physical world to blockchain and back. Job 1 is the critical gap. Jobs 2-4 are partially built. Job 5 closes the VVFL loop.
Job 1: Connect Physical Devices to the Stack (THE GAP)
Situation: A DePIN operator deploys 500 weather sensors across a city. Each sensor speaks MQTT. The blockchain contracts expect SensorEvent data with signatures and location proofs. Between MQTT publish and on-chain attestation there is nothing — every project builds a custom bridge from scratch.
| Element | Detail |
|---|---|
| Struggling moment | Writing custom IoT-to-blockchain bridges for every device type, every transport protocol, every project |
| Current workaround | Centralized REST API endpoint, manual data transformation, batch upload to chain on a cron |
| What progress looks like | Plug an MQTT adapter into a pipeline that normalises, signs, verifies, stores, and anchors data with one config |
| Hidden objection | "Our devices use a proprietary protocol — a generic transport layer won't work" |
| Switch trigger | When a sensor fleet scales from 50 to 5,000 devices and the custom bridge falls over |
Features that serve this job:
- Transport adapter interface (extending existing
HardwareAdapter) - MQTT adapter — industry standard for IoT telemetry (billion+ devices speak it)
- HTTP webhook adapter — simplest path, any device with WiFi can POST JSON
- WebSocket adapter — bidirectional, enables actuator commands back to devices
- Data normaliser — raw device payload → canonical
SensorEventschema - Device signature verification — ed25519 or device-specific signing
- Location proof attachment — GPS coordinates with accuracy and timestamp
- Batch aggregator — collect N readings, hash, anchor one proof on-chain
- Quality scorer — uptime, data freshness, reading accuracy per device
- Dead letter queue — handle offline devices, failed deliveries, retries
Transport priority matrix:
| Transport | Connects To | Priority | Why |
|---|---|---|---|
| MQTT | Industrial sensors, ESP32, Raspberry Pi, any MQTT client | P0 | IoT standard. Broker-based pub/sub. Billion devices. |
| HTTP webhook | Gateways, cloud-connected devices, third-party APIs | P0 | Simplest integration. Any device with WiFi. |
| WebSocket | Real-time bidirectional (read sensors + command actuators) | P1 | Closes the VVFL loop — read AND write. |
| BLE | Short-range (wearables, indoor sensors) | P2 | Requires local gateway, not cloud-native. |
| LoRaWAN | Long-range low-power (agriculture, environmental) | P2 | Needs gateway partnership (Helium, Chirp, TTN). |
| GPIO | Raspberry Pi / edge compute direct pin control | P3 | led_control experiment already proves this path. |
Job 2: Register and Manage Devices On-Chain (BUILT — needs wiring)
Situation: A DePIN protocol builder needs to onboard 10,000 weather sensors. Each device needs a unique on-chain identity, ownership tracking, firmware versioning, and the ability to transfer between operators.
| Element | Detail |
|---|---|
| Struggling moment | Writing device identity contracts from scratch for every new DePIN project |
| Current workaround | Copy-paste from Helium's cNFT pattern or Chirp's object model, modify extensively |
| What progress looks like | Import a library, call registerDevice(), get an on-chain identity with ownership semantics |
| Hidden objection | "Every DePIN network has unique device properties — a generic library won't fit" |
| Switch trigger | When a 3-month contract audit reveals bugs that a battle-tested library would have prevented |
What's already built:
- Sui
device_registry— 5 device types, 4 states, owner/agent/operator, Location, capabilities, reputation, staking, metadata - Sui
depin_core— Protocol config, stats, pause/resume, admin transfer - Solana
depin_incentives— 7 device types, staking, performance metrics, reward multiplier, slashing - Sui TS client for device registry
- Sui event indexer with device handlers
What's missing:
- Chain-agnostic TypeScript
Devicetype that maps to both Sui and Solana shapes - Solana
depin_incentivesfull TypeScript client (9 instructions in contract, client partial) - Fleet hierarchy (operator → fleet → device → sensor) in domain types
- Batch onboarding (Sui: object creation, Solana: compressed NFTs via Bubblegum)
Job 3: Verify and Store Sensor Data (PARTIALLY BUILT)
Situation: A geospatial DePIN project collects positioning data from 50,000 GNSS receivers. The data needs verifiable provenance — proof that this data came from this device at this time at this location.
| Element | Detail |
|---|---|
| Struggling moment | Building custom verification pipelines for every device type and storage backend |
| Current workaround | Centralised API → database → periodic on-chain attestation. Verification is an afterthought |
| What progress looks like | Data flows through: transport → normalise → verify → store → anchor, configured once |
| Hidden objection | "Decentralised verification is too slow for real-time sensor data" |
| Switch trigger | When a data buyer rejects a dataset because provenance can't be verified back to the device |
What's already built:
- Solana
data_oracle— 11 instructions: provider registration, data submission with cryptographic proofs, multi-source aggregation, temporal validation, reputation, slashing - Walrus adapter — blob storage on Sui's native storage layer
- SEAL encryption adapter — IBE encryption for device data at rest
-
HardwareEventinterface — canonical event shape (deviceId, eventType, payload, timestamp)
What's missing:
- Transport adapters that produce
HardwareEventfrom real device protocols (Job 1) - Normaliser — raw device payloads vary wildly, need canonical schema
- Verification pipeline wiring
data_oracleproof verification to ingest flow - Storage routing — policy-based: Walrus for hot data, Filecoin for archival, DB for indexing
- On-chain data anchoring — hash commitment per batch, not per reading
- Solana
data_oracleTypeScript client (11 instructions in contract, client partial)
Job 4: Distribute Rewards Sustainably (PARTIALLY BUILT)
Situation: A compute DePIN network needs to distribute tokens to 5,000 GPU providers weekly. The reward calculation depends on actual utilisation, not just uptime. Token emissions must stay below revenue to avoid the Ponzi trap.
| Element | Detail |
|---|---|
| Struggling moment | Designing token economics that don't collapse when emissions exceed revenue |
| Current workaround | Fixed emission schedules borrowed from Bitcoin, poorly adapted for utility networks |
| Hidden objection | "We need maximum flexibility in reward logic — a library would constrain us" |
| Switch trigger | When the revenue/emission ratio drops below 1.0 and the token enters a death spiral |
What's already built:
- Solana
depin_incentives— performance-weighted reward multiplier (uptime 50% + quality 100% + success rate 50%), staking, slashing, claim flow -
depin-scorealgorithm in agency lib — investment-grade DePIN project scoring - DePIN data adapters — DefiLlama, TokenTerminal, on-chain metrics for project analytics
What's missing:
- Revenue/emission ratio tracking wired to on-chain
ProtocolStats - Sui incentives —
rewards.moveis a stub (RewardPool only), needs full epoch/distribution logic - Epoch management — snapshot contributions, calculate, distribute cycle
- Sustainability dashboard data — revenue vs emissions over time, projected crossover
- Merkle tree distribution for Solana (cheaper than individual transfers at scale)
Job 5: Close the Loop — Actuator Commands (NOT BUILT)
Situation: An AI agent processes sensor data, makes a decision, and needs to send a command back to a physical device — adjust irrigation, reroute a drone, change a traffic signal. The precision_agriculture contract already models weather predictions and yield forecasts. But the command path from AI decision to physical actuator doesn't exist.
| Element | Detail |
|---|---|
| Struggling moment | AI makes a decision but has no way to push it to the physical device that needs to act |
| Current workaround | Human reads dashboard, manually adjusts device settings |
| What progress looks like | Agent workflow: sensor reading → AI inference → actuator command → device executes → telemetry confirms |
| Hidden objection | "Autonomous physical actions are too risky — we need human-in-the-loop" |
| Switch trigger | When a 2-second response window matters (frost detection → irrigation trigger) and no human is awake |
Features that serve this job:
- WebSocket adapter with bidirectional channels (read telemetry + send commands)
- Command queue with confirmation (device ACKs execution)
- Safety constraints — max actuation rate, geofencing, human-override flag
- VVFL loop completion: Perceive → Question → Act → Measure → Learn
- Integration with existing A2A orchestrator for agent-to-device messaging
- Audit trail — every command logged with decision context and outcome
Chain Comparison: Sui vs Solana
Both chains serve DePIN. Neither dominates the other. The split is architectural.
Where Each Chain Wins
| Dimension | Solana | Sui |
|---|---|---|
| DePIN market cap | $3.24B (June 2025) | Early stage |
| Major projects | Helium (600K subs), Render, io.net ($20M ARR), Hivemapper, GEODNET | Chirp (500K users, IoT mesh) |
| Device model | Account + compressed NFT (Bubblegum) | First-class object with owned/shared/immutable/wrapped types |
| Tx cost | ~$0.00025 | $0.001-$0.01 |
| Practical TPS | ~4,000 | ~400 user tx (owned-object tx bypass consensus) |
| Storage | Filecoin (external integration) | Walrus (native, erasure-coded, up to 100x cheaper for hot data) |
| Parallelism | Dynamic (runtime conflict detection) | Static (compile-time, owned objects parallel by default) |
| DePIN SDK maturity | Official quickstart guide, Anchor framework, cNFT patterns, Geyser plugins | General Move SDK, no DePIN-specific tooling yet |
| DeFi liquidity | Deep (Jupiter, Raydium) | Growing |
| Security model | Program-level enforcement | Language-level (Move linear types prevent 5 of OWASP top 10) |
Architectural Verdict
Solana wins for: token economics, reward distribution, DeFi composability, anything needing immediate ecosystem and liquidity. Helium's 900K hotspot cNFTs cost ~$122 total. The patterns are proven. Ship now.
Sui wins for: device state management with complex ownership hierarchies, IoT networks with independent device streams (owned-object tx bypass consensus entirely), and applications needing native programmable storage via Walrus. Build right.
The library supports both. Chain-specific implementations behind shared ports. Composition root selects the provider. Device management can run on Sui while token rewards run on Solana. The same workflow orchestrator doesn't care which chain settles which layer.
Other Chains to Watch
| Chain | Thesis | Signal |
|---|---|---|
| peaq | Purpose-built L1 for machine economy. Modular DePIN Functions (ID, Pay, Access, Data) in ~15 lines of JS. 60+ DePIN projects. Mastercard + Bosch partnerships. | Strongest DePIN-native tooling. Watch for ecosystem growth. |
| IoTeX | W3bstream off-chain computation with ZK/TEE/MPC proofs. Physical Consensus (PVC) Mainnet planned Q1 2026. | Most interesting middleware layer. If PVC delivers, physical data verification becomes consensus. |
Value Chain Architecture
The AI data value chain has five layers. This library provides the TypeScript infrastructure to interact with each layer.
COLLECTION CONNECTIVITY STORAGE COMPUTE APPLICATION
(devices) (transport) (persistence) (intelligence) (actuation)
GEODNET Helium Walrus io.net Peaq robots
Hivemapper World Mobile Filecoin Render Autonomous agents
WeatherXM Arweave Akash
DIMO Gensyn
High margin Medium margin Low-Med margin High margin Very high margin
Non-commodity Commodity unless 5x cost advantage GPU shortage = Where value is
data coverage unique pricing power consumed
The Alexander Wang insight: Scale AI proved data labeling is infrastructure ($870M→$2B revenue, 165% CAGR, $29B valuation). DePIN extends this from data LABELING to data COLLECTION — but the moat is community-owned devices, not a labour marketplace.
The transmitter/actuator insight: DePIN devices are dual-function. GEODNET feeds cm-accuracy GPS to drones (transmitter). The same positioning data guides the drone's flight path (actuator). The device that feeds the AI also closes the loop. This IS the VVFL feedback loop implemented in hardware.
Domain Model
OPERATORS ←→ FLEETS
↕ ↕
DEVICES ←→ SENSORS
↕ ↕
DATA STREAMS REWARDS
↕ ↕
PROOFS EPOCHS
| Entity | What It Represents | Key Fields |
|---|---|---|
| Operator | A person or org running DePIN hardware | Address (wallet), stake, reputation score |
| Fleet | A group of devices under one operator | Operator, device count, coverage area |
| Device | A physical DePIN device on-chain | UID, type, firmware hash, location, status, owner |
| Sensor | A data channel on a device | Device, sensor type, calibration, sampling rate |
| DataStream | Time-series readings from a sensor | Sensor, payload, timestamp, signature, quality score |
| Proof | Cryptographic attestation of contribution | Device, epoch, proof type, hash, verified flag |
| Reward | Token distribution for a contribution period | Operator, epoch, amount, basis (utilisation/coverage/quality) |
| Epoch | A reward calculation period | Start, end, total emissions, total revenue, ratio |
Relationships
| From | To | Cardinality | Example |
|---|---|---|---|
| Operator | Fleet | One-to-many | One operator manages multiple fleets across cities |
| Fleet | Device | One-to-many | A fleet of 500 weather stations |
| Device | Sensor | One-to-many | One device has temperature, humidity, pressure sensors |
| Sensor | DataStream | One-to-many | Continuous readings over time |
| Device | Proof | One-to-many | One proof per epoch per device |
| Operator | Reward | One-to-many | Rewards per epoch based on fleet contribution |
Library Architecture
The Full Data Flow
PHYSICAL WORLD IoT TRANSPORT (THE GAP) ON-CHAIN SETTLEMENT
Temperature sensor ──MQTT──→ ┌─────────────────────┐ ┌──────────────────┐
GPS receiver ──HTTP──→ │ Transport Adapter │ │ device_registry │
Camera feed ──WS────→ │ (MQTT/HTTP/WS/BLE) │ │ (Sui Move) │
Actuator ←─WS──── │ │ │ │
│ ↓ normalise │ │ depin_core │
│ ↓ sign │ │ (protocol config) │
│ ↓ verify │ ──anchor──→ │ │
│ ↓ batch │ │ depin_incentives │
│ ↓ store (Walrus) │ │ (Solana Anchor) │
│ ↓ score quality │ │ │
│ │ ←─rewards── │ data_oracle │
│ ↓ route commands │ │ (Solana Anchor) │
└──────────┬───────────┘ └──────────────────┘
│
▼
┌─────────────────────┐
│ Agent Orchestrator │
│ (A2A + messaging) │
│ │
│ perceive → question │
│ → act → measure │
│ → learn │
└──────────────────────┘
Layer Map
libs/infrastructure/depin/
├── domain/ # Zero deps — pure types
│ ├── device.types.ts # Device, Fleet, Operator (chain-agnostic)
│ ├── sensor-event.types.ts # SensorEvent (extends HardwareEvent + signature + location proof)
│ ├── reward.types.ts # Epochs, distributions, sustainability
│ ├── command.types.ts # Actuator commands, ACKs, safety constraints
│ └── ports/ # Abstract interfaces
│ ├── transport.port.ts # Start, stop, onEvent, sendCommand (bidirectional)
│ ├── device-registry.port.ts # Register, transfer, query devices
│ ├── data-ingest.port.ts # Normalise, verify, batch, route
│ ├── reward-engine.port.ts # Calculate, distribute rewards
│ └── storage.port.ts # Store and retrieve data blobs
│
├── transport/ # IoT TRANSPORT ADAPTERS — the critical gap
│ ├── mqtt.adapter.ts # P0 — MQTT 3.1.1/5.0 via broker (mosquitto, EMQX, HiveMQ)
│ ├── http-webhook.adapter.ts # P0 — POST endpoint for device/gateway callbacks
│ ├── websocket.adapter.ts # P1 — Bidirectional: telemetry in, commands out
│ ├── ble.adapter.ts # P2 — Bluetooth Low Energy via gateway
│ ├── lorawan.adapter.ts # P2 — LoRaWAN via TTN/Helium/Chirp gateway
│ ├── in-memory.adapter.ts # Test/dev (migrated from InMemoryHardwareAdapter)
│ └── transport-factory.ts # Create adapter from config: { type: 'mqtt', broker: '...' }
│
├── pipeline/ # Data processing pipeline
│ ├── normaliser.ts # Raw device payload → canonical SensorEvent
│ ├── signer.ts # Attach device signature (ed25519 or device-specific)
│ ├── verifier.ts # Verify signature, location proof, timestamp
│ ├── batch-aggregator.ts # Collect N readings, hash batch, anchor one proof
│ ├ ── quality-scorer.ts # Uptime, freshness, accuracy per device
│ ├── storage-router.ts # Policy: Walrus (hot) / Filecoin (archive) / DB (index)
│ └── dead-letter.ts # Offline devices, failed deliveries, retries
│
├── commands/ # Actuator command channel (Job 5)
│ ├── command-queue.ts # Queue commands, await ACK, retry/timeout
│ ├── safety-constraints.ts # Max rate, geofencing, human-override flag
│ └── audit-trail.ts # Log every command with decision context + outcome
│
├── clients-sui/ # Sui-specific implementations (wire existing)
│ ├── sui-device-registry.ts # Move contract client (object model) — EXISTS
│ ├── sui-depin-core.ts # Protocol config client — NEEDED
│ ├── sui-reward-distributor.ts # Direct transfer to owned objects — NEEDED
│ └── walrus-storage.ts # Walrus blob storage — EXISTS (in adapters/)
│
├── clients-solana/ # Solana-specific implementations
│ ├── solana-depin-incentives.ts # 9-instruction client — NEEDED (contract built)
│ ├── solana-data-oracle.ts # 11-instruction client — NEEDED (contract built)
│ ├── solana-device-registry.ts # cNFT via Bubblegum — NEEDED
│ └── merkle-distributor.ts # Batch reward distribution — NEEDED
│
├── reward-engine/ # Chain-agnostic reward logic
│ ├── calculators/ # Utilisation, coverage, quality weighted
│ ├── sustainability.ts # Revenue/emission ratio wired to ProtocolStats
│ └── epoch-manager.ts # Snapshot, calculate, distribute cycle
│
└── orchestrator/ # Cross-layer workflow coordination
├── depin-provider.port.ts # Abstract interface for any DePIN network
├── dual-mode-provider.ts # Tier 1 (browser) + Tier 2 (API) execution
├── workflow-composer.ts # Transport → verify → store → reward → command
└── auto-promoter.ts # Scout learns patterns, graduates to structured
Path Aliases (tsconfig.base.json additions)
{
"@stackmates/depin": "libs/infrastructure/depin/domain/index.ts",
"@stackmates/depin-transport": "libs/infrastructure/depin/transport/index.ts",
"@stackmates/depin-pipeline": "libs/infrastructure/depin/pipeline/index.ts",
"@stackmates/depin-commands": "libs/infrastructure/depin/commands/index.ts",
"@stackmates/depin-sui": "libs/infrastructure/depin/clients-sui/index.ts",
"@stackmates/depin-solana": "libs/infrastructure/depin/clients-solana/index.ts",
"@stackmates/depin-rewards": "libs/infrastructure/depin/reward-engine/index.ts",
"@stackmates/depin-orchestrator": "libs/infrastructure/depin/orchestrator/index.ts"
}
Dependency Rules
@stackmates/depin (domain) → zero deps, client-safe, runs anywhere
@stackmates/depin-transport → @stackmates/depin, mqtt.js, ws (Node/edge)
@stackmates/depin-pipeline → @stackmates/depin, @stackmates/depin-transport
@stackmates/depin-commands → @stackmates/depin, @stackmates/depin-transport
@stackmates/depin-sui → @mysten/sui, @stackmates/depin
@stackmates/depin-solana → @solana/kit, @stackmates/depin
@stackmates/depin-rewards → @stackmates/depin, @stackmates/agency (depin-score)
@stackmates/depin-orchestrator → @stackmates/depin, @stackmates/depin-pipeline,
@stackmates/depin-commands, @stackmates/infra-messaging
The domain layer imports nothing. Transport adapters implement domain ports. Pipeline composes transport + verification + storage. Chain clients talk to contracts. Orchestrator wires the full VVFL loop at the composition root.
Composition Root Pattern
// libs/app-server/composition/depin-workflow.composition.ts
import { createTransport } from '@stackmates/depin-transport';
import { createPipeline } from '@stackmates/depin-pipeline';
import { SuiDeviceRegistry } from '@stackmates/depin-sui';
import { SolanaDataOracle } from '@stackmates/depin-solana';
import { WalrusStorage } from '@stackmates/depin-sui';
import { createRewardEngine } from '@stackmates/depin-rewards';
import { createWorkflowComposer } from '@stackmates/depin-orchestrator';
// 1. IoT TRANSPORT — the on-ramp from physical world
const transport = createTransport({
type: 'mqtt',
broker: 'mqtt://sensors.local:1883',
topics: ['sensors/+/telemetry'], // subscribe to all device telemetry
commandTopic: 'devices/+/commands', // publish actuator commands
});
// 2. DATA PIPELINE — normalise → verify → batch → store
const pipeline = createPipeline({
transport,
normaliser: sensorEventNormaliser, // raw MQTT payload → SensorEvent
verifier: ed25519SignatureVerifier, // prove device identity
batchSize: 100, // anchor 1 proof per 100 readings
storage: new WalrusStorage({ publisherUrl }), // hot data on Walrus
oracle: new SolanaDataOracle({ connection }), // proof verification on-chain
});
// 3. DEVICE MANAGEMENT — on-chain identity
const deviceRegistry = new SuiDeviceRegistry({ client: suiClient });
// 4. REWARDS — utilisation-weighted, sustainability-tracked
const rewards = createRewardEngine({
calculator: utilisationWeighted,
distributor: solanaRewardDistributor,
sustainabilityThreshold: 1.0, // revenue/emission ratio floor
});
// 5. ORCHESTRATOR — full VVFL loop
const orchestrator = createWorkflowComposer({
perceive: pipeline, // sensor data flows in
question: agencyAlgorithms, // AI processes data
act: transport, // commands flow back to actuators (bidirectional)
measure: pipeline, // telemetry confirms execution
learn: rewards, // quality scores feed reward calculation
deviceRegistry,
});
Dual-Tier Agent Architecture
The DHH/OpenClaw insight applied to DePIN: agents don't always need structured APIs.
// libs/infrastructure/depin/orchestrator/dual-mode-provider.ts
interface DePINProviderPort {
// Tier 2: Structured, fast, cheap — for production workloads
getDeviceData(deviceId: string): Promise<SensorReading>;
submitProof(proof: ContributionProof): Promise<TxHash>;
// Tier 1: Browser-based, flexible — for exploration and onboarding
exploreNetwork(networkUrl: string): Promise<NetworkSchema>;
}
interface DualModeConfig {
structured?: StructuredProvider; // Use when API/SDK exists
exploratory?: BrowserProvider; // Use when it doesn't (yet)
autoPromote: boolean; // Learn patterns, graduate to structured
}
Tier 1 (Scout): Agent navigates a new DePIN network's web interface cold. Signs up, reads docs, discovers data structures. Slow, expensive, infinitely flexible. Used for onboarding to networks that don't have APIs yet.
Tier 2 (Operator): Structured SDK calls. Fast, cheap, reliable. Used for production workloads — real-time data ingestion, reward distribution, device management.
Auto-promotion: Tier 1 scouts learn patterns. When a pattern stabilises, the system generates a Tier 2 integration. Over time, the library accumulates structured integrations that started as zero-accommodation exploration. The scout becomes the operator.
Existing Assets — Three-Layer Stack Already Built
The engineering repo has a substantial DePIN stack across three layers. This PRD connects and extends what exists.
Layer 1: Smart Contracts (libs/blockchain/)
Sui Move contracts:
| Contract | Module | What It Does | Status |
|---|---|---|---|
depin_core | protocol.move | Protocol config (min stake, reward rate, slash rate, data validity), stats (total devices, active devices, data points, rewards), pause/resume, admin transfer | Built |
device_registry | device.move | Device struct (5 types: sensor/actuator/gateway/compute/storage), Location, DeviceCapability, ownership transfer, operator delegation, reputation scoring, metadata table, capability management | Built |
incentives | rewards.move | RewardPool (stub — needs full epoch/distribution logic) | Stub |
precision_agriculture | farm_network.move | Farm, AgriculturalSensor (8 sensor types), SensorReading, WeatherPrediction, YieldPrediction, CropInsurance, weather risk calculation — first vertical | Built |
smart_city | urban_infrastructure.move | Urban DePIN vertical | Built |
cross_chain_bridge | bridge_protocol.move | Cross-chain messaging | Built |
experiments/led_control | led_device.move | Raspberry Pi LED/motor control via Solana blinks | Built |
tokenomics_validation | tokenomics_tests.move | Token model verification | Built |
The device.move contract is production-grade: 5 device types, 4 device states (active/inactive/maintenance/decommissioned), owner + agent + operator separation, location with GPS accuracy, capabilities as dynamic vector, reputation scoring, staking, metadata table. This is the Sui device management layer.
Solana Anchor programs:
| Program | Instructions | What It Does | Status |
|---|---|---|---|
depin_incentives | initialize_protocol, register_device, stake_for_device, submit_performance_data, distribute_rewards, slash_stake, unstake_and_deactivate, claim_rewards, update_protocol_params | Full DePIN incentive lifecycle — device registration with 7 types (Storage/Compute/Wireless/Sensor/Energy/Vehicle/Custom), staking, performance metrics (uptime/quality/jobs/response time), reward multiplier calculation, slashing | Built |
data_oracle | initialize_oracle, register_provider, submit_data, verify_proof, aggregate_data, create_data_request, fulfill_data_request, validate_temporal_data, update_provider_reputation, slash_provider, claim_provider_rewards | Oracle network for verified DePIN data — provider registration, cryptographic proof verification, multi-source aggregation, temporal validation, reputation system | Built |
device_registry | — | Device registration (Solana-native) | Stub |
led_control | — | Hardware control experiment | Built |
governance | Full instruction set | DAO governance (proposals, voting, staking, delegation, treasury, council) | Built |
The Solana depin_incentives program has a performance-weighted reward multiplier: uptime bonus (50%), quality bonus (100%), success rate bonus (50%). Device types include Custom(u8) for extensibility. Performance metrics track uptime, data provided, quality score, jobs completed/failed, average response time.
The data_oracle program is a complete oracle network: provider registration, data submission with cryptographic proofs, multi-source aggregation, temporal validation, reputation scoring, and slashing for malicious providers.
Layer 2: TypeScript Clients (libs/infrastructure/blockchain/)
| Client | What It Does | Status |
|---|---|---|
clients-sui/device-registry.ts | TypeScript wrapper for Sui device_registry Move calls | Built |
clients-sui/identity-client.ts | On-chain identity management | Built |
clients-sui/loyalty-client.ts | Loyalty program client | Built |
clients-solana/ | Solana client layer | Partial |
indexer/ | Sui event indexer with device/loyalty handlers | Built |
shared/ | Multi-chain provider abstraction (Sui, Solana, EVM) | Built |
Layer 3: Infrastructure Adapters (libs/infrastructure/)
| Asset | Location | Status | Wire To |
|---|---|---|---|
| HardwareEvent interface | libs/infrastructure/hardware/src/lib/hardware.ts | Built | Rename to depin/, extend with signature + location proof |
| HardwareAdapter | Same file | Built | Becomes base transport adapter |
| InMemoryHardwareAdapter | Same file | Built | Test/dev adapter for data ingest |
| DePIN score algorithm | libs/agency/algorithms/investment/depin-score/ | Built | Wire into reward sustainability tracking |
| DePIN data adapters | libs/infrastructure/data-api/depin-data-adapters/ | Partial | Wire into data ingest pipeline |
| Walrus adapter | libs/infrastructure/adapters/walrus/ | Built | Wire as storage backend |
| SEAL encryption | libs/infrastructure/adapters/seal/ | Built | IBE encryption for device data at rest |
| Messaging bus | libs/infrastructure/messaging/ | Built | Agent-to-device pub/sub |
| A2A orchestrator | libs/agency/orchestrators/a2a-orchestrator.ts | Built | Agent-to-device workflow orchestration |
What's Actually Missing
The contracts and clients exist. What's missing is the wiring layer — the TypeScript infrastructure lib that composes all three layers into usable workflows.
| Gap | What Exists | What's Needed |
|---|---|---|
| Unified domain types | Sui Device struct + Solana Device account (different shapes) | Chain-agnostic TypeScript Device type that maps to both |
| Data ingest pipeline | HardwareEvent interface + data-oracle program | Transport → normalise → verify → store pipeline |
| Reward sustainability tracking | depin-score algo + depin_incentives program + protocol::reward_rate | Revenue/emission ratio calculation wiring the on-chain data to the algo |
| Cross-layer workflow | A2A orchestrator + messaging bus + device registry + data oracle | Composer that chains: register device → ingest data → verify proof → distribute reward |
| Solana client parity | Full Anchor programs built, client layer partial | TypeScript clients matching what clients-sui/ already provides |
Rename: hardware → depin
The current libs/infrastructure/hardware/ library has the right abstractions but the wrong name and scope. The rename is structural, not cosmetic:
| Current (hardware) | Target (depin/domain) |
|---|---|
HardwareEvent | SensorEvent + add signature, locationProof, qualityScore |
HardwareAdapter | TransportAdapter (in data-ingest/transport/) |
InMemoryHardwareAdapter | InMemoryTransportAdapter (test/dev) |
@stackmates/infrastructure-hardware | @stackmates/depin (domain types barrel) |
The existing interface becomes the seed. The chain-agnostic domain types unify the Sui device.move struct and Solana Device account into one TypeScript shape.
Business Model
Revenue Architecture
Stackmates captures value at three points in the DePIN stack:
| Revenue Stream | Mechanism | Margin Profile |
|---|---|---|
| Orchestration fees | Per-workflow fee when agent workflows touch multiple DePIN layers (collection + compute + storage) | High — coordination premium, no commodity competition |
| Intelligence premium | Oracle-style agents monitoring DePIN health — revenue/emission tracking, anomaly detection, quality scoring | High — data insight, not raw data |
| Protocol licensing | Reusable agent templates sold to DePIN operators ("sensor health monitoring", "coverage optimisation", "reward sustainability") | Medium — recurring, scales with operator count |
Unit Economics Targets
| Metric | Target | Basis |
|---|---|---|
| Orchestration fee | $0.001-$0.01 per workflow execution | Below centralized middleware pricing |
| Intelligence subscription | $99-499/mo per DePIN protocol monitored | Value: prevents token death spirals |
| Template license | $29-99/mo per active agent template | Value: replaces custom development |
Flywheel
More agent templates
→ More DePIN operators adopt Stackmates
→ More workflow data
→ Better agent performance
→ More templates
→ repeat
The data from orchestration becomes the moat, not the code.
Commissioning
Ordered by the data flow: physical device → transport → pipeline → chain → rewards → commands.
| Component | What Exists | What's Missing | Status | Priority |
|---|---|---|---|---|
| MQTT transport adapter | HardwareAdapter interface | Real MQTT implementation (mqtt.js) | 0% | P0 |
| HTTP webhook adapter | HardwareAdapter interface | Express/Hono endpoint that produces SensorEvent | 0% | P0 |
| WebSocket adapter | HardwareAdapter interface | Bidirectional WS (telemetry in, commands out) | 0% | P1 |
| Transport factory | — | Config-driven: { type: 'mqtt', broker: '...' } → adapter | 0% | P0 |
| Data normaliser | HardwareEvent shape | Raw payload → canonical SensorEvent with schema registry | 10% | P0 |
| Batch aggregator | — | Collect N readings, hash, anchor one proof | 0% | P1 |
| Quality scorer | Solana PerformanceMetrics on-chain | TS-side uptime/freshness/accuracy tracking per device | 15% | P1 |
| Dead letter queue | — | Offline devices, failed deliveries, retries | 0% | P1 |
| Domain types | Sui Device + Solana Device (different shapes) | Chain-agnostic TS Device, SensorEvent, Reward, Command | 0% | P0 |
| Sui device_registry | Contract done + TS client done | Wire into depin lib | 75% | P1 |
| Sui depin_core | Contract done | TS client | 70% | P2 |
| Sui incentives | RewardPool stub | Full epoch/distribution logic | 10% | P2 |
| Sui precision_agriculture | Contract done | TS client for farm/sensor/prediction | 65% | P2 |
| Solana depin_incentives | 9-instruction contract done | Full TS client | 60% | P1 |
| Solana data_oracle | 11-instruction contract done | Full TS client, wire to pipeline verifier | 60% | P1 |
| Walrus storage wiring | Adapter exists | Compose with pipeline storage router | 30% | P1 |
| Reward sustainability | depin-score algo + on-chain stats | Wire algo to ProtocolStats for revenue/emission ratio | 20% | P2 |
| Command queue | — | Queue, ACK, retry, safety constraints | 0% | P2 |
| Workflow orchestrator | A2A orchestrator + messaging bus | DePIN-specific VVFL composer | 10% | P2 |
| Dual-mode provider | — | Architecture spec only | 0% | P3 |
What's Built vs What's Needed
| Layer | Built | Status | Gap |
|---|---|---|---|
| IoT transport | HardwareAdapter interface + InMemoryAdapter (test stub) | 5% | Zero real transport implementations. This is the critical gap. |
| Data pipeline | HardwareEvent shape, DePIN data adapters (analytics only) | 10% | No normaliser, no verifier, no batch aggregator, no storage router |
| Sui contracts | depin_core + device_registry + precision_agriculture + smart_city + governance + bridge | 70% | Incentives/rewards needs epoch logic |
| Solana programs | depin_incentives + data_oracle + governance | 60% | device_registry stub, full TS clients needed |
| TS clients (Sui) | device-registry, identity, loyalty, indexer | 50% | Missing: depin_core client, agriculture client |
| TS clients (Solana) | Partial | 20% | Missing: depin_incentives client, data_oracle client |
| Actuator commands | Nothing | 0% | No command channel, no safety constraints, no audit trail |
| Orchestration | A2A orchestrator, messaging bus | 30% | DePIN-specific VVFL workflow composer |
Maturity Targets
| Level | Definition | Gate |
|---|---|---|
| L0 | PRD and domain types defined | This document + domain/ types compile |
| L1 | Single-chain implementation works | Register device, ingest data, distribute reward on Sui OR Solana |
| L2 | Both chains operational | Same workflow runs on either chain via composition root swap |
| L3 | Cross-layer orchestration | Agent workflow: collect → compute → store → act across protocols |
| L4 | Dual-tier agent + auto-promotion | Scout discovers new DePIN network, auto-generates Tier 2 integration |
Success Criteria
Functional
| # | Criterion | Verification | Job Served |
|---|---|---|---|
| F1 | MQTT adapter receives sensor data and produces SensorEvent within 50ms | Load test with mosquitto broker | Job 1 |
| F2 | HTTP webhook adapter accepts POST from ESP32 and produces SensorEvent | End-to-end test with real device | Job 1 |
| F3 | Pipeline: device reading → normalise → verify signature → store on Walrus → anchor proof on-chain | Walkthrough | Job 1, 3 |
| F4 | Register a device on Sui with ownership transfer in under 5 seconds | Timed test | Job 2 |
| F5 | Register 10,000 devices on Solana as cNFTs for under $1 total | Cost test | Job 2 |
| F6 | Ingest 1,000 sensor readings/second sustained through MQTT pipeline | Load test | Job 1, 3 |
| F7 | data_oracle proof verification round-trips within 2 seconds | Timed test | Job 3 |
| F8 | Calculate and distribute rewards to 5,000 operators in one epoch | End-to-end test | Job 4 |
| F9 | Revenue/emission ratio tracked and displayed per epoch | Data verification | Job 4 |
| F10 | WebSocket command sent to actuator, ACK received within 500ms | Round-trip test | Job 5 |
| F11 | Swap chain implementation via composition root without changing transport or pipeline code | Architectural test | All |
Non-Functional
| # | Criterion | Threshold |
|---|---|---|
| NF1 | Transport-to-storage latency | Under 100ms from MQTT publish to Walrus blob |
| NF2 | Reconnection time | MQTT adapter reconnects within 5 seconds after broker restart |
| NF3 | Dead letter handling | Zero message loss — offline readings queued and delivered on reconnect |
| NF4 | Reward distribution gas cost | Under $0.001 per recipient (batched) |
| NF5 | Library bundle size (domain only) | Under 50KB |
| NF6 | Zero chain-specific imports in domain or transport layers | Architectural lint rule |
| NF7 | Chain client hot-swap time | Under 1 minute (config change, no redeploy) |
Risk + Kill Signal
| Risk | Likelihood | Impact | Mitigation |
|---|---|---|---|
| DePIN remains niche (<1% market share) | Medium | High | Keep centralized/decentralized framing balanced. Library works with centralized backends too. |
| Token emission economics prove unsustainable across most projects | Medium | High | Sustainability tracker IS the product — we help protocols avoid death spirals |
| Sui DePIN ecosystem doesn't grow | Medium | Low | Solana-first implementation. Sui support is architectural option, not dependency. |
| Regulatory crackdown on DePIN tokens | Low | High | Library separates device management (always legal) from tokenomics (regulatory risk) |
| Another chain captures DePIN (peaq, IoTeX) | Medium | Medium | Multi-chain abstraction. Adding a new chain client is additive, not rewrite. |
Kill signal: If after 6 months no DePIN protocol has integrated any library component, the abstraction is wrong. The market wants vertical solutions (per-protocol), not horizontal infrastructure (cross-protocol). Pivot to building protocol-specific agent templates instead.
What would change the thesis: If revenue/emission ratios prove unsustainable across most DePIN projects (revenue never catches emissions), the economic model fails. Watch: io.net revenue trajectory, Helium subscriber growth, Filecoin paid storage volume.
Shape Up
| Stage | Status | Output |
|---|---|---|
| Napkin | Done | This PRD — data flow architecture, IoT transport gap, chain comparison |
| Mock-up | Destination built, on-ramp missing | Sui + Solana contracts, TS clients, Walrus adapter, HardwareAdapter interface. Zero real IoT transport. |
| Market | Not started | Identify 3 DePIN protocols building on Sui or Solana who need transport + verification |
| Build | Transport layer is the bottleneck | MQTT adapter → pipeline → chain wiring. Contracts are ready. |
| Demand | Not started | First physical device → on-chain proof end-to-end |
Appetite: 3-week cycle, transport-first.
Cycle 1 — The On-Ramp (P0): Rename hardware → depin. Define domain types (SensorEvent extending HardwareEvent, chain-agnostic Device). Build MQTT adapter and HTTP webhook adapter. Test: ESP32 sensor → MQTT broker → adapter → SensorEvent → console log. This proves the physical-to-digital bridge.
Cycle 2 — The Pipeline: Build normaliser, signature verifier, batch aggregator, storage router. Wire Walrus adapter as storage backend. Wire Solana data_oracle TS client for proof verification. Test: MQTT sensor reading → normalise → verify → store on Walrus → anchor proof hash on-chain.
Cycle 3 — Close the Loop: Build WebSocket adapter (bidirectional). Build command queue with ACK and safety constraints. Wire to precision_agriculture contract (sensor reading → AI prediction → irrigation command → device executes). Wire reward sustainability tracker to on-chain ProtocolStats.
Next Steps
1. Rename libs/infrastructure/hardware/ → libs/infrastructure/depin/
2. Define domain types: SensorEvent (extends HardwareEvent + signature + locationProof + qualityScore),
Device (unifies Sui device.move + Solana Device account), Command (actuator instructions)
3. Build MQTT transport adapter implementing TransportPort (mqtt.js, topic subscription, reconnect)
4. Build HTTP webhook transport adapter (POST endpoint → SensorEvent)
5. Build data normaliser (raw device payloads → canonical SensorEvent)
6. Wire pipeline: MQTT adapter → normaliser → verifier → Walrus storage → data_oracle proof anchor
7. Build Solana data_oracle TypeScript client (11 instructions in contract, needed for verification)
8. Build WebSocket adapter (bidirectional — telemetry in, commands out)
9. Build command queue with ACK, retry, and safety constraints
10. Wire depin-score algorithm to on-chain ProtocolStats for sustainability tracking
Smallest move: Rename the lib. Build MQTT adapter that implements the existing HardwareAdapter interface — start() connects to broker, stop() disconnects, onEvent() forwards messages as HardwareEvent. Run against a local mosquitto broker with a temperature sensor publishing JSON. If a real sensor reading arrives as a typed HardwareEvent in the Node process, the on-ramp exists.
Kill signal: If the MQTT adapter can't sustain 1,000 messages/second from a local broker without dropping messages, the architecture won't scale to real DePIN networks. Test throughput before building the pipeline.
Key architectural insight: The contracts model the destination (what a device IS, what it earns). The transport models the journey (how data gets from physical world to digital). The pipeline is the bridge. The command channel closes the loop. Build bottom-up: transport → pipeline → chain wiring → orchestration. Not top-down.
Key insight from contracts review: The Sui contracts model devices as things with identity (UID, capabilities, metadata table). The Solana programs model devices as things with performance (uptime, quality score, jobs completed, reward multiplier). Both are needed. The chain-agnostic type should carry identity from Sui and performance from Solana — the two chains complement rather than compete at the type level.
Mycelium Capability
The DePIN Infrastructure Library is a physical-world capability. It extends the Mycelium into hardware — devices that perceive, compute, store, and act. Every other Mycelium capability operates in software. This one closes the loop with the physical world.
Currently Growing In: stackmates
The VVFL connection: DePIN devices PERCEIVE (collect ground truth) → AI QUESTIONS (trains on data, builds predictions) → Actuators ACT (robots, autonomous systems execute) → Outcomes MEASURED (device telemetry records results) → System LEARNS (model improves, device network adapts). The dual transmitter/actuator role means the same device that feeds the loop also closes it.
Context
- DePIN Platform — Core DePIN concepts, stack layers, device categories
- DePIN Devices — Hardware evaluation framework
- Phygital Marketing — Physical + digital integration patterns
- Solana DePIN Programs — Raspberry Pi example, circuit → blockchain
- Sui Tech — Object model, Move, zkLogin, PTBs
- Sui Wallet Safety — Safety patterns for chain interactions
- DePIN Tokens — Token economics reference
- Jobs To Be Done — Demand-side thinking
- AI Data Industry — Value chain, transmitter/actuator framing
- Robotics Industry — Autonomous systems that consume DePIN data
- The Infrastructure Flip — DePIN coordination thesis
- Phygital Mycelium — The capability catalogue