CoCo Blockchain

Crypto that works for real businesses.
Near-zero fees. Real-time inventory. No complexity.

118 Tests Passing 105+ Extrinsics 16 Pallets Smart Contracts Solana Bridge v0.9

Overview

The French Butcher Problem: A butcher in France pays $9,000/year in card processing fees at 5% per transaction — that's half his monthly rent, gone to Visa and Mastercard. Small merchants everywhere are trapped: accept cards and bleed margin, or refuse cards and lose customers. Crypto should fix this. Instead it adds confusion: wallets, gas fees, seed phrases, exchanges. CoCo exists to make crypto invisible — a payment rail that merchants don't have to think about, with fees near zero, inventory tracked in real time, and barcode scanning that just works at checkout.

CoCo is a Substrate-based blockchain protocol purpose-built for real businesses. It creates a programmable economic layer where merchants can issue tokens, track inventory, manage digital rights, and accept payments — all without understanding blockchain. The system hides behind familiar tools: a barcode scanner, a dashboard, a POS terminal.

Any organization can issue custom programmable tokens — loyalty points, employee compensation, asset-backed credits, or micro-finance instruments — that can be exchanged across a unified ecosystem with near-zero fees (0% internal, 0.25% external vs. 2-5% card networks). The protocol extends this with a Product Rights Management (PRM) system: physical products are tokenized as NFTs carrying DRM flags that enable pay-as-you-go, lease-to-own, subscriptions, and microtransaction-based feature unlocks.

Barcode scanning, real-time inventory analysis, and POS integration provide the physical-world bridge. The goal is not to build a crypto platform — it's to build a better payment and inventory system that happens to run on a blockchain.

Three-Layer Architecture

Layer 1
Programmable Economy
Tokens · Exchange · Yield
Layer 2
Product Rights Mgmt
DRM · Micro-finance · Locks
Layer 3
Physical Bridge
Barcodes · Realtime Inventory · POS

Key Differentiators (v0.6)

CapabilityCoCoTraditional
Payment Fees (retail)0.25%Visa/MC 2-5%
B2B / Supplier Payment0% internal2-3% card or $25 wire
Settlement Time6 seconds1-3 business days
ChargebacksNoneCostly & frequent
Programmable TokensCustom sub-tokens + smart contractsSiloed loyalty programs
DRM EnforcementOn-chain lock/unlock/repossessNo enforcement mechanism
Micro-financePAYG, lease-to-own, subscriptions, rentalsCredit cards (2-3% fees)
Supply Chain + InventoryReal-time, on-chain, auto-reorder from suppliersSiloed, no cross-org data
Inter-Ecosystem Trade0% between any CoCo tokensVisa/Mastercard 2-3%
Merchant ComplexityScan barcode → doneTerminal contract, PCI audit, chargeback risk

Fee Comparison: Retail Payment ($20 purchase)

ProcessorFee on $20Settlement
CoCo$0.056 seconds
Visa / Mastercard$0.50 – $0.901-2 days
MercadoPago QR$0.30 – $0.40Next day
MercadoPago Card$0.80 – $1.00Next day
PayPal$1.19Instant (holds apply)
Stripe$0.881-2 days

Fee Comparison: B2B / Supplier Payment ($1,000 invoice)

MethodFee on $1,000Settlement
CoCo (internal)$0.006 seconds
CoCo (border crossing)$2.506 seconds
Wire Transfer$25 – $50 flat1-3 days
Corporate Credit Card$20 – $30 (2-3%)1-2 days
Paper Check$5 – $10 + float5-10 days
ACH / SEPA~$0.502-3 days

0.25% border fee is still 10-24x cheaper than any card processor. Internal ecosystem movement is 0%. The only thing cheaper is cash — and cash doesn't give you inventory analytics, DRM enforcement, automated supplier ordering, or yield-bearing savings.

Architecture

System Diagram

