140  Smart Contracts for IoT

In 60 Seconds

Smart contracts are self-executing blockchain programs that automatically enforce agreements when IoT conditions are met (e.g., temperature breach triggers insurance payout). The oracle problem is the key challenge: contracts cannot access sensor data directly and need trusted oracle services. Store full sensor data off-chain (cheap), store only cryptographic hashes on-chain (tamper-proof verification at minimal gas cost).

Minimum Viable Understanding
  • Smart contracts are self-executing programs on a blockchain that automatically enforce agreements when conditions are met (e.g., temperature breach triggers insurance claim) – no intermediaries needed.
  • The oracle problem is the key challenge: smart contracts cannot access real-world sensor data directly; they need trusted oracle services to bridge IoT data to the blockchain.
  • Hybrid on-chain/off-chain architecture is essential: store full sensor data off-chain (cheap), store only cryptographic hashes on-chain (tamper-proof verification at minimal cost).

The Sensor Squad was monitoring a truck full of ice cream being shipped across the country. The deal was simple: if the temperature goes above -18C for more than 30 minutes, the shipping company pays a $10,000 penalty.

“In the old days,” explained Max the Microcontroller, “someone would download the temperature logs AFTER delivery, find the problem, file a complaint, argue for weeks, and MAYBE get paid months later.”

“But with a smart contract,” Sammy the Sensor said proudly, “I send my temperature readings to the blockchain, and the code AUTOMATICALLY checks: Is it too warm? For how long? If the answer is yes – BOOM – the penalty payment happens instantly. No arguing, no waiting, no lawyers!”

Lila the LED raised a concern: “But wait – the smart contract lives on the blockchain. How does it KNOW what my temperature is? It can’t reach out and read a thermometer!”

“Great question!” said Max. “That’s the ORACLE problem. The smart contract needs a helper (an oracle) to bring real-world data INTO the blockchain. Our IoT gateway is that helper – it reads Sammy’s temperature, signs it with a secret key, and feeds it to the contract.”

Bella the Battery summarized: “Smart contracts are like vending machines for agreements. Put in the right conditions, and the result comes out automatically. But someone still has to put the coins in – that’s what IoT sensors do!”

Think of a smart contract as a programmable “if-then” rule that lives on a blockchain:

  • IF the temperature sensor reads above 25C for more than 1 hour
  • THEN automatically send $10,000 from the shipper’s account to the receiver’s account AND record the breach permanently

The key difference from a normal program is that smart contracts are:

  • Unstoppable: Once deployed, no one can change or stop them (on most platforms)
  • Transparent: Everyone can see the rules
  • Automatic: No human needs to press a button – the contract executes itself

The main challenge for IoT is the “oracle problem”: smart contracts cannot read sensors directly. They need a trusted intermediary (called an oracle) to bring real-world data onto the blockchain.

140.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Design smart contracts for IoT automation and machine-to-machine transactions
  • Explain the oracle problem and how IoT devices bridge real-world data to blockchain
  • Architect hybrid on-chain/off-chain solutions for scalable IoT systems
  • Implement gateway-based patterns for resource-constrained blockchain clients
  • Apply periodic anchoring and lightweight verification techniques

140.2 Smart Contracts for IoT

Time: ~12 min | Difficulty: Advanced | P04.C09.U04

Smart contracts are self-executing programs stored on a blockchain. When predefined conditions are met, the contract automatically executes actions–no intermediaries needed.

Smart contract execution diagram for IoT showing an IoT sensor submitting temperature data to a blockchain smart contract via an oracle bridge. The contract automatically checks predefined conditions and, when met, triggers actions including payment releases, alert notifications, and permanent ledger recording without human intervention.

Smart Contract IoT
Figure 140.1: Smart contract execution in IoT - automatic trustless automation triggered by sensor data.

Blockchain-based supply chain tracking diagram showing goods flowing through five parties: manufacturer, shipper, customs, distributor, and retailer. At each handoff, IoT sensors record conditions and smart contracts automatically enforce compliance thresholds. All handoff events are stored on a shared distributed ledger visible to all participants.

