Skip to main content

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.

ElementDetail
Struggling momentWriting custom IoT-to-blockchain bridges for every device type, every transport protocol, every project
Current workaroundCentralized REST API endpoint, manual data transformation, batch upload to chain on a cron
What progress looks likePlug 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 triggerWhen 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 SensorEvent schema
  • 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:

TransportConnects ToPriorityWhy
MQTTIndustrial sensors, ESP32, Raspberry Pi, any MQTT clientP0IoT standard. Broker-based pub/sub. Billion devices.
HTTP webhookGateways, cloud-connected devices, third-party APIsP0Simplest integration. Any device with WiFi.
WebSocketReal-time bidirectional (read sensors + command actuators)P1Closes the VVFL loop — read AND write.
BLEShort-range (wearables, indoor sensors)P2Requires local gateway, not cloud-native.
LoRaWANLong-range low-power (agriculture, environmental)P2Needs gateway partnership (Helium, Chirp, TTN).
GPIORaspberry Pi / edge compute direct pin controlP3led_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.

ElementDetail
Struggling momentWriting device identity contracts from scratch for every new DePIN project
Current workaroundCopy-paste from Helium's cNFT pattern or Chirp's object model, modify extensively
What progress looks likeImport 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 triggerWhen 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 Device type that maps to both Sui and Solana shapes
  • Solana depin_incentives full 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.

ElementDetail
Struggling momentBuilding custom verification pipelines for every device type and storage backend
Current workaroundCentralised API → database → periodic on-chain attestation. Verification is an afterthought
What progress looks likeData flows through: transport → normalise → verify → store → anchor, configured once
Hidden objection"Decentralised verification is too slow for real-time sensor data"
Switch triggerWhen 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
  • HardwareEvent interface — canonical event shape (deviceId, eventType, payload, timestamp)

What's missing:

  • Transport adapters that produce HardwareEvent from real device protocols (Job 1)
  • Normaliser — raw device payloads vary wildly, need canonical schema
  • Verification pipeline wiring data_oracle proof 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_oracle TypeScript 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.

ElementDetail
Struggling momentDesigning token economics that don't collapse when emissions exceed revenue
Current workaroundFixed 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 triggerWhen 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-score algorithm 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.move is 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.

ElementDetail
Struggling momentAI makes a decision but has no way to push it to the physical device that needs to act
Current workaroundHuman reads dashboard, manually adjusts device settings
What progress looks likeAgent 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 triggerWhen 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

DimensionSolanaSui
DePIN market cap$3.24B (June 2025)Early stage
Major projectsHelium (600K subs), Render, io.net ($20M ARR), Hivemapper, GEODNETChirp (500K users, IoT mesh)
Device modelAccount + 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)
StorageFilecoin (external integration)Walrus (native, erasure-coded, up to 100x cheaper for hot data)
ParallelismDynamic (runtime conflict detection)Static (compile-time, owned objects parallel by default)
DePIN SDK maturityOfficial quickstart guide, Anchor framework, cNFT patterns, Geyser pluginsGeneral Move SDK, no DePIN-specific tooling yet
DeFi liquidityDeep (Jupiter, Raydium)Growing
Security modelProgram-level enforcementLanguage-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

ChainThesisSignal
peaqPurpose-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.
IoTeXW3bstream 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
EntityWhat It RepresentsKey Fields
OperatorA person or org running DePIN hardwareAddress (wallet), stake, reputation score
FleetA group of devices under one operatorOperator, device count, coverage area
DeviceA physical DePIN device on-chainUID, type, firmware hash, location, status, owner
SensorA data channel on a deviceDevice, sensor type, calibration, sampling rate
DataStreamTime-series readings from a sensorSensor, payload, timestamp, signature, quality score
ProofCryptographic attestation of contributionDevice, epoch, proof type, hash, verified flag
RewardToken distribution for a contribution periodOperator, epoch, amount, basis (utilisation/coverage/quality)
EpochA reward calculation periodStart, end, total emissions, total revenue, ratio

Relationships

FromToCardinalityExample
OperatorFleetOne-to-manyOne operator manages multiple fleets across cities
FleetDeviceOne-to-manyA fleet of 500 weather stations
DeviceSensorOne-to-manyOne device has temperature, humidity, pressure sensors
SensorDataStreamOne-to-manyContinuous readings over time
DeviceProofOne-to-manyOne proof per epoch per device
OperatorRewardOne-to-manyRewards 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:

ContractModuleWhat It DoesStatus
depin_coreprotocol.moveProtocol config (min stake, reward rate, slash rate, data validity), stats (total devices, active devices, data points, rewards), pause/resume, admin transferBuilt
device_registrydevice.moveDevice struct (5 types: sensor/actuator/gateway/compute/storage), Location, DeviceCapability, ownership transfer, operator delegation, reputation scoring, metadata table, capability managementBuilt
incentivesrewards.moveRewardPool (stub — needs full epoch/distribution logic)Stub
precision_agriculturefarm_network.moveFarm, AgriculturalSensor (8 sensor types), SensorReading, WeatherPrediction, YieldPrediction, CropInsurance, weather risk calculation — first verticalBuilt
smart_cityurban_infrastructure.moveUrban DePIN verticalBuilt
cross_chain_bridgebridge_protocol.moveCross-chain messagingBuilt
experiments/led_controlled_device.moveRaspberry Pi LED/motor control via Solana blinksBuilt
tokenomics_validationtokenomics_tests.moveToken model verificationBuilt

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:

ProgramInstructionsWhat It DoesStatus
depin_incentivesinitialize_protocol, register_device, stake_for_device, submit_performance_data, distribute_rewards, slash_stake, unstake_and_deactivate, claim_rewards, update_protocol_paramsFull 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, slashingBuilt
data_oracleinitialize_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_rewardsOracle network for verified DePIN data — provider registration, cryptographic proof verification, multi-source aggregation, temporal validation, reputation systemBuilt
device_registryDevice registration (Solana-native)Stub
led_controlHardware control experimentBuilt
governanceFull instruction setDAO 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/)

ClientWhat It DoesStatus
clients-sui/device-registry.tsTypeScript wrapper for Sui device_registry Move callsBuilt
clients-sui/identity-client.tsOn-chain identity managementBuilt
clients-sui/loyalty-client.tsLoyalty program clientBuilt
clients-solana/Solana client layerPartial
indexer/Sui event indexer with device/loyalty handlersBuilt
shared/Multi-chain provider abstraction (Sui, Solana, EVM)Built

Layer 3: Infrastructure Adapters (libs/infrastructure/)

AssetLocationStatusWire To
HardwareEvent interfacelibs/infrastructure/hardware/src/lib/hardware.tsBuiltRename to depin/, extend with signature + location proof
HardwareAdapterSame fileBuiltBecomes base transport adapter
InMemoryHardwareAdapterSame fileBuiltTest/dev adapter for data ingest
DePIN score algorithmlibs/agency/algorithms/investment/depin-score/BuiltWire into reward sustainability tracking
DePIN data adapterslibs/infrastructure/data-api/depin-data-adapters/PartialWire into data ingest pipeline
Walrus adapterlibs/infrastructure/adapters/walrus/BuiltWire as storage backend
SEAL encryptionlibs/infrastructure/adapters/seal/BuiltIBE encryption for device data at rest
Messaging buslibs/infrastructure/messaging/BuiltAgent-to-device pub/sub
A2A orchestratorlibs/agency/orchestrators/a2a-orchestrator.tsBuiltAgent-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.