┌─────────────────────────────────────────────────────────────────────┐
│                      CoCo Blockchain (Substrate)                    │
│                                                                     │
│  ┌────────────────────────────────────────────────────────────┐    │
│  │                    Runtime (FRAME) — 3 Layers              │    │
│  │                                                             │    │
│  │  LAYER 1: ECONOMIC ✦ BRIDGE                               │    │
│  │  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────────┐ │    │
│  │  │pallet-   │ │pallet-   │ │pallet-   │ │pallet-       │ │    │
│  │  │assets    │ │kyc       │ │rewards   │ │bridge 🆕     │ │    │
│  │  └──────────┘ └──────────┘ └──────────┘ └──────────────┘ │    │
│  │                                                             │    │
│  │  LAYER 2: PRODUCT RIGHTS MANAGEMENT                        │    │
│  │  ┌──────────────────┐ ┌────────────┐ ┌──────────────────┐ │    │
│  │  │pallet-product-nft│ │pallet-drm  │ │pallet-           │ │    │
│  │  │★ (digital twins) │ │(enforce)   │ │microfinance      │ │    │
│  │  └──────────────────┘ └────────────┘ └──────────────────┘ │    │
│  │                                                             │    │
│  │  LAYER 3: PHYSICAL BRIDGE ✦ REALTIME INVENTORY           │    │
│  │  ┌──────────┐ ┌──────────┐ ┌──────────┐                   │    │
│  │  │barcode   │ │inventory │ │POS       │                   │    │
│  │  │scanner   │ │analysis  │ │terminal  │                   │    │
│  │  └──────────┘ └──────────┘ └──────────┘                   │    │
│  │                                                             │    │
│  │  System: ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────┐ │    │
│  │          │balances  │ │timestamp │ │sudo      │ │grandpa│ │    │
│  │          └──────────┘ └──────────┘ └──────────┘ └──────┘ │    │
│  └────────────────────────────────────────────────────────────┘    │
│  Consensus: Aura (6s blocks) + Grandpa (fast finality)              │
└────────────────────────────────────────────────────────────────────┘
                          ↕
┌─────────────────────────┼──────────────────────────┐
│                         │                          │
│              ┌──────────▼──────────┐              │
│              │   Node.js Server    │              │
│              │  (REST API + WS)    │              │
│              └──────────┬──────────┘              │
│                         │                          │
│  ┌─────────────────┐  ┌───────────────────────┐  │
│  │ Web Apps        │  │   Mobile Apps         │  │
│  │ /login          │  │   Android Scanner     │  │
│  │ /admin          │  │   (Kotlin + ML Kit)   │  │
│  │ /dashboard      │  └───────────────────────┘  │
│  │ /marketplace    │                              │
│  │ /onboarding      │                              │
│  └─────────────────┘                              │
└──────────────────────────────────────────────────┘

Directory Structure

/home/nate/gemini/coco/
├── coco-substrate/          ★ Primary — Substrate blockchain
│   ├── node/                Node binary (CLI, RPC, chain spec)
│   ├── runtime/             All pallets configured
│   ├── pallets/             11 custom pallets + pallet-contracts
│   │   ├── product-nft/     ★ Core — product NFT + DRM (v0.5)
│   │   ├── kyc/             KYC provider network
│   │   ├── rewards/         Yield distribution + staking
│   │   └── ... (7 more)
│   ├── contracts/           Example ink! smart contracts (PAYG, Lease, Escrow)
│   ├── scripts/             Build & run utilities
│   └── docs/                Technical documentation
├── barcode/                 Scanner app + POS server
│   ├── app/                 Android app (Kotlin)
│   └── Server/              Node.js backend (Express, SQLite)
└── website/                 Public website and documentation

Pallet Reference

Product NFT Pallet — Complete Reference

The core pallet managing the full lifecycle of physical products as digital twins (NFTs). 17 extrinsics (0-16) + 8 DRM extrinsics (17-24), 14 storage maps, 26 events, 43 error codes.

Core Extrinsics (Call Index 0-16)

#ExtrinsicCall IndexAccessDescription
0register_company0KYC userRegister a brand/company
1deactivate_company1OwnerDeactivate own company
2activate_company2OwnerReactivate company
3mint_product3CompanyMint 1 product with GTIN+serial
4batch_mint_products4CompanyMint up to 1000 units
5transfer5OwnerTransfer custody + location
6sell_to_consumer6OwnerRetail sale + warranty
7authenticate_product7MfrMark authentic on-chain
8recall_product8MfrRecall product, block sale
9resolve_recall9MfrClose recall, EndOfLife
10register_product10OwnerAdd to consumer portfolio
11submit_warranty_claim11OwnerFile a warranty claim
12resolve_warranty_claim12MfrApprove/deny claim
13list_for_sale13OwnerList on marketplace
14buy_listing14AnyPurchase listed product
15cancel_listing15SellerRemove listing
16set_fee_config16RootSet fee rates & treasury collector