Supply Chain Blockchain
Figure 140.2: Blockchain-based supply chain tracking with IoT sensors ensuring transparency and compliance at each stage.
Common Misconception: Smart Contracts Are Legally Binding

Myth: “Smart contracts automatically enforce legal agreements and replace lawyers.”

Reality: Smart contracts are code that executes automatically–they are NOT inherently legal contracts:

  • Code does not equal legal contract: A smart contract is software. Legal enforceability depends on jurisdiction, proper contract formation, meeting of minds, and consideration.
  • Bugs are permanent: Unlike traditional contracts that can be interpreted by judges, smart contract bugs become immutable once deployed (on most platforms). The DAO hack (2016) exploited a smart contract flaw to steal $60M in Ethereum.
  • Legal gray area: Most jurisdictions don’t recognize code as a contract. You typically need both: (1) traditional legal agreement, and (2) smart contract that attempts to enforce it.
  • Oracle problem: Smart contracts cannot access real-world data directly. They depend on oracles (trusted data feeds), which reintroduces centralization and trust assumptions.

Best practice: Use smart contracts for automated execution of agreements, but pair with traditional legal contracts and dispute resolution mechanisms. Smart contracts work best for simple, objective conditions (temperature > 8C) rather than subjective judgments (product quality is “acceptable”).

140.2.1 What Smart Contracts Do

Think of smart contracts as if-then logic enforced by mathematics:

IF (temperature > 25C for > 1 hour)
THEN (trigger insurance claim for $10,000)
AND (record breach on ledger)
AND (notify all supply chain participants)

Unlike traditional contracts requiring lawyers and courts, smart contracts are:

  • Deterministic: Same inputs always produce same outputs
  • Tamper-proof: Code cannot be changed after deployment (on most platforms)
  • Self-executing: No human intervention required
  • Transparent: All parties see the contract logic

140.2.2 Example: Pharmaceutical Cold Chain

Scenario: A pharmaceutical company ships temperature-sensitive vaccines. Contract terms require temperatures between 2-8C. Breaches trigger penalties and insurance claims.

Traditional approach:

  1. Shipping container has temperature logger
  2. Upon arrival, recipient manually downloads logs
  3. If breach detected, they file claim with shipper
  4. Shipper disputes; negotiations or arbitration ensue
  5. Settlement takes weeks or months

Blockchain + Smart Contract approach:

  1. Shipping container has IoT temperature sensor + GPS
  2. Gateway device signs and submits readings to blockchain every 15 minutes
  3. Smart contract monitors temperature stream
  4. IF temperature exceeds 8C for >30 minutes:
    • Contract automatically transfers penalty payment from shipper to recipient
    • Triggers insurance claim with carrier
    • Notifies regulatory authorities if required
    • Records immutable evidence of breach
  5. Settlement is instant and undisputable
Sequence diagram showing smart contract execution flow for pharmaceutical cold chain monitoring. IoT temperature sensor sends 9C reading to gateway device (blockchain node), which signs with private key and submits to smart contract on blockchain. Contract checks condition if temperature exceeds 8C for over 30 minutes, detects breach, then automatically executes: deducts $10,000 penalty from shipper wallet, transfers $10,000 to recipient wallet, triggers insurance claim event, and records breach on ledger. Insurance system acknowledges claim. All actions are automatic, tamper-proof, and instant without human intervention.
Figure 140.3: Smart contract execution flow for pharmaceutical cold chain monitoring with automated penalty and insurance claim triggering.

140.2.3 Real-World Smart Contract Examples

Energy Trading: Residential solar panels sell excess energy to neighbors via smart contracts (Brooklyn Microgrid project).

Autonomous Vehicle Insurance: Usage-based insurance where smart contracts adjust premiums based on driving behavior recorded by vehicle sensors.

Equipment Maintenance: Industrial IoT sensors trigger maintenance payments when vibration signatures indicate bearing wear, automatically compensating service providers.

140.3 Architectural Patterns for IoT-Blockchain Integration

Time: ~15 min | Difficulty: Advanced | P04.C09.U05

