Docs›WASM Guides›Inventory Sync
WASM Module Guide

Inventory Sync Module

This guide shows how to decrement inventory counts atomically. In a CRDT mesh network, local subtractions sync across all peer edge nodes automatically.

#Atomic Subtraction

src/lib.rs
#![no_std]

use qos_sdk::{state, output};

#[no_mangle]
pub extern "C" fn run() -> i32 {
    let sku_key = "inventory:sku_beer";
    
    if let Some(val) = state::get(sku_key) {
        if val.len() == 4 {
            let mut buf = [0u8; 4];
            buf.copy_from_slice(&val);
            let mut stock = u32::from_le_bytes(buf);
            
            if stock > 0 {
                stock -= 1;
                state::set(sku_key, &stock.to_le_bytes()).unwrap();
                output::write(b"{\"status\":\"success\",\"msg\":\"Dispensing...\"}");
                return 0;
            } else {
                output::write(b"{\"status\":\"error\",\"msg\":\"Out of stock!\"}");
                return 1;
            }
        }
    }
    
    output::write(b"{\"status\":\"error\",\"msg\":\"SKU not found\"}");
    1
}