DRM Extrinsics — see drm tab (Call Index 17-24)

Storage Maps

NameKeyValueQuery
CompaniesAccountIdCompanyInfoOption
CompanyCountu32Value
NextProductIdu128Value
Productsu128ProductNFTOption
ProductLookup(GTIN, Serial)u128
Authenticationsu128AuthenticationRecordOption
RecalledProductsu128RecallInfoOption
ConsumerPortfolioAccountIdBoundedVec<u128>Value
WarrantyClaimCountu32Value
WarrantyClaims(u128, u32)WarrantyClaimOption
MarketListingsu128MarketListingOption
FeeConfigFeeConfigurationValue
ProductDRM 🆕u128DRMStatusOption

Key Structs

ProductNFT {
    product_id: u128,
    gtin: BoundedString,         // GTIN-14 (GS1 standard)
    serial_number: BoundedString, // Unit-level serial
    batch_id: BoundedString,
    name: BoundedString,
    category: ProductCategory,
    manufacturer: AccountId,
    manufactured_at: BlockNumber,
    current_owner: AccountId,
    status: ProductStatus,       // InProduction → ... → Sold/EndOfLife
    custody_chain: BoundedVec<CustodyRecord>,
    sale_price: Option<Balance>,
    warranty: Option<WarrantyInfo>,
    drm: Option<DRMStatus>,     // 🆕 v0.5: DRM config, state, features
}

DRMStatus {                     // 🆕 v0.5
    drm_config: DRMConfig { drm_enabled, enforcement_type, ... },
    drm_state: DRMState,        // Unlocked | Licensed | FeatureLocked | FullyLocked | Repossessed | Burned
    features: BoundedVec<FeatureLock>,
    enforcement_history: BoundedVec<EnforcementRecord>,
}

ProductStatus enum:
  InProduction | InTransit | AtDistributor | InStore |
  Sold | ListedForResale | Recalled | ReportedStolen | EndOfLife

RecallInfo {
    recalled_by: AccountId,
    recalled_at: BlockNumber,
    reason: BoundedString,
    action: RecallAction,  // Return | Dispose | Replace | Refund
    is_resolved: bool,
    resolved_at: Option<BlockNumber>,
}

MarketListing {
    seller: AccountId,
    price: Balance,
    listed_at: BlockNumber,
    royalty_percent: Option<u8>,  // Brand royalty on resale
}

DRM Enforcement Pallet 🆕

Product Rights Management system. Enables lock/unlock, feature-level gating, repossession, and emergency override on product NFTs. DRM config is set by the manufacturer at product level with consumer consent.

DRM Extrinsics (Call Index 17-24)

#ExtrinsicAccessDescription
17set_drm_configManufacturerEnable DRM on a product, set enforcement type
18lock_productFinancing EntityLock product (missed payment, default)
19unlock_productFinancing EntityRestore product access on payment
20unlock_featureAnyMicrotransaction: unlock single feature for N blocks
21lock_featureFinancing EntityLock a specific feature
22repossess_productManufacturerTransfer ownership back on final default
23burn_drmOwnerPermanently remove DRM (full ownership achieved)
24emergency_drm_overrideEmergency AuthTemporary unlock for safety/medical emergencies

DRM States

Unlocked → Licensed → FeatureLocked → FullyLocked → Repossessed → Burned
   ↑          |            |               |             |
   └──────────┴────────────┴───────────────┴─────────────┘
                    (payment restores access)

DRM Storage

NameKeyValueQuery
ProductDRMu128 (product_id)DRMStatus {config, state, features, history}Option

Use Cases

ModelExampleDRM Flow
Pay-as-you-goHeated seats: $0.50/24hFeatureLocked → unlock_feature(payment) → Timed unlock → Locked on expiry
Lease-to-ownSmartphone: $30/mo × 24Licensed → Each payment → ownership% → Full payment → Burned
SubscriptionPremium audio: $10/moLicensed → Missed payment → FeatureLocked → Payment → Unlocked
Micro-loan$200 loan on $500 phoneFullyLocked → Repayment → Unlocked → Default → Repossessed

ProductNFT Struct (v0.5 Update)

ProductNFT {
    ...
    drm: Option<DRMStatus>,  // NEW: DRM config, state, features
}

KYC Pallet