The fundamental challenge: IoT devices cannot run full blockchain nodes. A Raspberry Pi has 1GB RAM and 16GB storage; an Ethereum full node requires 1TB storage and gigabytes of RAM. How do we bridge this gap?

140.3.1 Pattern 1: On-Chain vs Off-Chain Data

Problem: Storing all sensor data on-chain is prohibitively expensive and slow.

Solution: Hybrid approach: - Off-chain: Store full sensor data in traditional database (IPFS, cloud storage, local database) - On-chain: Store cryptographic hash of data

This provides: - Verification: Anyone can hash the off-chain data and compare to on-chain hash - Immutability: Changing off-chain data changes its hash, exposing tampering - Efficiency: Only 32-byte hash stored on expensive blockchain

Example:

Sensor reading: {temp: 23.5, humidity: 65, timestamp: 1638360000, device_id: "sensor_42"}
SHA-256 hash: 0x8f3b2c1d...  <-- This goes on blockchain
Full data stored in IPFS or database
Hybrid on-chain/off-chain architecture diagram showing four layers. IoT device layer contains temperature sensor, GPS tracker, and humidity sensor. These feed into gateway layer with IoT gateway performing aggregation and signing. Gateway splits data flow to storage layer: full sensor data goes to off-chain storage (IPFS/database) while only cryptographic hashes (32 bytes each) go to blockchain for efficiency. Verification process shows user/auditor retrieving full data from off-chain storage and hash from blockchain, computing hash of retrieved data, and comparing hashes--match indicates valid data, mismatch indicates tampering. This architecture provides tamper-proof verification without blockchain scalability limitations.
Figure 140.4: Hybrid on-chain/off-chain architecture: full data stored off-chain, cryptographic hashes on blockchain for tamper-proof verification.

Geometric visualization of blockchain consensus mechanisms showing multiple validator nodes arranged in a network pattern, each maintaining synchronized ledger copies, with arrows indicating message passing for Byzantine fault-tolerant consensus, demonstrating how distributed agreement is reached without central authority through cryptographic voting and verification protocols

Blockchain consensus mechanism for IoT networks
Figure 140.5: Consensus mechanisms are the heart of blockchain security. In IoT applications, lightweight consensus protocols like Practical Byzantine Fault Tolerance (PBFT) enable faster transaction finality compared to Proof-of-Work, making them suitable for time-sensitive sensor data validation and smart contract execution.

140.3.2 Pattern 2: IoT Gateway as Blockchain Node

Problem: Individual IoT devices lack resources to participate in blockchain consensus.

Solution: Deploy gateway devices that: - Aggregate data from many IoT devices - Run full or light blockchain nodes - Sign and submit transactions on behalf of devices - Handle blockchain communication complexity

Architecture:

[IoT Devices] --BLE/Zigbee--> [Gateway] --Ethernet/LTE--> [Blockchain Network]
    ^                             ^
  Lightweight               Full/Light Node
  (kB memory)              (GB memory, wallet)

Example: A smart building has 500 sensors. Instead of each sensor interacting with blockchain, a single gateway collects readings, batches them, and submits one transaction representing all 500 sensors every 15 minutes.

140.3.3 Pattern 3: Periodic Anchoring vs Real-Time

Real-time: Every sensor reading triggers blockchain transaction - Cost: High (gas fees per transaction) - Latency: Slow (block confirmation time) - Suitable for: Critical events only (equipment failure, security breach)

Periodic anchoring: Batch many readings, compute Merkle root, submit root to blockchain - Cost: Low (one transaction per batch) - Latency: Acceptable (delayed verification) - Suitable for: Regular monitoring data

Example: A fleet of 1,000 delivery trucks with GPS trackers: - Real-time: Log every location update to blockchain = 1,000 vehicles x 60 updates/hour = 60,000 TPS (impossible) - Periodic: Every 15 minutes, compute Merkle root of all updates, submit one transaction = 4 transactions/hour (feasible)

140.3.4 Pattern 4: Lightweight Verification (SPV)

Simplified Payment Verification allows resource-constrained devices to verify transactions without downloading entire blockchain.