GapWhat ExistsWhat's Needed
Unified domain typesSui Device struct + Solana Device account (different shapes)Chain-agnostic TypeScript Device type that maps to both
Data ingest pipelineHardwareEvent interface + data-oracle programTransport → normalise → verify → store pipeline
Reward sustainability trackingdepin-score algo + depin_incentives program + protocol::reward_rateRevenue/emission ratio calculation wiring the on-chain data to the algo
Cross-layer workflowA2A orchestrator + messaging bus + device registry + data oracleComposer that chains: register device → ingest data → verify proof → distribute reward
Solana client parityFull Anchor programs built, client layer partialTypeScript 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)
HardwareEventSensorEvent + add signature, locationProof, qualityScore
HardwareAdapterTransportAdapter (in data-ingest/transport/)
InMemoryHardwareAdapterInMemoryTransportAdapter (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 StreamMechanismMargin Profile
Orchestration feesPer-workflow fee when agent workflows touch multiple DePIN layers (collection + compute + storage)High — coordination premium, no commodity competition
Intelligence premiumOracle-style agents monitoring DePIN health — revenue/emission tracking, anomaly detection, quality scoringHigh — data insight, not raw data
Protocol licensingReusable agent templates sold to DePIN operators ("sensor health monitoring", "coverage optimisation", "reward sustainability")Medium — recurring, scales with operator count

Unit Economics Targets

MetricTargetBasis
Orchestration fee$0.001-$0.01 per workflow executionBelow centralized middleware pricing
Intelligence subscription$99-499/mo per DePIN protocol monitoredValue: prevents token death spirals
Template license$29-99/mo per active agent templateValue: 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.

ComponentWhat ExistsWhat's MissingStatusPriority
MQTT transport adapterHardwareAdapter interfaceReal MQTT implementation (mqtt.js)0%P0
HTTP webhook adapterHardwareAdapter interfaceExpress/Hono endpoint that produces SensorEvent0%P0
WebSocket adapterHardwareAdapter interfaceBidirectional WS (telemetry in, commands out)0%P1
Transport factoryConfig-driven: { type: 'mqtt', broker: '...' } → adapter0%P0
Data normaliserHardwareEvent shapeRaw payload → canonical SensorEvent with schema registry10%P0
Batch aggregatorCollect N readings, hash, anchor one proof0%P1
Quality scorerSolana PerformanceMetrics on-chainTS-side uptime/freshness/accuracy tracking per device15%P1
Dead letter queueOffline devices, failed deliveries, retries0%P1
Domain typesSui Device + Solana Device (different shapes)Chain-agnostic TS Device, SensorEvent, Reward, Command0%P0
Sui device_registryContract done + TS client doneWire into depin lib75%P1
Sui depin_coreContract doneTS client70%P2
Sui incentivesRewardPool stubFull epoch/distribution logic10%P2
Sui precision_agricultureContract doneTS client for farm/sensor/prediction65%P2
Solana depin_incentives9-instruction contract doneFull TS client60%P1
Solana data_oracle11-instruction contract doneFull TS client, wire to pipeline verifier60%P1
Walrus storage wiringAdapter existsCompose with pipeline storage router30%P1
Reward sustainabilitydepin-score algo + on-chain statsWire algo to ProtocolStats for revenue/emission ratio20%P2
Command queueQueue, ACK, retry, safety constraints0%P2
Workflow orchestratorA2A orchestrator + messaging busDePIN-specific VVFL composer10%P2
Dual-mode providerArchitecture spec only0%P3

What's Built vs What's Needed

LayerBuiltStatusGap
IoT transportHardwareAdapter interface + InMemoryAdapter (test stub)5%Zero real transport implementations. This is the critical gap.
Data pipelineHardwareEvent shape, DePIN data adapters (analytics only)10%No normaliser, no verifier, no batch aggregator, no storage router
Sui contractsdepin_core + device_registry + precision_agriculture + smart_city + governance + bridge70%Incentives/rewards needs epoch logic
Solana programsdepin_incentives + data_oracle + governance60%device_registry stub, full TS clients needed
TS clients (Sui)device-registry, identity, loyalty, indexer50%Missing: depin_core client, agriculture client
TS clients (Solana)Partial20%Missing: depin_incentives client, data_oracle client
Actuator commandsNothing0%No command channel, no safety constraints, no audit trail
OrchestrationA2A orchestrator, messaging bus30%DePIN-specific VVFL workflow composer

Maturity Targets

LevelDefinitionGate
L0PRD and domain types definedThis document + domain/ types compile
L1Single-chain implementation worksRegister device, ingest data, distribute reward on Sui OR Solana
L2Both chains operationalSame workflow runs on either chain via composition root swap
L3Cross-layer orchestrationAgent workflow: collect → compute → store → act across protocols
L4Dual-tier agent + auto-promotionScout discovers new DePIN network, auto-generates Tier 2 integration

Success Criteria

Functional

#CriterionVerificationJob Served
F1MQTT adapter receives sensor data and produces SensorEvent within 50msLoad test with mosquitto brokerJob 1
F2HTTP webhook adapter accepts POST from ESP32 and produces SensorEventEnd-to-end test with real deviceJob 1
F3Pipeline: device reading → normalise → verify signature → store on Walrus → anchor proof on-chainWalkthroughJob 1, 3
F4Register a device on Sui with ownership transfer in under 5 secondsTimed testJob 2
F5Register 10,000 devices on Solana as cNFTs for under $1 totalCost testJob 2
F6Ingest 1,000 sensor readings/second sustained through MQTT pipelineLoad testJob 1, 3
F7data_oracle proof verification round-trips within 2 secondsTimed testJob 3
F8Calculate and distribute rewards to 5,000 operators in one epochEnd-to-end testJob 4
F9Revenue/emission ratio tracked and displayed per epochData verificationJob 4
F10WebSocket command sent to actuator, ACK received within 500msRound-trip testJob 5
F11Swap chain implementation via composition root without changing transport or pipeline codeArchitectural testAll

Non-Functional

#CriterionThreshold
NF1Transport-to-storage latencyUnder 100ms from MQTT publish to Walrus blob
NF2Reconnection timeMQTT adapter reconnects within 5 seconds after broker restart
NF3Dead letter handlingZero message loss — offline readings queued and delivered on reconnect
NF4Reward distribution gas costUnder $0.001 per recipient (batched)
NF5Library bundle size (domain only)Under 50KB
NF6Zero chain-specific imports in domain or transport layersArchitectural lint rule
NF7Chain client hot-swap timeUnder 1 minute (config change, no redeploy)

Risk + Kill Signal

RiskLikelihoodImpactMitigation
DePIN remains niche (<1% market share)MediumHighKeep centralized/decentralized framing balanced. Library works with centralized backends too.
Token emission economics prove unsustainable across most projectsMediumHighSustainability tracker IS the product — we help protocols avoid death spirals
Sui DePIN ecosystem doesn't growMediumLowSolana-first implementation. Sui support is architectural option, not dependency.
Regulatory crackdown on DePIN tokensLowHighLibrary separates device management (always legal) from tokenomics (regulatory risk)
Another chain captures DePIN (peaq, IoTeX)MediumMediumMulti-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

StageStatusOutput
NapkinDoneThis PRD — data flow architecture, IoT transport gap, chain comparison
Mock-upDestination built, on-ramp missingSui + Solana contracts, TS clients, Walrus adapter, HardwareAdapter interface. Zero real IoT transport.
MarketNot startedIdentify 3 DePIN protocols building on Sui or Solana who need transport + verification
BuildTransport layer is the bottleneckMQTT adapter → pipeline → chain wiring. Contracts are ready.
DemandNot startedFirst 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