Manages KYC provider network and user address approvals. Used as a gate for company registration and staking.

Extrinsics

ExtrinsicAccessDescription
add_kyc_providerRootRegister a KYC provider
remove_kyc_providerRootRemove a KYC provider
activate_providerRootReactivate suspended provider
deactivate_providerRootSuspend a provider
approve_addressProviderKYC-approve a user
revoke_approvalProviderRevoke KYC approval

Public Query Functions

  • is_kyc_approved(address) — Check if address is KYC'd and active
  • get_kyc_approval(address) — Get approval details (expiry, provider)
  • is_kyc_provider(account) — Check if account is a KYC provider
  • get_all_approved_addresses() — List all active KYC addresses

Rental Contract Pallet 🆕

Apartment lease agreements with DRM-enforced access control. An apartment is a ProductNFT with DRM — on-time payment unlocks the door, late payment locks it. Security deposits held in escrow, released on completion or dispute.

Extrinsics

#ExtrinsicAccessDescription
0create_agreementLandlordSet terms: rent, deposit, grace period, late fee
1accept_agreementTenantPay deposit + first month → status Active
2pay_rentTenantMonthly payment. Restores DRM unlock if late.
3trigger_lateAnyoneAfter grace period. Locks DRM on property.
4serve_noticeLandlordStart eviction process.
5vacateTenant/LandlordEnd tenancy. Status → Terminated.
6release_depositTenant/LandlordRelease security deposit.

State Machine

Pending → Active → Late → EvictionProcess → Terminated → Completed
            ↑         ↓ (pay rent)               ↓
            └─────────┘                    release_deposit

Use Cases

  • Apartment rentals: monthly rent, security deposit, late fee enforcement
  • Smart apartment integration: DRM on digital door lock, automatic lock on late payment
  • Integration with micro-loans: use CoCo-K for rent payments, earn yield on deposit

Bridge Pallet 🆕

Cross-chain bridge for Solana, USDC, and USDT interoperability. Wrapped tokens on CoCo backed 1:1 by locked tokens on source chains. Relayer-based verification with replay protection.

Extrinsics

#ExtrinsicAccessDescription
0register_assetRootRegister bridged token (USDC/USDT/SOL)
1deactivate_assetRootStop new deposits
2depositRelayerComplete deposit (mint wrapped tokens)
3withdrawAnyInitiate withdrawal (burn wrapped tokens)
4complete_withdrawalRelayerConfirm unlock on source chain
5add_relayerRootAuthorize relayer
6remove_relayerRootRemove relayer
7set_pausedRootEmergency stop

Bridge Flow

Solana → CoCo: User locks tokens on Solana
               → Relayer detects event
               → Calls bridge.deposit() on CoCo
               → Wrapped tokens minted to recipient

CoCo → Solana: User calls bridge.withdraw() on CoCo
               → Wrapped tokens burned
               → Relayer detects WithdrawalInitiated event
               → Calls unlock_tokens() on Solana program
               → User receives native tokens on Solana

Supported Assets

AssetSolana AddressCoCo IDDecimals
USDCEPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v06
USDTEs9vMFrzaCERmJfrF4H2FYD4KCoNkY11McCe8BenwNYB16
SOL (w)So1111111111111111111111111111111111111111229

Security

  • Replay protection: source_tx_hash checked to prevent double-processing
  • Relayer gating: only authorized relayers can complete deposits/withdrawals
  • Emergency pause: root can halt all bridge operations
  • Solana Program Spec: docs/SOLANA_BRIDGE_SPEC.md
  • Relayer Script: scripts/bridge-relayer.js

Rewards Pallet

Treasury-managed yield distribution to KYC-approved stakers. Implements the CoCo-K staking model where real-world asset yield (USDC from T-bills) is distributed proportionally.

Extrinsics

ExtrinsicAccessDescription
set_treasury_managerRootAppoint treasury manager
remove_treasury_managerRootRemove treasury manager
activate_managerRootReactivate manager
deactivate_managerRootSuspend manager
distribute_rewardsManagerDistribute yield to KYC stakers
claim_rewardsStakerClaim pending rewards
stakeKYC userStake CoCo-K tokens
unstakeStakerUnstake tokens
set_distribution_scheduleRootConfigure interval/minimum

Reward Distribution Flow

Off-Chain Treasury (T-bills)
    ↓ Interest earned