How it works:

  1. Device stores only block headers (~80 bytes each)
  2. To verify a transaction, device requests Merkle proof from full node
  3. Device checks proof against header–confirms transaction is in blockchain

Trade-off:

  • Pro: Minimal storage (10 years of Bitcoin headers = ~40MB)
  • Con: Trusts full nodes to provide honest Merkle proofs (acceptable in many scenarios)

140.4 Understanding Check: Cold Chain Design Challenge

You’re designing a global pharmaceutical cold chain system for COVID-19 vaccine distribution. Requirements:

  • Scale: 10,000 shipments per day
  • Sensors: Temperature logger recording every 1 minute
  • Compliance: FDA requires complete temperature history for every shipment
  • Stakeholders: Manufacturers, airlines, distributors, hospitals, regulators (all need access)
  • Critical: Temperature breaches must trigger immediate alerts

Questions:

  1. Can you store all temperature readings directly on blockchain?
    • Calculate: 10,000 shipments x 1,440 readings/day x 365 days = ?
    • Compare to blockchain capacity
  2. Design an appropriate on-chain/off-chain strategy
    • What goes on-chain?
    • What stays off-chain?
    • How do you ensure data integrity?
  3. Choose blockchain type (public, private, IoT-optimized)
    • Justify your choice based on requirements
  4. Design smart contract for breach handling
    • What are trigger conditions?
    • What automated actions should occur?
    • How to handle false positives (sensor malfunction)?

Solutions:

1. Direct on-chain storage calculation:

  • Daily readings: 10,000 x 1,440 = 14.4 million readings/day
  • Required TPS: 14.4M / 86,400 seconds = ~167 TPS
  • Storage per reading: ~100 bytes (timestamp, temp, sensor_id, signature)
  • Daily storage: 14.4M x 100 bytes = 1.44 GB/day
  • Annual storage: 525 GB/year

What’s the actual storage burden of on-chain sensor data? Let’s calculate the exact cost for the pharmaceutical cold chain:

For 10,000 shipments with 1-minute temperature sampling:

  • Daily readings: \[10{,}000 \text{ shipments} \times 1{,}440 \frac{\text{readings}}{\text{day}} = 14.4 \text{ million readings/day}\]

  • Required blockchain throughput: \[\text{TPS} = \frac{14{,}400{,}000}{86{,}400 \text{ sec}} = 167 \text{ TPS}\]

  • Storage growth (at 100 bytes/reading): \[\text{Daily} = 14.4M \times 100 = 1.44 \text{ GB/day} \quad \text{Annual} = 525 \text{ GB/year}\]

  • Ethereum gas cost (at \(1/transaction):\)\(\text{Daily cost} = 14.4M \times \$1 = \$14.4 \text{ million/day}\)$

The hybrid approach (hourly hashes instead of raw readings) achieves 225,000× cost reduction while maintaining tamper-proof verification. This demonstrates why on-chain/off-chain architecture isn’t optional – it’s economically essential.

Verdict: Storing all readings on-chain is: - Technically challenging (requires 167 TPS sustained–possible with private blockchain, not public) - Economically prohibitive (Ethereum gas costs would be millions of dollars per day) - Unnecessary (full granularity not needed on immutable ledger)

2. Recommended on-chain/off-chain strategy:

Off-chain (stored in IPFS or cloud database): - Full granular temperature readings (every 1 minute) - GPS coordinates and timestamps - Sensor calibration data - Photos of packaging condition

On-chain (stored on blockchain): - Shipment initialization (batch ID, origin, destination, temperature range) - Merkle root of hourly temperature batches (60 readings -> 1 hash) - Breach events (timestamp, duration, severity) - Chain of custody transfers (manufacturer -> shipper -> distributor -> hospital) - Regulatory certifications and approvals

Integrity mechanism:

  • Every hour, IoT gateway computes Merkle tree of 60 temperature readings
  • Merkle root (32 bytes) submitted to blockchain
  • Anyone can verify data by: (1) requesting off-chain readings, (2) computing Merkle root, (3) comparing to on-chain root
  • Tampering with off-chain data invalidates Merkle proof