Convert to USDC
    ↓ Bridge to CoCo chain
Treasury Manager calls distribute_rewards()
    ↓ Proportional to stake
KYC-Approved Stakers → Pending Rewards
    ↓ claim_rewards()
Withdrawn to staker's wallet

Smart Contracts Pallet 🆕

Wasm-based smart contracts via pallet-contracts. Deploy ink! contracts that call into the CoCo runtime via a custom chain extension. Contract deployment uses COCO for gas metering and storage deposits.

CoCo Chain Extension — 5 Functions

Contracts can query on-chain state through the CoCoExtension without paying cross-contract call fees:

IDFunctionInputOutputDescription
1is_kyc_approvedAccountIdboolCheck if an address is KYC-approved
2get_product_owneru128 (product_id)Option<AccountId>Get current owner of a product NFT
3is_product_authenticu128 (product_id)boolCheck manufacturer authentication status
4get_product_statusu128 (product_id)Option<u8>Get product lifecycle status enum
5is_drm_enabledu128 (product_id)boolCheck if DRM is active on a product

Example Contracts

ContractSourceDescription
PAYGcontracts/payg/Pay-as-you-go: purchase time blocks, vendor withdraws, KYC-gated access
Leasecontracts/lease/Lease-to-own: fixed installments, ownership transfer on full payment
Escrowcontracts/escrow/Time-locked escrow with mediator resolution, 10 COCO stake

Deploy Flow

# Install ink! toolchain
cargo install cargo-contract

# Build a contract
cd coco-substrate/contracts/payg
cargo contract build

# Upload via Polkadot.js → Developer → Contracts
# Instantiate with constructor args
# Call via extrinsic or UI

Storage Parameters

ParameterValue
Deposit per storage item1 COCO
Deposit per byte0.01 COCO
Max code length128 KB
Call stack depth5 frames
Max delegate actions2
KYC Integration: Contracts use the chain extension to verify KYC status at runtime. The PAYG contract checks is_kyc_approved before granting product access. No KYC check is needed for deployment — any user can deploy, but the contract logic enforces KYC where required.

API Reference

The Node.js server at barcode/Server/ provides REST API endpoints for both the POS system and blockchain operations.

Auth & POS Endpoints

MethodEndpointDescription
POST/api/auth/loginUsername + password → JWT token
POST/api/auth/registerCreate new user (admin required)
GET/api/auth/meGet current user from token
POST/api/auth/change-passwordChange password
POST/api/auth/logoutLogout (stateless, logs event)
GET/api/itemsList inventory items
POST/api/itemsAdd inventory item
GET/api/transactionsList POS transactions

Blockchain Onboarding Endpoints

EndpointBlockchain CallKey Parameters
/kyckyc.approveAddressaddress
/registerproductNft.registerCompanyname, seed
/assetassets.create + setMetadataassetId, name, symbol, seed
/mintproductNft.mintProductgtin, serialNumber, batchId, name, category, seed
/mint-batchproductNft.batchMintProductsgtin, batchId, name, category, quantity, seed
/transferproductNft.transferproductId, toAddress, newStatus, lat, lng, desc, action, seed
/saleproductNft.sellToConsumerproductId, consumerAddress, price, warrantyDuration, lat, lng, desc, seed
/authenticateproductNft.authenticateProductproductId, seed
/recallproductNft.recallProductproductId, reason, action, seed
/resolve-recallproductNft.resolveRecallproductId, seed
/register-productproductNft.registerProductproductId, seed
/warranty-claimproductNft.submitWarrantyClaimproductId, description, seed
/resolve-claimproductNft.resolveWarrantyClaimproductId, claimIndex, resolution, seed
/list-for-saleproductNft.listForSaleproductId, price, royaltyPercent, seed
/buy-listingproductNft.buyListingproductId, lat, lng, desc, seed
/cancel-listingproductNft.cancelListingproductId, seed
/set-drm 🆕productNft.setDrmConfigproductId, enforcementType, paymentTokenId, seed
/lock 🆕productNft.lockProductproductId, reason, seed
/unlock 🆕productNft.unlockProductproductId, seed
/unlock-feature 🆕productNft.unlockFeatureproductId, featureId, durationBlocks, seed
/lock-feature 🆕productNft.lockFeatureproductId, featureId, seed
/repossess 🆕productNft.repossessProductproductId, seed
/burn-drm 🆕productNft.burnDrmproductId, seed
/emergency-override 🆕productNft.emergencyDrmOverrideproductId, seed