Benefits:

  • Reduces on-chain transactions from 14.4M/day to 240K/day (60x reduction)
  • Blockchain storage from 1.44 GB/day to 7.5 MB/day (200x reduction)
  • Maintains tamper-proof verification
  • Full audit trail available when needed

3. Blockchain type selection:

Recommended: Private/Consortium Blockchain (Hyperledger Fabric)

Justification:

  • Known participants: Pharmaceutical companies, logistics providers, hospitals, FDA
  • Performance: Need ~3 TPS for hourly anchoring (well within Fabric’s 10,000+ TPS)
  • Privacy: Confidential business data (pricing, quantities) must be restricted–Fabric supports channels
  • Compliance: HIPAA, FDA CFR 21 Part 11 require access controls and audit trails–easier with permissioned blockchain
  • Cost: Private blockchain avoids gas fees (critical for economically sustainable operation)
  • Governance: Consortium of pharmaceutical companies + regulators can jointly manage network

Why not public blockchain?:

  • Too slow (Ethereum: 15 TPS insufficient for global scale)
  • Too expensive (gas fees make micropayments for each shipment economically unviable)
  • Privacy issues (public transparency exposes confidential business data)

Why not IOTA/DAG:

  • Less mature ecosystem for enterprise use
  • Governance model unclear for regulated industry
  • Hyperledger has better enterprise tooling and support

4. Smart contract design for temperature breach:

// Pseudocode for pharmaceutical cold chain smart contract
contract VaccineShipment {
    struct Shipment {
        bytes32 batchId;
        address manufacturer;
        address currentCustodian;
        uint256 startTime;
        int8 minTemp;  // 2C
        int8 maxTemp;  // 8C
        uint8 maxBreachDuration;  // 30 minutes
        bool breached;
    }

    mapping(bytes32 => Shipment) public shipments;

    event TemperatureReading(bytes32 indexed batchId, int8 temp, uint256 timestamp);
    event BreachDetected(bytes32 indexed batchId, int8 temp, uint256 duration);
    event ShipmentCompromised(bytes32 indexed batchId);

    // Initialize shipment
    function createShipment(bytes32 batchId, address manufacturer, int8 minTemp, int8 maxTemp) public {
        shipments[batchId] = Shipment(batchId, manufacturer, manufacturer, block.timestamp, minTemp, maxTemp, 30, false);
    }

    // Submit temperature reading (called by IoT gateway with signed data)
    function submitReading(bytes32 batchId, int8 temperature, uint256 timestamp, bytes memory signature) public {
        require(verifySignature(batchId, temperature, timestamp, signature), "Invalid signature");

        Shipment storage s = shipments[batchId];
        emit TemperatureReading(batchId, temperature, timestamp);

        // Check if temperature is out of range
        if (temperature < s.minTemp || temperature > s.maxTemp) {
            emit BreachDetected(batchId, temperature, timestamp - s.lastBreachTime);

            // If breach duration exceeds threshold, mark shipment as compromised
            if (timestamp - s.lastBreachTime > s.maxBreachDuration * 60) {
                s.breached = true;
                emit ShipmentCompromised(batchId);

                // Trigger automated actions
                notifyStakeholders(batchId);
                triggerInsuranceClaim(batchId);
                alertRegulatoryAuthority(batchId);
            }
        }
    }

    // Transfer custody (manufacturer -> shipper -> distributor -> hospital)
    function transferCustody(bytes32 batchId, address newCustodian) public {
        Shipment storage s = shipments[batchId];
        require(msg.sender == s.currentCustodian, "Only current custodian can transfer");
        require(!s.breached, "Cannot transfer compromised shipment");

        s.currentCustodian = newCustodian;
    }

    // Handle false positives: Allow authorized party to dispute breach (with evidence)
    function disputeBreach(bytes32 batchId, bytes32 evidenceHash, string memory reason) public {
        require(isAuthorizedDisputer(msg.sender), "Unauthorized");
        // Log dispute for human review; may require multi-sig to clear breach flag
    }
}

Key features:

  1. Trigger conditions:
    • Temperature outside 2-8C range
    • Breach duration >30 minutes (configurable)
    • Multiple consecutive breaches (pattern detection)
  2. Automated actions:
    • Emit blockchain events (permanent record)
    • Notify all stakeholders via off-chain notification service (email, SMS)
    • Trigger insurance claim with carrier
    • Alert FDA or relevant regulatory authority
    • Mark shipment as compromised (preventing further custody transfers)
  3. False positive handling:
    • Require sensor signature verification (prevents fake readings)
    • Allow authorized parties to dispute breaches with evidence
    • Use multi-signature approval for clearing critical flags
    • Store calibration certificates on-chain; expired calibration flags readings as suspect
    • Machine learning model (off-chain) analyzes temperature patterns to detect sensor malfunction vs genuine breach
  4. Additional safeguards:
    • Chain of custody: Only current custodian can transfer to next party
    • Access control: Only authorized IoT gateways can submit readings (whitelist public keys)
    • Time-bound validity: Shipments have expiration; readings after expiration ignored
    • Redundancy: Require 2-3 independent sensors per shipment; breach only if majority agree

Result: This design provides tamper-proof audit trail, automated compliance, rapid breach response, while remaining economically and technically feasible at global scale.

Common Mistake: Writing Smart Contracts Without Fail-Safes for IoT Sensor Failures

The Mistake: A pharmaceutical cold chain smart contract automatically triggers a $10,000 penalty payment when temperature exceeds 8°C for 30 minutes. After 6 months of operation, legitimate shipments are penalized because sensor batteries die mid-transit, causing false “temperature breach” readings (sensor reads 0°C or nonsensical values that cross thresholds). The company pays $60,000 in wrongful penalties before discovering the issue.

Why It Happens: Smart contract developers focus on the happy path (sensor works correctly, temperature stays in range) and fail to account for IoT reality – sensors fail, batteries die, radios drop packets, and firmware has bugs. Traditional software allows post-facto corrections; immutable smart contracts do not. A sensor sending 150°C (impossible for vaccine storage) is clearly a malfunction, but a naive contract treats it as a legitimate breach.

Real-World Consequences:

  • False positives destroy trust: After 3 wrongful penalties, shippers refuse to use the system
  • No “undo” button: Payments are irreversible; recovering funds requires legal action outside the blockchain
  • Reputation damage: Media reports “blockchain system penalizes working refrigerators”
  • Financial losses: Company pays for both wrongful penalties AND manual verification of every shipment

The Fix - Implement Multi-Layer Fail-Safes:

1. Sensor-Level Validation (Gateway/Oracle):

// Gateway validates sensor readings BEFORE submitting to blockchain
function validateReading(int8 temp) pure returns (bool) {
    // Reject physically impossible values
    if (temp < -50 || temp > 50) return false;  // Vaccines never stored below -50°C or above 50°C

    // Reject sensor error codes
    if (temp == 0 && lastReading == 0) return false;  // Two consecutive zeros = sensor failure

    // Reject sudden jumps (sensor malfunction indicator)
    if (abs(temp - lastReading) > 20) return false;  // 20°C jump in 15 minutes = sensor error

    return true;
}

2. Smart Contract Sanity Checks:

event TemperatureReading(bytes32 shipmentId, int8 temp, uint256 timestamp);
event SensorMalfunction(bytes32 shipmentId, string reason);
event BreachDisputed(bytes32 shipmentId, address disputedBy, string evidence);