Bridge Endpoints 🆕

EndpointBlockchain CallAccess
/api/bridge/register-assetbridge.registerAssetRoot
/api/bridge/deactivate-assetbridge.deactivateAssetRoot
/api/bridge/depositbridge.depositRelayer
/api/bridge/withdrawbridge.withdrawAny
/api/bridge/complete-withdrawalbridge.completeWithdrawalRelayer
/api/bridge/add-relayerbridge.addRelayerRoot
/api/bridge/remove-relayerbridge.removeRelayerRoot
/api/bridge/set-pausedbridge.setPausedRoot

Note: "seed" is the private key seed phrase for signing transactions. In production, this would use a wallet connection (Polkadot.js extension, mobile wallet) rather than raw seed input.

Web App Routes

RouteFileDescription
/loginlogin.htmlLogin/Register page 🆕
/adminadmin.htmlPOS Admin Dashboard
/dashboardcompany-dashboard.htmlCompany Dashboard
/marketplacemarketplace.htmlP2P Marketplace
/onboardingonboarding.htmlCompany Onboarding

Substrate Service (substrate.js)

// The Polkadot.js API client handles:
getApi()           — Connect to ws://127.0.0.1:9944
sendTransaction()  — Sign + submit + wait for inclusion + decode errors
getAlice()         — Get dev sudo key for KYC approval

Web Applications

🔐 Login & Auth 🆕

Login/Register page with JWT-based authentication for POS and admin access.

Features:
Username/password sign in · Admin-only registration · Token-based session management · Auto-redirect on expiry

→ Open Login

🖥️ Company Dashboard

Full-featured admin panel for companies to manage their CoCo operations.

Features:
Product inventory with search/filter · Single & batch minting · Supply chain transfers · Retail sales · Recall management · Warranty claim resolution · Product authentication · Company settings

→ Open Dashboard

🏪 P2P Marketplace

Browse and buy verified products listed for resale on the CoCo network.

Features:
Browse listings · Search & filter by category · View product details (authenticity, warranty) · Buy with wallet · List your own products · Cancel listings · Optional brand royalty on resale

→ Open Marketplace

📋 Onboarding Wizard

6-step onboarding flow for new companies: KYC → Register → Asset → Mint → Transfer → Sale

→ Open Onboarding

📱 POS Admin

Point-of-sale dashboard for inventory and transaction management.

→ Open POS Admin

📖 Scanner Integration Guide

Guide for integrating the Android barcode scanner app with the CoCo blockchain (wallet management, on-chain queries, transaction signing).

→ Read Guide

🛠️ Admin Script

Command-line tool for common operations: build, run node, test, check, start server, reset chain data, generate spec, build Docker.

./coco-substrate/scripts/admin.sh build
./coco-substrate/scripts/admin.sh run
./coco-substrate/scripts/admin.sh test nft

QR Code Standard

Every product on CoCo has a scannable QR code linking its physical form to its on-chain digital twin. The standard is defined in docs/QR_CODE_STANDARD.md.

URI Scheme

coco://product/{chain_id}/{product_id}?gtin={gtin}&serial={serial}&sig={signature}

Example

coco://product/0/0x00000000000000000000000000000001?gtin=00012345678905&serial=LV-2024-001234

Types

TypeUseSignature
Static QRPrinted on packaging, permanentNo (lookup only)
Dynamic QRApp-generated at POS/transferECDSA signature from owner

GS1 Digital Link Compatibility

GS1 Digital Link:  https://id.gs1.org/01/00012345678905/21/LV-2024-001234
CoCo Equivalent:   coco://product/0/0x01?gtin=00012345678905&serial=LV-2024-001234

Supported Barcode Formats (Scanner App)

UPC-A, UPC-E, EAN-13, EAN-8, Code 128, Code 39, Code 93, QR, Data Matrix, PDF417, Aztec, ITF, Codabar

Resolution Flow

User scans QR code → App extracts product_id from URI
  → Queries chain: Products(product_id)
  → Displays: authenticity, status, custody chain, warranty
  → If for sale: show purchase option
  → If owned by user: show manage options (list, claim warranty)

Installation / Runtime Guide

Beta Testnet: Full deployment instructions with validator setup, bridge configuration, and monitoring are in beta_instructions.md. This section covers building, configuring, and running the CoCo node.

System Requirements

ComponentDevelopmentTestnet Validator
CPU2 vCPU4 vCPU
RAM4 GB8 GB
Storage20 GB100 GB SSD
OSLinux / macOS / WSL2Ubuntu 22.04+

Prerequisites

# Rust toolchain
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
rustup target add wasm32-unknown-unknown

# System dependencies (Ubuntu)
apt install build-essential pkg-config libssl-dev clang

# Node.js 18+ (for server/relayer)
curl -fsSL https://deb.nodesource.com/setup_18.x | bash -
apt install nodejs

# Verify
rustc --version          # ≥ 1.77
node --version           # ≥ 18

Build from Source

cd coco-substrate

# Release build (recommended — 30-60 min)
./scripts/build.sh

# Or manually:
cargo build --release -p coco-substrate

# Binary at: ./target/release/coco-node
./target/release/coco-node --version

Development Chain (Single Node)

# Quick start
./scripts/run-dev.sh

# Or manual:
./target/release/coco-node --dev --tmp

# Connect: ws://127.0.0.1:9944
# Connect: https://polkadot.js.org/apps → Development → Local Node

Validator Setup (Testnet)

# 1. Generate chain spec
./target/release/coco-node build-spec --chain local --raw > testnet-spec.json

# 2. Generate validator keys
./target/release/coco-node key generate --scheme sr25519 --output-type json > aura-key.json
./target/release/coco-node key generate --scheme ed25519 --output-type json > grandpa-key.json

# 3. Insert keys
./target/release/coco-node key insert \
  --base-path /opt/coco/data/validator \
  --chain testnet-spec.json \
  --scheme sr25519 --key-type aura --suri "<seed>"

./target/release/coco-node key insert \
  --base-path /opt/coco/data/validator \
  --chain testnet-spec.json \
  --scheme ed25519 --key-type gran --suri "<seed>"

# 4. Start validator
./target/release/coco-node \
  --chain testnet-spec.json \
  --base-path /opt/coco/data/validator \
  --name "My Validator" --validator \
  --rpc-methods Safe --rpc-external --ws-external \
  --prometheus-external

# Ports: 30333 (P2P), 9933 (RPC), 9944 (WS), 9615 (metrics)
# See beta_instructions.md for multi-validator testnet setup

Server + Website

# Start Node.js server (POS + blockchain proxy)
cd barcode/Server
npm install
cp .env.example .env    # Edit SUBSTRATE_URL
npm start               # http://localhost:3000

# Web apps:
#   /admin      — POS dashboard
#   /dashboard  — Company inventory
#   /marketplace — P2P product listings
#   /onboarding — Company setup wizard
#   /login      — Authentication

Wallets

# Linux CLI wallet
cd barcode/linux-wallet
npm install
./wallet.js new           # Create wallet
./wallet.js balance       # Check balances
./wallet.js send <addr> <amt>  # Send COCO

# Android wallet
# Build: cd barcode && ./gradlew assembleDebug
# APK: app/build/outputs/apk/debug/app-debug.apk

Running the Bridge Relayer

# Environment
export COCO_WS_URL=ws://127.0.0.1:9944
export COCO_RELAYER_SEED=//RelayerRelayer

# Start relayer
node scripts/bridge-relayer.js

# Register bridged assets (as root)
curl -X POST http://localhost:3000/api/bridge/register-asset \
  -H "Content-Type: application/json" \
  -d '{
    "sourceChain":"Solana",
    "sourceTokenAddress":"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
    "name":"USD Coin","symbol":"USDC","decimals":6,
    "seed":"//Alice"
  }'
Test Results (Latest): All 75 tests passing across product-nft (47), micro-finance (16), and bridge (12) pallets.

Build & Test Guide

Build Blockchain

cd coco-substrate

# Quick build (recommended)
./scripts/build.sh

# Or manually:
cargo build --release -p coco-substrate-runtime
cargo build --release -p coco-substrate

# Binary: ./target/release/coco-node

Run Dev Chain

./scripts/run-dev.sh
# or: ./target/release/coco-node --dev

# RPC: ws://127.0.0.1:9944 | http://127.0.0.1:9933
# Connect: https://polkadot.js.org/apps → Development → Local Node

Run Tests

# Product NFT pallet (36 tests)
cargo test -p pallet-product-nft