function submitReading(bytes32 shipmentId, int8 temp, uint256 timestamp, bytes memory signature) public {
    require(verifySignature(shipmentId, temp, timestamp, signature), "Invalid signature");

    Shipment storage s = shipments[shipmentId];

    // Sanity check: Reading too old (clock sync issue or replay attack)
    if (timestamp < s.lastReadingTime) {
        emit SensorMalfunction(shipmentId, "Timestamp older than last reading");
        return;  // Don't trigger breach on suspicious data
    }

    // Sanity check: Physically impossible temperature
    if (temp < -50 || temp > 50) {
        emit SensorMalfunction(shipmentId, "Temperature outside physical range");
        s.sensorHealthScore -= 10;  // Decrement sensor reliability score
        return;
    }

    // Sanity check: Two consecutive identical readings (sensor stuck)
    if (temp == s.lastTemp && timestamp - s.lastReadingTime < 60 * 60) {
        emit SensorMalfunction(shipmentId, "Duplicate reading - sensor may be stuck");
        s.sensorHealthScore -= 5;
        return;
    }

    emit TemperatureReading(shipmentId, temp, timestamp);
    s.lastTemp = temp;
    s.lastReadingTime = timestamp;

    // Only trigger breach logic if temperature is out of range AND sensor health is good
    if ((temp < s.minTemp || temp > s.maxTemp) && s.sensorHealthScore > 50) {
        handleBreach(shipmentId, temp, timestamp);
    }
}

3. Dispute Mechanism (Human Override):

function disputeBreach(bytes32 shipmentId, string memory evidenceHash) public {
    require(isAuthorizedDisputer(msg.sender), "Unauthorized");
    Shipment storage s = shipments[shipmentId];
    require(s.breached, "No breach to dispute");
    require(block.timestamp < s.breachTime + 7 days, "Dispute window expired");

    emit BreachDisputed(shipmentId, msg.sender, evidenceHash);
    s.disputed = true;
    s.evidenceHash = evidenceHash;

    // Pause penalty payment until multi-sig resolves dispute
    s.penaltyOnHold = true;
}

function resolveDispute(bytes32 shipmentId, bool breachConfirmed) public {
    require(isMultiSigApprover(msg.sender), "Requires multi-sig approval");
    Shipment storage s = shipments[shipmentId];
    require(s.disputed, "No active dispute");

    if (breachConfirmed) {
        // Legitimate breach - proceed with penalty
        executePenalty(shipmentId);
    } else {
        // False positive - clear breach flag, refund if already paid
        s.breached = false;
        if (s.penaltyPaid) {
            refundPenalty(shipmentId);
        }
    }
    s.disputed = false;
}

Best Practices Summary:

  1. Validate at gateway: Filter out sensor errors before data reaches blockchain (cheapest)
  2. Sanity checks in contract: Reject physically impossible or suspicious values
  3. Sensor health scoring: Track reliability; ignore readings from failing sensors
  4. Human dispute mechanism: Allow authorized parties to flag false positives within 7-day window
  5. Redundant sensors: Require 2-of-3 agreement before triggering high-value actions
  6. Graduated penalties: Warn before penalizing; escalate slowly
  7. Comprehensive logging: Emit events for ALL decision points to enable forensic analysis

Verification Checklist:

140.5 Gas Cost and Anchoring Strategy Calculator

Use this calculator to compare the cost of storing all sensor data on-chain versus using Merkle root anchoring.

Key Concepts

  • Smart Contract: Self-executing code deployed on a blockchain that automatically enforces agreement terms when predefined conditions are met, without requiring trusted intermediaries
  • Solidity: The primary programming language for Ethereum smart contracts, a statically-typed language with syntax similar to JavaScript designed specifically for EVM execution
  • Ethereum Virtual Machine (EVM): The sandboxed runtime environment that executes smart contract bytecode identically across all Ethereum nodes, ensuring deterministic execution without external dependencies
  • Oracle: A trusted external data feed that bridges off-chain real-world information (temperature readings, API responses, IoT sensor data) to smart contracts that cannot directly access the internet
  • Gas: The unit measuring computational effort in Ethereum smart contract execution; users pay gas fees (ETH) to compensate miners, creating an economic barrier against infinite loops and spam
  • Chaincode: The Hyperledger Fabric equivalent of a smart contract, written in Go, JavaScript, or Java, defining business logic executed within the fabric peer’s container environment
  • Event-Driven Automation: Smart contract architecture where IoT sensor readings trigger contract execution — e.g., temperature exceeding threshold automatically releases insurance payment — without human approval

Common Pitfalls