# All pallets
cargo test -p pallet-kyc
cargo test -p pallet-rewards

Run Server + Onboarding Website

cd barcode/Server
npm install
cp .env.example .env         # Edit SUBSTRATE_URL if needed
npm start                    # http://localhost:3000

# Open: http://localhost:3000/onboarding.html

Build Android App

cd barcode
./gradlew assembleDebug
# APK: app/build/outputs/apk/debug/app-debug.apk
Test Results (Latest): cargo test -p pallet-product-nft -p pallet-micro-finance -p pallet-bridge → 75 passed, 0 failed.

Onboarding Flow

The company onboarding process is a 6-step flow documented in ONBOARDING.md and implemented in the website at /onboarding.html.

1. KYC
Approval
2. Company
Registration
3. Sub-Coin
Creation
4. Product
Minting
5. Supply Chain
Transfer
6. Retail
Sale

Step Details

StepBlockchain ActionWho
1. KYC Approvalkyc.approveAddressProvider (Alice in demo)
2. Register CompanyproductNft.registerCompanyKYC-approved user
3. Create Assetassets.create + setMetadataCompany
4. Mint ProductsproductNft.mintProduct / batchMintProductsCompany
5. Supply Chain TransferproductNft.transferCurrent owner
6. Retail SaleproductNft.sellToConsumerRetailer

Extended Consumer Flow

ActionBlockchain CallWhen
Register productproductNft.registerProductAfter purchase
Authenticate productproductNft.authenticateProductManufacturer only
Submit warranty claimproductNft.submitWarrantyClaimWithin warranty period
List for resaleproductNft.listForSaleOwner wants to sell
Buy from marketplaceproductNft.buyListingAny user
Cancel listingproductNft.cancelListingOriginal seller

Tokenomics & Network Parameters

Network Parameters

ParameterValueNotes
Block Time6 secondsAura slot duration
Finality~12-18 secondsGrandpa 2/3+ confirmation
Native TokenCOCO12 decimal places
Total Supply1,000,000,000Pre-mined at genesis
Existential Deposit500 plancksMinimum balance
Max Validators32Aura authorities
Max KYC Providers100Configurable
Max Stakers100,000CoCo-K stakers

Fee Model

Implemented: Fee routing is live in pallet-product-nft. Configurable rates via set_fee_config (sudo). Default rates shown below.
TransactionFeeRecipientStatus
Supply chain transfer0%FreeLive
Product minting0.1% (configurable)TreasuryLive
Retail sale0.25% (configurable)TreasuryLive
P2P resale0.25% (configurable)TreasuryLive
COCO transferNetwork feeValidatorsLive
Sub-token swap (same brand)0%FreePlanned
Sub-token to COCO0.25%TreasuryPlanned

How It Works

// Fee configuration (stored on-chain):
struct FeeConfiguration {
    fee_collector: AccountId,    // Treasury address
    sale_fee_rate: Permill,      // 0.25% default
    resale_fee_rate: Permill,    // 0.25% default
    mint_fee_rate: Permill,      // 0.1% default
}

// Example: Retail sale of 1000 COCO product
// Sale price: 1000 COCO
// Fee (0.25%): 2.5 COCO → transferred to TreasuryAccount
// Seller receives: 997.5 COCO (net)

Fees are automatically deducted during sell_to_consumer and buy_listing extrinsics via the charge_fee helper. The treasury account is set to Alice in dev mode and should be changed to a multi-sig treasury for production.

Dev Accounts

NameRoleCOCO
AliceSudo / Validator1,000,000
BobValidator / KYC Provider1,000,000
CharlieUser / Staker1,000,000
DaveUser1,000,000
EveUser1,000,000

Roadmap & Status

Legend

Done New Pending Planned

Phase 1 — Foundation Complete

Phase 2 — Product Features Complete

Phase 3a — DRM & Enforcement Complete

Phase 3e — Rental Contracts Complete

Phase 3c — Solana/USDC/USDT Bridge Complete

Phase 4 — Merchant Tools & Ecosystem Complete

Phase 5 — Smart Contracts Complete

Phase 6 — Infrastructure & Scale Remaining

Year 1 Targets (v0.5)

MetricTarget
Brands onboarded50
Products tokenized500M
Active consumers10M
Resale volume$100M
Microtransaction volume$10M
DRM-enabled products100K
Network revenue$90M