Smart contracts cannot call external APIs or access sensor data directly — the EVM has no network access. Developers who try to fetch sensor readings inside contracts get compilation errors. Use a blockchain oracle (Chainlink, Band Protocol) to feed verified external data.

Solidity prior to version 0.8 did not automatically check for integer overflow. A calculation like uint8 x = 255 + 1 silently wraps to 0, enabling attackers to drain payment contracts. Use SafeMath or Solidity 0.8+ for all arithmetic.

Using block.timestamp in smart contracts for time-sensitive IoT triggers. Miners can manipulate block timestamps by ±30 seconds. For precise timing in control systems, use oracle-provided timestamps or block numbers with known block times.

Storing sensitive IoT calibration parameters, device keys, or proprietary sensor data as contract state variables. All Ethereum state is publicly readable regardless of access modifiers. Encrypt sensitive data off-chain; store only hashes on-chain.

Emitting a blockchain event for every sensor reading from 10,000 devices. Smart contract storage and event logs are permanent and gas-expensive. Batch readings or store only threshold-crossing events.

140.6 Summary

This chapter covered smart contracts for IoT automation and architectural patterns for integrating blockchain with resource-constrained devices.

Key Takeaways:

  1. Smart contracts are deterministic, self-executing programs that enforce if-then agreements on blockchain without intermediaries
  2. The oracle problem is the fundamental challenge: smart contracts cannot access external sensor data and need trusted oracles to bridge the gap
  3. Pattern 1 – On-chain/Off-chain: Store full data off-chain, only cryptographic hashes on-chain (reduces cost by 99.9%)
  4. Pattern 2 – Gateway as Node: Aggregate IoT device data through gateways that run blockchain nodes on behalf of constrained devices
  5. Pattern 3 – Periodic Anchoring: Batch sensor readings into Merkle trees and submit roots periodically instead of per-reading (reduces transactions by 60-1000x)
  6. Pattern 4 – Lightweight Verification (SPV): Resource-constrained devices verify transactions using block headers and Merkle proofs without downloading the full chain
Test Your Understanding

Question 1: A pharmaceutical cold chain smart contract needs to check if the temperature inside a shipping container exceeds 8C. Why can’t the smart contract simply read the temperature sensor directly?

  1. Smart contracts do not support floating-point arithmetic
  2. Temperature sensors are too inaccurate for blockchain use
  3. Smart contracts are deterministic and cannot access external data – they need an oracle to bring sensor readings on-chain
  4. Blockchain networks block all IoT device connections for security

c) The oracle problem. Smart contracts must produce identical results on every blockchain node to maintain consensus. If a contract tried to read an external sensor, different nodes might get different values at different times, breaking consensus. Oracles solve this by having a trusted gateway read the sensor, sign the data, and submit it as a blockchain transaction that all nodes can process identically.

Question 2: A fleet of 1,000 delivery trucks reports GPS location every second. The company wants blockchain-based proof of delivery. What is the most cost-effective architectural pattern?

  1. Store every GPS reading directly on Ethereum (1,000 TPS)
  2. Use periodic anchoring: batch 15 minutes of readings, compute Merkle root, submit one transaction
  3. Run a full Ethereum node on each truck’s onboard computer
  4. Store GPS data in a centralized database with no blockchain involvement

b) Periodic anchoring with Merkle roots. Storing every reading (1,000 TPS) on Ethereum is technically impossible (15 TPS limit) and would cost millions in gas fees. Periodic anchoring batches 900,000 readings per 15-minute window into a single Merkle root, requiring only 4 transactions per hour – well within capacity and economically feasible. This provides tamper-proof verification while reducing on-chain transactions by 225,000x.

140.7 Knowledge Check

140.8 What’s Next?

You’ve learned how smart contracts automate IoT agreements and how architectural patterns bridge resource-constrained devices with blockchain networks. Continue exploring:

Next Topic Description
Blockchain Limitations and Implementations Scalability challenges and real-world blockchain-IoT deployments
Blockchain Interactive Lab Build a working blockchain on ESP32 with hash chains and mining
Blockchain Fundamentals for IoT Review blockchain types and public vs private selection