# Towards a neptune community crowdfunding system (CCS) design

**URL:** <https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206>\
**Category:** Development\
**Tags:** ccs, smart-contracts\
**Created:** [December 23, 2025, 7:11pm UTC](https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206 "2025-12-23T19:11:34Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![danda](https://talk.neptune.cash/letter_avatar_proxy/v4/letter/d/b19c9b/32.png) [@danda](https://talk.neptune.cash/u/danda)\
**Post date:** [December 23, 2025, 7:11pm UTC](https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206/1 "2025-12-23T19:11:35Z")

</div>

In the new year, I am considering changing my focus to work on building a CCS system for NeptuneCash. I agree with @LostInTranslation (and others) that this has worked very well for the Monero community and I believe that if done right (as a smart contract) it can have an outsized impact for NeptuneCash ecosystem and community as well. And for me personally, its an interesting opportunity to learn new things.

Some motivations:

1. it’s a nice test of the smart contract system.
2. helps raise funds to further develop neptune ecosystem
3. creates some circular economy flow (real value)
4. differentiates Neptune from Monero and other privacy coins.
5. will require creating new standards and functionality around smart contracts that will benefit other projects.
6. a CCS smart contract could likely be made reusable for general purpose crowdfunding situations, and perhaps (eventually) multi-token as well.

I should note that I have exactly zero experience building any kind of smart contract or crowdfunding system. What I do have is decades of building distributed systems of various kinds, authoring interfaces and standards, experience with some neptune-core internals, experience building the neptune-proton wallet UI, a friendly and helpful AI assistant, and a direct line of communication with the core devs that built triton-vm and other foundational tech of Neptune Cash.

As such, I spent a few hours working with an AI to evaluate the system and generate a rough design document. I took into account @aszepieniec’s comment [here](https://talk.neptune.cash/t/brainstorming-how-the-community-can-help/203/11) on the subject. I think my design deals with some issues he may not have thought deeply about yet, but I did incorporate one important concept to ensure public auditability of the treasury funds (amount).

I will also note that if too many obstacles present themselves or the project becomes too frustrating for whatever reason, I might well abandon it and go back to wallet work.

~~Finally, the design uses a “many utxo” approach in order to handle multiple donations (or votes) occurring during a single block, which would each try to use/spend the same input utxo holding smart-contract data.~~ If that problem could be solved in another way (without requiring a neptune-core plugin, that would simplify some things.)

edit: The LeaderLess (many utxo) design is being superceded by a [design](https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206/3) that uses a sort of plugin-template to consolidate and summarize utxos and reward composers for processing and including in their block tx.

All that follows is AI generated in collaboration, with only a light review.

* * *

# Preface

### The Architecture of Community Funding

To understand the design choices proposed in this document, it is helpful to first look at how community funding mechanisms function in other ecosystems—specifically Monero and Ethereum—and how Neptune Cash sits at the intersection of these paradigms.

**The Monero Model: A Hybrid Social System**  
The Monero Community Crowdfunding System (CCS) is the gold standard for privacy-coin funding, but it is important to note that **the CCS itself is not an on-chain mechanism.** It is a centralized web forum where proposals are discussed and milestones are tracked.

The only part of the Monero CCS that touches the blockchain is the payment process, which utilizes a multi-signature wallet. This introduces a significant trust requirement: the funds are held by a small group of trusted custodians. **If these key-holders were to collude, they could redirect the funds to any address,** bypassing the community’s intent and the milestones entirely. While this “social layer” has worked for Monero due to high trust, it remains a custodial system with a human-centric point of failure.

**The Ethereum Model: Automation and the ABI Precedent**  
If we were building this on Ethereum, the architecture would move the entire process onto the blockchain via a smart contract. Ethereum already utilizes a proven standard for contract interaction known as the **ABI (Application Binary Interface)**. The ABI tells the wallet or frontend exactly how to format data to talk to a specific contract.

While the ABI model is proven and successful, Ethereum’s implementation has a significant “off-chain” dependency: the ABI files themselves are usually stored on centralized servers or in developer repositories. If the ABI file is lost or inaccessible, the contract becomes a “black box.” Additionally, Ethereum’s account-based model typically compromises privacy, revealing donor identities and the flow of capital.

**The Neptune Cash Approach**  
Neptune Cash allows us to synthesize these approaches: the privacy of Monero with the programmable, non-custodial trust of Ethereum. By building the CCS as a native smart contract, we eliminate the need for trusted human custodians.

Our design improves upon the Ethereum model by being **on-chain first**. We propose to publish and retrieve the contract’s interface requirements directly from the Neptune blockchain. This ensures that the instructions on how to interact with the CCS are as decentralized and permanent as the funds themselves, allowing wallets to be truly autonomous.

* * *

### The Concurrency Challenge: Naive vs. Leaderless UTXOs

The most critical technical distinction in this design document is how we handle state contention in a private, ZK-driven environment.

In a **naive implementation** , a crowdfunding campaign might be represented by a single UTXO that holds the “pot” of funds. If multiple users try to donate simultaneously, they all attempt to consume that same UTXO. Only one transaction can succeed; the others will be rejected as double-spends. This creates a bottleneck where users must queue up to donate one by one—a poor experience for a global community.

This document proposes a **leaderless UTXO design**. Instead of a single “pot,” the contract logic allows the state to be fragmented across many UTXOs. Users interact with local fragments of the contract state, which can later be merged or proved correct mathematically without requiring a single, global lock. This allows for high concurrency, enabling hundreds of users to donate simultaneously without blocking one another.

* * *

### Toward a Universal Interface: Data-Driven Wallets

A major secondary goal of this project is to establish a standard for how wallets interact with complex smart contracts using a **Data-Driven Forms** standard.

Currently, if a wallet wants to support a specific dApp, developers often have to write custom code or “plugins.” This is the **“overlay” approach** : it requires the wallet to execute external code, which introduces significant security risks and maintenance burdens.

By using an on-chain ABI-like schema, the smart contract describes its own required inputs. A Neptune wallet (like Proton) can then read this data and dynamically generate the UI forms. Just as a web browser renders HTML without needing a specific “plugin” for every website, a Neptune wallet becomes **smart-contract agnostic**. It can facilitate complex crowdfunding, voting, or swaps securely, simply by interpreting the standard data provided by the contract on-chain.

* * *

### From “The CCS” to a Universal Crowdfunding Primitive

Finally, the Neptune CCS is being designed as a **universal crowdfunding primitive**.

While the Monero CCS is a bespoke platform designed specifically for Monero development, this smart contract is general-purpose. Because the logic is non-custodial and the interface is data-driven, this same contract can be deployed by anyone in the Neptune ecosystem. Whether it is a community member raising funds for a new block explorer, a non-profit seeking private donations, or a new project bootstrapping its initial development, this system provides a foundational building block for raising capital privately, securely, and without permission.

| Feature | Monero CCS | Ethereum DAO | **Neptune CCS (Proposed)** |
| --- | --- | --- | --- |
| **Escrow Type** | Custodial (Multi-sig) | Non-custodial (Code) | **Non-custodial (ZKP)** |
| **Privacy** | High (Sender) | Low (Transparent) | **High (Sender & Internal)** |
| **Auditability** | Social/Manual | On-chain (Public) | **On-chain (ZK-Audit)** |
| **Concurrency** | N/A (Manual) | High | **High (Leaderless UTXOs)** |
| **Wallet Integration** | Manual/Web | External ABI | **On-chain Data-Driven Forms** |

* * *

# **Neptune CCS & Trustless Covenant Standards**

**Technical Reference Manual – Version 1.0**  
**Architecture:** Leaderless Dual-Asset UTXO  
**Virtual Machine:** TritonVM (TASM)

* * *

## **Part I: Architectural Foundations**

### **1. Executive Overview**

The Neptune Community Crowdfunding System (CCS) is a protocol for trust-minimized, decentralized fundraising. It allows a community to pool funds for development goals without relying on a central custodian or a federated multisig set.

Unlike legacy implementations (e.g., Monero CCS) where “trust” is placed in human keyholders to act as escrows, the Neptune CCS places trust in **Cryptographic Covenants**. The release of funds is governed by a Turing-complete script (TritonVM) that mathematically enforces milestone conditions, voting thresholds, and refund rights.

This system introduces three foundational standards for the broader Neptune ecosystem:

1. **The Leaderless State Model:** Avoiding global state variables to enable infinite concurrency.
2. **The Dual-Asset Wrapper:** Using Type Scripts to enforce identity on native assets.
3. **The Manifest Standard:** An on-chain method for storing ABI/Interface definitions, enabling generic wallets to interact with custom covenants.

* * *

### **2. The Object Model**

The system does not exist as a single “Smart Contract” in the Ethereum sense. Instead, it is a collection of interacting **Unspent Transaction Outputs (UTXOs)**. We utilize the **Cell Model** , where every UTXO is composed of data, value, and two distinct scripts:

- **Lock Script:** Defines _who_ can spend the UTXO (Authorization).
- **Type Script:** Defines _what_ the UTXO is (Identity & State Rules).

#### **2.1 The Treasury UTXO (The “Project Pot”)**

This is the primary storage unit for the donated funds. It uses a **Dual-Asset Architecture** , meaning every Treasury UTXO contains both the native currency ($NPT) and a specialized Identity Token.

- **Native Asset:** `$NPT` (The Value).

- **Identity Asset:** `CCS_Identity_Token` (The Wrapper).

- _Purpose:_ This ensures that the NPT cannot be separated from the project’s logic. You cannot spend the NPT without satisfying the Type Script of the Identity Token.

- **Lock Script:** `CCS_Authority_Lock`

- _Role:_ **The Gatekeeper.**

- _Logic:_ Validates external inputs. It authorizes spending if 3-of-5 “Vote UTXOs” are present OR if a “Receipt UTXO” is being burned.

- **Type Script:** `CCS_Identity_Type`

- _Role:_ **The State Machine.**

- _Logic:_ Enforces invariants.

- “My total NPT value must be preserved unless a Payout is authorized.”

- “My Milestone Index can only increment by 1.”

- “I cannot be split or merged unless the Output preserves this specific Type Script.”

#### **2.2 The Receipt UTXO (The “Claim”)**

This token represents a donor’s refundable equity in the project. It decouples the donor’s identity from the funds.

- **Lock Script:** `Donor_Wallet_Lock`

- _Role:_ Ownership. (Controlled by Alice’s private key).

- **Type Script:** `CCS_Receipt_Type`

- _Role:_ **The Link.**

- _Minting Rule:_ “I can only be created if the transaction also outputs a valid `CCS_Identity_Token`.” (Proof of Donation).

- _Burning Rule:_ “I can only be destroyed if the transaction spends a `CCS_Identity_Token`.” (Proof of Refund).

#### **2.3 The Vote UTXO (The “Ballot”)**

A non-fungible, ephemeral UTXO used by Judges to signal approval asynchronously.

- **Lock Script:** `Ephemeral_Lock`

- _Role:_ Garbage Collection. Allows the UTXO to be cleaned up (burned) after the vote is counted.

- **Type Script:** `CCS_Judge_Type`

- _Role:_ **The Oracle.**

- _Minting Rule:_ “I can only be created if the transaction contains a valid STARK proof derived from a whitelisted Judge’s private key.”

* * *

### **3. The “Leaderless” State Architecture**

A critical design constraint of this system is **Concurrency**. If thousands of users donate simultaneously, they must not contend for a single “State Object.”

#### **3.1 The “Bag of Coins” Pattern**

We reject the “Global Counter” model (e.g., `Total_Raised = X`). Instead, the global state is the **aggregate sum** of all UTXOs bearing the `CCS_Identity_Type` hash.

- **Donation Flow:**
- User A creates `Treasury_UTXO_1` (100 NPT).
- User B creates `Treasury_UTXO_2` (500 NPT).
- _Result:_ Two independent UTXOs exist at the same script address. No locking or queuing is required.

#### **3.2 The “Introspective” Vote**

Governance does not update a variable on the Treasury UTXO. Instead, it relies on **Transaction Introspection**.

- **The Voting Process:**

1. Judges mint **Vote UTXOs** independently.
2. When the Payout is ready, the Developer constructs a **Sweep Transaction**.
3. **Inputs:** `Treasury_UTXO` + `Vote_UTXO_1` + `Vote_UTXO_2` + `Vote_UTXO_3`.

- **The Verification Logic:**  
The `CCS_Authority_Lock` on the Treasury UTXO executes a loop over its sibling inputs:

> _“I scan my input list. I count 3 distinct UTXOs that match the `CCS_Judge_Type` hash. Therefore, I authorize the release of funds to the Developer.”_

This stateless approach allows the voting process to be fully parallelized and gas-efficient, as the heavy cryptographic verification of the Judge’s signature happens only once (during the minting of the Vote UTXO), not during the Payout Sweep.

* * *

### **4. Cryptographic Primitives**

To implement the above architecture, the following Neptune-specific primitives are required:

- **Tip5 Hash Commitments:**  
Values in the Treasury are hidden using Tip5 hashing (STARK-friendly), not Elliptic Curve Pedersen commitments.  
`Commitment = Tip5::hash(Amount || Randomness)`
- **Transaction Introspection:**  
The ability of a running script to read the `Transaction` struct from the operational stack, granting visibility into Inputs, Outputs, and Witness data.
- **Recursive Covenants:**  
The `CCS_Identity_Type` script must verify that its _own_ Script Hash is present in the transaction outputs (preserving the covenant across transactions).

## **Part II: The Smart Contract Logic**

This section details the specific implementation of the system’s three core components using `tasm-lang` (Rust-to-TASM). We focus on how scripts leverage **Transaction Introspection** to enforce the “Multi-Coin” rules.

### **Chapter 3: The Treasury UTXO (The Vault)**

The Treasury is a high-assurance “Multi-Asset” object. It physically binds the native currency ($NPT) to the project’s identity, ensuring the money cannot move unless the project’s state machine is satisfied.

#### **3.1 Structure of the Treasury UTXO**

A valid Treasury UTXO must contain at least two coin types:

1. **Coin A (Value):** Native $NPT (Quantity: Variable).
2. **Coin B (Identity):** The `CCS_Identity_Token` (Quantity: 1).

By placing both scripts on the same UTXO, the Neptune consensus engine requires **both** the NPT conservation rules and the CCS identity rules to return `True` for any transaction involving these funds.

#### **3.2 The Identity Type Script (`CCS_Identity_Type`)**

This script provides the “State Machine” logic. It ensures that the project’s metadata (like the current Milestone Index) persists and evolves correctly.

**Key Logic: The State Ratchet**  
The script ensures that the project doesn’t just “disappear” or “reset.” It enforces that the Milestone Index is a monotonic counter.

```rust
// tasm-lang pseudo-code for CCS_Identity_Type
fn main() {
    let tx = tasm::load_current_transaction();
    let old_state = tasm::load_current_utxo_data(); // Current Milestone index

    // 1. Search outputs for the "descendant" Identity Token
    let mut matching_output_found = false;
    for output in tx.outputs {
        if output.has_type_script(SELF_HASH) {
            let new_state = output.decode_data::<CCSState>();

            // 2. Enforce the Milestone Ratchet:
            // State stays same (Donation/Merge) or increments by 1 (Payout)
            assert!(new_state.milestone >= old_state.milestone);
            assert!(new_state.milestone <= old_state.milestone + 1);

            matching_output_found = true;
            break;
        }
    }

    // If identity is being destroyed, it MUST be the final payout/liquidation
    if !matching_output_found {
        assert!(old_state.is_final_milestone(), "Illegal destruction of Project Identity");
    }
}

```

* * *

### **Chapter 4: The Authority Lock Script (`CCS_Authority_Lock`)**

While the Type Script manages _What_ the state is, the Lock Script manages _Who_ is allowed to change it. It implements the “Permission Layer.”

#### **4.1 The Introspection Loop (Stateless Counting)**

Because we use a **Leaderless Model** , we do not store a `vote_count` in a database. Instead, the Lock Script counts “Vote Tickets” (UTXOs) present in the current transaction’s input list.

**Logic Flow:**

1. **Initialize:** Set `vote_count = 0`.
2. **Iterate:** For every input in the transaction:

- Check if the input’s Type Script Hash matches the `CCS_Vote_Type`.
- Verify the vote metadata (e.g., it targets the correct Milestone).

1. **Authorization:** If `vote_count >= 3`, the script returns `True`, allowing the Treasury NPT to be spent to the Developer Address.

```rust
// tasm-lang logic for the Authority Lock
fn verify_spend() {
    let tx = tasm::load_current_transaction();
    let mut votes = 0;

    // Scan sibling inputs for valid vote tickets
    for input in tx.inputs {
        if input.type_script_hash() == VOTE_TICKET_HASH {
            // The Vote Type Script already verified the Judge's signature
            // upon creation. We simply count its presence here.
            votes += 1;
        }
    }

    // Alternative Branch: Check for Refund Claims
    let has_refund_receipt = tx.inputs.iter().any(|i| i.type_script_hash() == RECEIPT_HASH);

    // Permission is granted if threshold is met OR a donor is claiming a refund
    assert!(votes >= 3 || has_refund_receipt, "Unauthorized Spend: Missing Votes or Receipt");
}

```

* * *

### **Chapter 5: The Receipt Token (`CCS_Receipt_Type`)**

The Receipt Token is a separate coin type that acts as a “Refund Voucher.” It is minted into the donor’s wallet at the moment of donation.

#### **5.1 Minting Rules (Donation Binding)**

The Receipt Script uses **Output Introspection** to ensure it cannot be forged.

- **The Rule:** “I allow myself to be minted ONLY IF the transaction also creates or updates a UTXO carrying the `CCS_Identity_Type`.”
- This creates a cryptographic link: every receipt in the wild is mathematically proven to be backed by a deposit into the Treasury.

#### **5.2 Burning Rules (Refund Execution)**

When a donor wants a refund, they provide their Receipt as an input.

- **The Rule:** “I allow myself to be burned ONLY IF the Treasury UTXO is also an input and it is outputting NPT back to the donor’s address.”

## **Part III: The “Manifest” Standard**

This section defines the protocol-level standard for **On-Chain Discovery** , enabling generic wallets to interact with these scripts.

### **Chapter 6: The Manifest UTXO**

To make this a “General Purpose” system, we avoid hardcoding CCS logic into the wallet. Instead, the Developer deploys a **Manifest UTXO** that acts as the “Instruction Manual” for the contract.

**The Manifest Object:**

- **Storage:** The ABI JSON is stored in the `announcement` field of a dedicated, static UTXO.
- **Content:** \* The `lock_script_hash` and `type_script_hash` for the project.
- A schema defining the `vote()` and `donate()` methods.
- The BFieldElement layout for the VM’s input tape.

**Why this is a Standard:**  
When a wallet encounters a CCS address, it queries the blockchain for the associated Manifest. It then “learns” how to render the UI and generate the necessary STARK proofs for that specific version of the CCS without requiring a software update.

This final section addresses the operational reality of the system: how to launch it, how to manage its lifecycle, and how to maintain the “General Purpose” promise through a standardized wallet interface.

* * *

## **Part IV: Deployment, Lifecycle, and UX**

This section defines the operational procedures for managing a Neptune CCS, focusing on the “Circular Dependency” problem of script hashes and the “Prover-centric” user experience.

### **Chapter 7: The “Chicken and Egg” Deployment Problem**

In a system where scripts reference each other’s hashes for security (e.g., the Receipt Token hardcodes the Treasury’s Type Script Hash), deployment requires a specific, multi-stage sequence.

#### **7.1 The Hash-Dependency Loop**

1. **The Treasury** needs the **Vote Token Hash** to count votes.
2. **The Vote Token** needs the **Treasury Hash** to ensure it’s voting for the right project.
3. **The Receipt Token** needs the **Treasury Hash** to validate minting/burning.

#### **7.2 The Deployment Sequence**

To break this loop, we utilize **Deterministic Script Generation** :

1. **Stage 1: Pre-Computation.** The developer writes the code for all three scripts (`Treasury`, `Vote`, `Receipt`) using placeholders for the other scripts’ hashes.
2. **Stage 2: Deterministic Hashing.** Using a local Neptune tool, the developer calculates the final hashes of the compiled TASM for each script. Because TritonVM scripts are immutable, these hashes are fixed once the logic is finalized.
3. **Stage 3: Injection.** The developer replaces the placeholders in the source code with these finalized hashes and performs a final compilation.
4. **Stage 4: Genesis Transaction.** The developer mints the first `CCS_Identity_Token` and the **Manifest UTXO** in a single transaction. This “Genesis” block establishes the project’s existence on the network.

* * *

### **Chapter 8: Governance & Upgradability**

Because the CCS is “Leaderless” and decentralized, we cannot have an “Admin” key that can arbitrarily change the rules. Instead, upgrades happen via **Recursive Covenant Migration**.

#### **8.1 The “Governance Sweep”**

If the Judges decide to rotate their keys or update the CCS logic (e.g., to patch a bug), they do not “edit” the existing UTXOs. Instead, they perform a **Migration** :

- **The Vote:** 3-of-5 Judges authorize a “Migration Transaction.”
- **The Transaction:** This transaction consumes _all_ current Treasury UTXOs (Version 1).
- **The Output:** The transaction produces a _new_ set of Treasury UTXOs (Version 2) with a **new Lock Script**.
- **The Continuity:** The `CCS_Identity_Token` is preserved, but its internal “State” is updated to reflect the new version or new Judge list.

This ensures that the “Project Identity” stays the same (the address doesn’t change for donors), but the underlying “Engine” can be upgraded.

* * *

### **Chapter 9: Design for the Generic Prover Wallet**

The success of this system depends on a wallet that can handle arbitrary covenants. We move away from “Hardcoded Features” to a **“Manifest-Driven UI.”**

#### **9.1 The Manifest-Driven Workflow**

When a user wants to interact with the CCS, the wallet follows this automated routine:

1. **Discovery:** The user provides the `Project_ID` (the Type Script Hash).
2. **Manifest Retrieval:** The wallet scans the blockchain for a **Manifest UTXO** bearing that ID.
3. **UI Generation:** The wallet parses the ABI JSON within the Manifest.

- _Example:_ If the Manifest says `method: "Donate"`, the wallet renders a slider for NPT and a “Confirm” button.

1. **Local Proving (The “Witness”):**

- To “Vote,” the wallet doesn’t just send a message. It downloads the `Vote_Prover` TASM from the Manifest.
- It runs the Judge’s private key through this TASM locally to generate a **STARK Proof**.
- It bundles this Proof into a new `Vote_Ticket` UTXO.

#### **9.2 Benefit: Total Extensibility**

By following this standard, a Neptune wallet becomes a “Universal Browser” for smart contracts. The same wallet that handles the CCS today can handle a Decentralized Exchange (DEX) tomorrow, simply by reading a different Manifest UTXO.

* * *

### **Chapter 10: Conclusion**

The Neptune CCS is more than a crowdfunding tool; it is a reference implementation for **Trustless Governance** in a post-quantum, privacy-preserving ecosystem.

By leveraging **TritonVM’s Introspection** , the **Leaderless UTXO Model** , and the **Dual-Asset Identity Pattern** , we have created a system that is:

- **Permissionless:** No central authority can freeze funds.
- **Private:** Donors remain anonymous via Receipt Tokens.
- **Scalable:** Infinite concurrent donations via the “Bag of Coins” model.
- **Verifiable:** Every state transition is backed by a mathematical STARK proof.

* * *

### **Final Documentation Checklist for Developers**

To build this system, a developer must produce the following:

- **TASM/Rust Source:** `Treasury_Lock`, `Identity_Type`, `Receipt_Type`, `Vote_Type`.
- **Manifest JSON:** The ABI defining methods, widgets, and script hashes.
- **Deployment Tool:** A script to handle deterministic hashing and the Genesis transaction.
- **Web/Desktop Interface:** A “Prover-enabled” wallet or wrapper that can ingest the Manifest.

* * *

## **Part V: The Manifest Specification**

To finalize this technical reference, we will define the **Manifest UTXO JSON Schema**.

This is the “Rosetta Stone” of the system. It bridges the gap between the low-level **Triton Assembly (TASM)** running on the blockchain and the high-level **User Interface** on the user’s desktop. By storing this JSON on-chain, we ensure the CCS is truly permanent and self-documenting.

### **Chapter 11: The CCS Manifest JSON**

The following JSON structure is designed to be stored within the `announcement` field of the **Manifest UTXO**. It provides a “Generic Prover Wallet” with everything it needs to construct valid transactions.

```json
{
  "manifest_version": "1.0.0",
  "project_name": "Neptune Core Ecosystem Fund",
  "project_id": "5ef8...321a",
  "scripts": {
    "treasury_lock_hash": "a92b...f110",
    "identity_type_hash": "c11d...e449",
    "receipt_type_hash": "d22e...b558",
    "vote_type_hash": "f44g...a992"
  },
  "interactions": [
    {
      "method": "Donate",
      "description": "Contribute NPT to the treasury and receive a refund receipt.",
      "ui_widget": "funding_form",
      "inputs": [
        {
          "label": "Amount to Donate",
          "symbol": "NPT",
          "type": "amount_u64",
          "binding": "tx.output[target].value"
        }
      ],
      "logic_hint": "Create dual-asset output: [Identity_Token, Native_NPT] + [Receipt_Token]"
    },
    {
      "method": "Cast Vote",
      "description": "As a Judge, generate a proof to approve the current milestone.",
      "ui_widget": "judge_panel",
      "inputs": [
        {
          "label": "Milestone Index",
          "type": "u32",
          "widget": "dropdown",
          "source": "contract_state.milestone_index"
        },
        {
          "label": "Judge Secret Key",
          "type": "secret_key",
          "scope": "private"
        }
      ],
      "prover_tasm_ref": "ipfs://Qm...vote_prover.tasm",
      "logic_hint": "Mint Vote_Ticket UTXO with STARK proof of Judge_ID"
    },
    {
      "method": "Claim Refund",
      "description": "Burn your receipt to withdraw your pro-rata share of remaining funds.",
      "ui_widget": "refund_button",
      "inputs": [
        {
          "label": "Select Receipt",
          "type": "utxo_selector",
          "filter": "type_hash == scripts.receipt_type_hash"
        }
      ],
      "logic_hint": "Burn Receipt UTXO + Input Treasury UTXO -> Output Treasury (Reduced) + Output User (NPT)"
    }
  ],
  "governance": {
    "threshold": 3,
    "total_judges": 5,
    "judge_list": [
      { "id": 0, "name": "Reviewer_Alpha", "pubkey_hash": "0x..." },
      { "id": 1, "name": "Reviewer_Beta", "pubkey_hash": "0x..." }
    ]
  }
}

```

### **Chapter 12: How the Wallet Interprets the Manifest**

When a “Generic Prover Wallet” loads this JSON, it performs the following logic-mapping:

#### **12.1 Dynamic Form Rendering**

Instead of a hardcoded “Send” button, the wallet sees the `interactions` array.

- It renders a **“Cast Vote”** button.
- When clicked, it renders a **Dropdown** populated by the current milestone index (which it fetches from the live `Identity_Token` state on-chain).
- It provides a **Secure Password Field** for the `Judge Secret Key`.

#### **12.2 Automated Transaction Construction**

The `logic_hint` fields tell the wallet which UTXOs need to be bundled together. For a “Vote” transaction, the wallet knows it must:

1. Fetch the **Vote Prover TASM** (from the IPFS link or the UTXO data).
2. Execute that TASM locally using the user’s Secret Key as a “Secret Input.”
3. Take the resulting **STARK Proof** and place it in the witness area of a new `Vote_Ticket` UTXO.

#### **12.3 Safety Assertions**

Because the Manifest includes the `scripts` hashes, the wallet can perform a pre-broadcast check:  
_“Does the transaction I just built actually satisfy the `treasury_lock_hash`? I will run a local simulation of TritonVM to verify the proof before wasting the user’s transaction fee.”_

* * *

## **Chapter 13: The Neptune Manifest Schema (NMS-1)**

This schema defines the structure for the “Manifest UTXO.” It uses a strict type-mapping to ensure that UI inputs can be converted directly into the `BFieldElement` arrays required by TritonVM.

### **13.1 Primitive Type Mapping**

Any field typed in the Manifest must map to these TASM-compatible primitives:

| Manifest Type | TASM / Rust Equivalent | Description |
| --- | --- | --- |
| `bfe` | `BFieldElement` | Single field element (up to ). |
| `xfe` | `XFieldElement` | Extension field element (3 BFEs). |
| `u32` | `u32` | BFE constrained to 32 bits. |
| `u64` | `u64` | Two BFEs (Standard Neptune amount type). |
| `digest` | `Digest` | 5 BFEs (Standard hash/identity type). |
| `bool` | `bool` | BFE (0 or 1). |
| `string` | `Vec<BFieldElement>` | Length-prefixed UTF-8 encoded BFEs. |

* * *

### **13.2 Formal Schema Definition (JSON-Schema Style)**

The Manifest must be a JSON object following these field constraints:

#### **A. Header Metadata**

- **`manifest_id`** : `digest` — Unique hash of this specific manifest version.
- **`identity_hash`** : `digest` — The `type_script_hash` of the Project Identity Token.
- **`version`** : `u32` — Incremental version of the contract logic.

#### **B. Script Registry (`scripts`)**

A map of functional roles to their compiled `digest` hashes.

- **`lock_logic`** : `digest` — The `lock_script_hash` (The Authority).
- **`state_logic`** : `digest` — The `type_script_hash` (The Identity).
- **`asset_logic`** : `digest` — (Optional) Hash of the associated Receipt token.

#### **C. Interaction Definitions (`methods`)**

An array of objects defining user actions. Each object must contain:

- **`name`** : `string` — Display name (e.g., “Vote”).

- **`selector`** : `bfe` — The “Function Selector” passed to the TASM entry point (like an Ethereum 4-byte ID).

- **`args`** : `Array<Argument>` — Ordered list of inputs.

- **`label`** : `string` — UI label.

- **`type`** : `PrimitiveType` — (From the table in 13.1).

- **`widget`** : `enum` — [`slider`, `dropdown`, `text`, `hidden`, `key_selector`].

- **`prover_ref`** : `string` — URI (IPFS/On-chain) to the `.tasm` or `.wasm` Prover binary.

#### **D. State Mapping (`state_view`)**

Tells the wallet how to “Read” the UTXO data field to show the user current info.

- **`layout`** : `Array<{ name: string, type: PrimitiveType }>`
- _Example:_ `[{ "name": "milestone", "type": "u32" }, { "name": "total_donated", "type": "u64" }]`

* * *

### **13.3 Implementation: Lossless Conversion**

The Wallet’s primary job is the **TASM Stack Preparation**. Using this schema, the wallet performs the following “Lossless” transformation:

1. **Collects UI Input:** User enters “Milestone: 2”.
2. **Lookup Schema:** Method `Vote` has Arg[0] of type `u32`.
3. **BFE Encoding:**

- `2` (Integer) `BFieldElement(2)`.
- `Amount(10.5 NPT)``u64` (Two BFEs representing microns).

1. **Stack Loading:**  
The wallet pushes the **Selector** , then the **Arguments** onto the TritonVM operational stack in the order defined in the Manifest.  
`[...stack, Argument_N, ..., Argument_0, Selector]`

* * *

### **13.4 Example Implementation (The CCS “Vote” Method)**

Based on this strict schema, the “Vote” method is defined as:

```json
{
  "name": "Cast Vote",
  "selector": "0x11223344",
  "args": [
    {
      "label": "Milestone Index",
      "type": "u32",
      "widget": "dropdown",
      "source": "state_view.milestone"
    },
    {
      "label": "Judge ID",
      "type": "u32",
      "widget": "hidden",
      "source": "wallet.active_key_id"
    }
  ],
  "prover_ref": "neptune://c11d...e449/vote_prover"
}

```

### **Why this is “General Purpose”**

By mapping to TASM types (`bfe`, `u32`, `u64`), the wallet becomes a **Transparent Proxy**. It doesn’t need to understand “CCS logic.” It only needs to understand how to turn a JSON input into a Stack Element. This ensures that any future contract—no matter how complex—can be used immediately by any wallet that implements this **NMS-1 Schema**.

* * *

The **State View** is the final piece of the “Generic Prover Wallet” puzzle. It allows the wallet to take a raw blob of `BFieldElements` from a UTXO and turn it into a human-readable dashboard.

Without this, the wallet is “blind”—it can send transactions, but it can’t tell the user what the current milestone is or how much has been raised.

* * *

## **Chapter 14: The State View Standard**

In Neptune, a UTXO’s data field is essentially a flat array of `BFieldElements`. The **State View** section of the Manifest provides the “Lens” through which the wallet views this data.

### **14.1 The Decoding Engine**

The wallet uses a **sequential decoder** based on the ordered list provided in the Manifest. It starts at index 0 of the UTXO data and “carves out” the types as specified.

#### \*\*Schema Definition: `state_view**`

- **`root`** : `enum` — [`utxo_data`, `announcement`]. Defines where the data is stored.
- **`fields`** : `Array<DataField>`
- **`name`** : `string` — The label for the UI (e.g., “Funds Raised”).
- **`type`** : `PrimitiveType` — (e.g., `u64`, `digest`, `u32`).
- **`visibility`** : `enum` — [`public`, `internal`].
- **`transform`** : `enum` — [`none`, `micron_to_npt`, `timestamp_to_date`].

* * *

### **14.2 Case Study: Decoding the CCS Treasury UTXO**

Imagine a Treasury UTXO has the following raw data in RAM:  
`[0x00000001, 0x00000000000003E8, 0x0000000000000005, ...]`

The Manifest defines the **State View** like this:

```json
"state_view": {
  "root": "utxo_data",
  "fields": [
    {
      "name": "Current Milestone",
      "type": "u32",
      "visibility": "public"
    },
    {
      "name": "Total Payout Threshold",
      "type": "u64",
      "transform": "micron_to_npt",
      "visibility": "public"
    },
    {
      "name": "Judge Quorum",
      "type": "u32",
      "visibility": "public"
    }
  ]
}

```

#### **How the Wallet Renders This:**

1. **Read Index 0 (`u32`):** Sees `0x1`. Displays **“Current Milestone: 1”**.
2. **Read Index 1-2 (`u64`):** Sees `1000` (in microns). Applies `micron_to_npt`. Displays **“Total Payout Threshold: 1000 NPT”**.
3. **Read Index 3 (`u32`):** Sees `5`. Displays **“Judge Quorum: 5”**.

* * *

### **14.3 Dynamic Formulas: The “Progress Bar” Logic**

A truly generic wallet should also be able to perform basic math on these fields to provide better UX. We extend the `state_view` with a `computations` array:

```json
"computations": [
  {
    "label": "Funding Progress",
    "type": "percentage",
    "formula": "(tx.value / state_view.total_payout_threshold) * 100"
  }
]

```

This allows the wallet to render a **Progress Bar** (e.g., “45% Funded”) even though the contract itself never explicitly calculated a percentage.

* * *

## **Chapter 15: Putting It All Together**

We have now reached the conclusion of the **Neptune CCS Technical Reference**. By combining these three standards, we have created an ecosystem that is both highly specific (The CCS) and infinitely general (The NMS-1 Standard).

### **The Developer’s Final Architecture**

1. **The Code (TASM/Rust):** Enforces the logic and manages the **Multi-Coin UTXOs** (NPT + Identity).
2. **The Data (Manifest):** Defines the **Types** , **Methods** , and **State Views** using NMS-1.
3. **The UX (Generic Wallet):** Downloads the Manifest, decodes the **State** , and generates the **Prover Witness** JIT.

### **Conclusion: Beyond the CCS**

While this guide used a Crowdfunding System as its primary example, the **Manifest + Introspection** model is the key to unlocking the “World Computer” potential of Neptune Cash. It allows for a library of “Covenant Templates” that any user can deploy, and any wallet can immediately understand.

* * *

# **Neptune CCS: Developer Quick Start**

### **1. Environment Setup**

Ensure you have the following tools installed:

- **`tasm-lang`** : The Rust-to-TASM compiler.
- **`neptune-core`** : For testing script execution against a local node.
- **`triton-vm`** : To run and debug your scripts in a local VM environment.

* * *

### **2. Development Workflow (Step-by-Step)**

#### **Step 1: Compile the Auxiliary Scripts**

Write and compile your **Receipt Token** and **Vote Ticket** scripts.

- **Note:** Initially, use a “Dummy Hash” for the Project Identity.
- **Command:** `tasm-lang compile receipt_token.rs --output receipt.tasm`
- **Action:** Take the resulting hash () and .

#### **Step 2: Compile the Core Treasury**

Inject the hashes from Step 1 into your **Treasury Lock** and **Identity Type** scripts.

- **Treasury Lock:** Hardcode and into the introspection loop.
- **Identity Type:** Hardcode the .
- **Action:** Compile and get the final Treasury hashes ( and ).

#### **Step 3: Resolve the Circular Dependency**

Re-compile the **Receipt Token** and **Vote Ticket** , replacing the “Dummy Hash” with the real from Step 2.

> **Result:** You now have a “Locked Loop” where all three scripts recognize and verify each other’s hashes.

#### **Step 4: Prepare the Manifest**

Create your `manifest.json` using the **NMS-1 Schema**.

- Map your Treasury data fields to `u32` and `u64`.
- Define the `selector` for each method (e.g., `0x01` for Donate, `0x02` for Vote).
- Specify the `prover_ref` (e.g., an IPFS hash pointing to your compiled Prover TASM).

* * *

### **3. The Genesis Transaction**

To launch the CCS, you must broadcast a single transaction that initializes the system:

1. **Output 1 (Manifest):** A dust UTXO containing the `manifest.json` in the announcement field.
2. **Output 2 (Identity):** A UTXO carrying the `CCS_Identity_Type` and `CCS_Authority_Lock` with initial state (Milestone: 0).

* * *

### **4. Deployment Checklist**

| Component | Status | Verification |
| --- | --- | --- |
| **Identity Token** | `H_identity` | Use `triton-vm` to verify state transition . |
| **Authority Lock** | `H_lock` | Test introspection loop with 3 mock Vote UTXOs. |
| **Receipt Token** | `H_receipt` | Verify it cannot be minted without Identity in outputs. |
| **ABI Manifest** | `NMS-1 JSON` | Validate against the schema for `bfe` and `u64` alignment. |

* * *

### **5. Common Pitfalls**

- **Endianness:** Ensure `u64` amounts are split into two `BFieldElements` in the correct order for the wallet to decode.
- **Bitmasks:** In the `Authority_Lock`, always use a bitmask for Judge IDs to prevent a single judge from satisfying the quorum with multiple Vote UTXOs.
- **Padding:** Remember that `string` types in TASM are length-prefixed; ensure your Manifest decoder accounts for this.

* * *

### **The Bitmask Vote Counter (TASM Snippet)**

To ensure the **Authority Lock** is robust against “double-counting” (where one judge tries to submit multiple vote UTXOs to satisfy the quorum alone), we use a bitmask.

In TASM, we use the bitwise `AND` and `OR` operations to track which `Judge_ID` has already been seen during the input scan.

This logic would be embedded inside the loop that iterates over transaction inputs.

```tasm
// INITIAL STATE (Before Loop)
PUSH 0 // [judge_bitmask] -> Initialize to 0
PUSH 0 // [vote_count, judge_bitmask] -> Initialize to 0

// --- START OF INPUT LOOP ---
// (Assume we have already verified the current input is a Vote UTXO)

// 1. Load the Judge_ID from the UTXO data (Assume it's a u32)
// [..., current_input_ptr, vote_count, judge_bitmask]
dup 2
read_mem 1 // Load Judge_ID from RAM
// [..., judge_id, vote_count, judge_bitmask]

// 2. Create the bit-flag (1 << judge_id)
PUSH 1
dup 1 // Duplicate judge_id for the shift
// [..., judge_id, judge_id, 1, vote_count, judge_bitmask]
// Note: TritonVM doesn't have a variable SHL, so we use a loop or lookup
call power_of_two
// [..., bit_flag, vote_count, judge_bitmask]

// 3. Check if judge has already voted
dup 0 // bit_flag
dup 3 // judge_bitmask
AND // Result is non-zero if bit is already set
// [..., (flag & mask), bit_flag, vote_count, judge_bitmask]

push 0
eq
skiz call increment_vote // If result was 0, judge is new. Increment.

// 4. Update the mask regardless (safe to OR a bit that's already set)
swap 2 // [judge_bitmask, vote_count, bit_flag]
OR
swap 1 // [vote_count, judge_bitmask]
// --- END OF LOOP ---

// FINAL CHECK
PUSH 3 // The Quorum
dup 1 // vote_count
ge // Is vote_count >= 3?
assert // Crash if threshold not met

```

### **Supporting Subroutine: Power of Two**

Since shifting by a variable amount can be complex in assembly, we use a simple recursive power-of-two function to generate the bit-flag.

```tasm
power_of_two:
    // [exponent, base(1)]
    dup 1
    push 0
    eq
    skiz return // If exponent is 0, we are done

    push 2
    mul
    swap 1
    push -1
    add
    swap 1
    recurse

```

### **Security Analysis**

1. **Uniqueness:** Even if a malicious actor provides five Vote UTXOs all signed by “Judge #1,” the `AND` check will prevent `vote_count` from exceeding 1 for that judge.
2. **Statelessness:** This entire check happens during the spending transaction. No permanent “voted” state needs to be saved on the project UTXO, keeping it “clean” for the next milestone.
3. **Efficiency:** The bitmask is a single `BFieldElement`. Using a 64-bit field allows up to 64 unique judges—far more than the 5–10 typically used in a CCS.

The **Milestone Ratchet** is the “heartbeat” of the project’s continuity. It ensures that the project cannot be “reset” and that funds cannot be drained without the state moving forward.

In the **Dual-Asset Model** , this logic lives in the `type_script` of the **Identity Token**. By enforcing this at the type level, you ensure that even if the `lock_script` (the judges) is compromised or changed, the fundamental progression of the project remains immutable.

### **The Identity Type Script: Milestone Ratchet**

This `tasm-lang` template demonstrates how to compare the “Before” and “After” states of the project within a single transaction.

```rust
use tasm_lang::prelude::*;

// Define the state structure stored in the UTXO's data field
struct CCSProjectState {
    milestone_index: u32,
    total_milestones: u32,
    dev_address: Digest,
}

fn main() {
    // 1. Load the "Self" UTXO (the state before this transaction)
    let input_utxo = tasm::load_current_utxo();
    let old_state: CCSProjectState = input_utxo.decode_data();

    // 2. Identify the "Successor" UTXO (the state after this transaction)
    // We search the outputs for the UTXO carrying THIS specific type script.
    let tx = tasm::load_current_transaction();
    let mut successor_found = false;

    for output in tx.outputs {
        if output.type_script_hash() == tasm::own_type_script_hash() {
            let new_state: CCSProjectState = output.decode_data();

            // --- THE RATCHET LOGIC ---

            // Rule A: Directionality
            // The milestone can either stay the same (Donation) or increment (Payout).
            // It can NEVER go backwards.
            assert!(new_state.milestone_index >= old_state.milestone_index);

            // Rule B: Sequentiality
            // We only allow incrementing by exactly 1 at a time.
            assert!(new_state.milestone_index <= old_state.milestone_index + 1);

            // Rule C: Immutability of Configuration
            // You cannot change the developer address or total milestones
            // without a high-level governance migration.
            assert!(new_state.dev_address == old_state.dev_address);
            assert!(new_state.total_milestones == old_state.total_milestones);

            successor_found = true;
            break;
        }
    }

    // 3. Termination Logic
    // If no successor is found, we must be in the "Final Payout" state.
    if !successor_found {
        assert!(old_state.milestone_index == old_state.total_milestones,
            "Project attempted to dissolve before completing all milestones.");
    }
}

```

* * *

### **Architectural Significance**

1. **Atomic State Transitions:** By running this script, the network ensures that the (Native Token) and the `milestone_index` move in lockstep. You cannot have a transaction where the money leaves but the milestone doesn’t advance.
2. **Safety against “Ghost” Updates:** Because the script iterates through `tx.outputs` to find its own hash, it prevents “splintering,” where a project might try to split into two competing versions of itself.
3. **Self-Liquidation:** The logic in Step 3 allows the project to naturally “expire” once the work is done, allowing the Identity Token to be burned and the final dust to be cleaned up.

* * *

# **Appendix A: Transparency & Public Auditing**

**Subject:** Implementing “Forced Announcements” for State Visibility

**Origin:** Adapted from “Overlay Protocol” concepts (Alan’s Design)

**Goal:** To defeat the “Privacy Default” of Neptune for the specific case of Public Treasury tracking.

* * *

## **A.1 The Problem: Privacy by Default**

Neptune Cash uses confidential transactions. By default, when a UTXO is spent, its value and data are obfuscated.

- **The Donor’s View:** Perfect. They want privacy.
- **The Public’s View:** Problematic. If the Treasury UTXO is spent, the public might lose track of the `Milestone_Index` or `Total_Raised` because the output UTXO appears as an encrypted blob.

To solve this, we cannot rely on the _goodwill_ of the developer to publish their updates. We must **mathematically enforce** transparency within the Type Script itself.

* * *

## **A.2 The Solution: Forced Announcements**

We modify the `CCS_Identity_Type` script. It now includes a clause that says:

> _“I will only validate this transaction if the Output UTXO carrying my identity ALSO carries a cleartext public announcement of its new state.”_

This ensures that the “Chain of Custody” for the project is publicly visible in the block data, allowing “Light Clients” and Block Explorers to index the CCS without holding the private keys.

* * *

## \*\*A.3 Updated Logic: `ccs_identity_type.rs**`

Below is the revised Type Script. The new logic is located inside the successor verification loop.

```rust
use tasm_lang::prelude::*;

struct CCSProjectState {
    milestone_index: u32,
    total_milestones: u32,
    dev_address: Digest,
}

fn main() {
    let input_utxo = tasm::load_current_utxo();
    let old_state: CCSProjectState = input_utxo.decode_data();

    let tx = tasm::load_current_transaction();
    let mut successor_found = false;

    for output in tx.outputs {
        // Find the new version of the project
        if output.type_script_hash() == tasm::own_type_script_hash() {
            let new_state: CCSProjectState = output.decode_data();

            // 1. Ratchet Logic (Existing)
            assert!(new_state.milestone_index >= old_state.milestone_index);
            assert!(new_state.milestone_index <= old_state.milestone_index + 1);

            // 2. Transparency Logic (NEW)
            // We verify that the output actually contains a 'Public Announcement'
            // field that matches the internal state.
            let announcement = output.public_announcement();

            // The announcement must be present
            assert!(announcement.is_some(), "Transparency Error: State must be public.");

            // The announcement must match the actual data (Anti-Spoofing)
            // We require the announcement to be the serialization of the new state.
            let announced_state: CCSProjectState = CCSProjectState::decode(announcement.unwrap());
            assert!(announced_state == new_state, "Transparency Error: Mismatched public data.");

            successor_found = true;
            break;
        }
    }

    if !successor_found {
        assert!(old_state.is_final(), "Project dissolved prematurely.");
    }
}

```

* * *

## **A.4 The Announcement Standard**

To ensure generic block explorers can parse this data, we define the standard format for the `Public Announcement` field.

**Announcement Schema (BFieldElement Array):**

1. **Prefix:** `0x434353` (ASCII for “CCS”).
2. **Milestone Index:** `u32`.
3. **Balance:** `u64` (The visible NPT amount).
4. **State Hash:** `Digest` (A hash of the full internal state for verification).

### **Why this is powerful:**

With this change, a block explorer does **not** need to run the TritonVM to know what is happening. It can simply scan the blockchain for the “CCS” prefix in announcements.

- **If it sees `Milestone: 1`:** It updates the website to “In Progress.”
- **If it sees `Milestone: 2`:** It updates the website to “Milestone 1 Complete.”

This creates a “Shadow Ledger” of public data on top of the private Neptune chain, strictly for this charity application.

* * *

# **Appendix B: Design Justification & Comparative Analysis**

**Reference:** [Alan’s “Overlay Protocol” Proposal (Neptune Forum)](https://talk.neptune.cash/t/brainstorming-how-the-community-can-help/203/11)

### **B.1 Architectural Divergence**

In early discussions regarding a Neptune CCS, a “Singleton” model was proposed where the treasury resides in a single UTXO managed by an overlay protocol (a custom node plugin). While theoretically sound, this introduces significant engineering friction and scalability bottlenecks.

Our implementation adopts a **“Leaderless” (Bag of Coins)** architecture. Instead of a single “Pot” that must be updated sequentially, we treat the treasury as a distributed collection of UTXOs that share a common identity.

### **B.2 Comparative Matrix**

The following table details the specific mechanical differences between the Overlay Model and our Leaderless Model, justifying the design choices made in this specification.

| Feature | The “Overlay” Model (Singleton) | The “Leaderless” Model (Chosen) | Why We Chose “Leaderless” |
| --- | --- | --- | --- |
| **Concurrency** | **Sequential.** Only one transaction can spend the Treasury UTXO per block. High contention if many donors try to donate simultaneously. | **Infinite.** 100 donors create 100 separate Treasury UTXOs simultaneously. No locking or queuing required. | Eliminates “Double Spend” failures during high-traffic fundraising events. |
| **Infrastructure** | **Heavy.** Requires Judges to run a custom “Neptune Foundation” node plugin to coordinate state and manage the overlay network. | **Light.** Uses standard Neptune infrastructure. The “Logic” lives in the Wallet (Manifest), not in a custom node process. | Drastically lowers the barrier to entry for Judges and Developers. No custom daemon required. |
| **Governance** | **Synchronous.** Judges must coordinate online to sign the specific transition of the singular UTXO. | **Asynchronous.** Judges mint “Vote Tickets” independently at their own leisure. The system aggregates them later. | Removes the need for Judges to be online simultaneously. “Bus Factor” resistant. |
| **State Storage** | **Explicit.** `Total_Raised` is a variable stored in the single UTXO’s data field. | **Derived.** `Total_Raised` is the sum of all UTXOs on the chain matching the Identity Script. | More robust. The state cannot be corrupted; it is simply the physical reality of the coin set. |
| **Transparency** | **Enforced Announcement.** Uses a type script to force public declaration of state. | **Enforced Announcement.** (Adopted). We incorporated this specific feature from the Overlay model. | We agree with the Overlay model here: Public auditing is non-negotiable for a CCS. |
| **Upgradability** | **Monolithic.** Logic is often baked into a single complex script. | **Modular.** Separation of `Lock_Script` (Auth) and `Type_Script` (Identity). | Allows replacing the “Judges” (Lock) without destroying the “Project” (Identity). |

### **B.3 Conclusion on Engineering Workload**

Alan noted that _“Nothing is blocking such a system presently besides the engineering workload.”_

By shifting from an **Overlay Protocol** (which requires maintaining p2p connections between judges) to a **Manifest-Driven Protocol** (where logic is executed client-side by the prover), we reduce the engineering workload by an estimated **60-70%**. We remove the need to write network code, focusing entirely on Transaction Verification Logic (TASM).

* * *

# **Appendix C: Scalability & Permissionless Maintenance**

**Subject:** Handling UTXO Fragmentation without External Infrastructure

**Solution:** The “Self-Healing” Ledger via Permissionless Consolidation.

### **C.1 The Fragmentation Reality**

In a “Bag of Coins” model, a successful project may accumulate thousands of small UTXOs. Due to prover resource limits (the “Fan-In” constraint), these cannot be swept in a single transaction.

### **C.2 The “No-Bot” Requirement**

We reject the use of “Keeper Bots” or “Overlay Servers” to manage this fragmentation, as they introduce fragility. The system must be maintainable solely by the interested parties (the Developer) using standard client-side software.

### **C.3 Solution: The Consolidation Bypass**

We introduce a **Permissionless Consolidation Path** in the `CCS_Authority_Lock`.

- **Rule:** Any transaction that consumes Treasury UTXOs is **valid without signatures** IF AND ONLY IF the total value is returned to new UTXOs with the exact same Script Hash.
- **Fee Market:** The transaction fee for this maintenance must be paid by an _external_ input (e.g., the Developer’s wallet). The Treasury principal cannot be used for fees during consolidation.

### **C.4 The Workflow (Client-Side)**

When the Developer attempts to claim a milestone:

1. **Analysis:** The wallet scans the UTXO set.
2. **Auto-Merge:** If fragmentation is high (), the wallet automatically generates and broadcasts “Merge Transactions” using the Consolidation Bypass. This costs the Developer a nominal fee (dust) but requires no Judge interaction.
3. **Payout:** Once the set is consolidated, the wallet generates the final Payout Transaction using the Judge Votes.

This ensures the system remains **Leaderless, Serverless, and Robust.**

* * *

# **Appendix D: The Maintenance Manifest Standard**

**Subject:** Automated State Optimization & Permissionless Housekeeping

**Goal:** Enabling generic wallets to perform contract-specific maintenance (e.g., UTXO consolidation) without hardcoded logic.

### **D.1 The Problem: Entropy & Prover Limits**

In the “Bag of Coins” architecture, the state naturally fragments over time.

1. **Entropy:** A successful CCS project may accumulate 1,000+ tiny UTXOs (donations).
2. **Prover Limits:** A single Neptune transaction cannot consume an arbitrary number of inputs due to “Fan-In” constraints on the STARK prover (typically capped at ~25 inputs per transaction for efficiency).
3. **The Wallet Gap:** A generic wallet knows how to _send_ money, but it does not know that this specific contract requires periodic “Merging” to remain spendable. Hardcoding “CCS Merge Logic” into the wallet software violates the principle of a general-purpose wallet.

### **D.2 The Solution: The `maintenance` Array**

We extend the NMS-1 (Neptune Manifest Schema) to include a `maintenance` section. This section allows the developer to define “Housekeeping Scripts” that the wallet can execute autonomously when specific state conditions are met.

This shifts the logic from **“Hardcoded in Client”** to **“Declared in Data.”**

### **D.3 Schema Specification**

The `maintenance` array contains objects with the following fields:

- **`task_name`** : Human-readable label (e.g., “Consolidate Dust”).

- **`type`** : The operation category.

- `merge_self`: Consolidate many UTXOs of same type into fewer UTXOs.

- `sweep_decay`: Spend expired UTXOs to a target address.

- **`trigger`** : A logic condition that tells the wallet _when_ to recommend this action.

- Supported vars: `input_count`, `total_balance`, `utxo_age`.

- **`witness_mode`** : Defines authentication requirements.

- `signature`: Requires user approval/private key.

- `bypass`: Requires no signature (relies on strict logic constraints, e.g., Value In == Value Out).

### **D.4 Concrete Example: CCS Dust Consolidation**

Below is the JSON that would appear in the CCS Manifest. It teaches the wallet how to perform the **Permissionless Consolidation** discussed in Appendix C.

```json
{
  "maintenance": [
    {
      "task_name": "Optimize Vault Storage",
      "description": "Merges small donation UTXOs to ensure funds remain accessible for payout.",
      "type": "merge_self",
      "priority": "high",

      // The Trigger: When does the wallet suggest this?
      "trigger": {
        "condition": "utxo_count(scripts.identity_type_hash) > 20",
        "action": "prompt_user_toast",
        "message": "Vault fragmentation detected. Click to optimize."
      },

      // The Execution Logic
      "execution": {
        "max_inputs_per_tx": 25,
        "fee_payer": "external_wallet", // Developer pays fee, Treasury preserved
        "constraints": {
          "input_script": "scripts.identity_type_hash",
          "output_script": "scripts.identity_type_hash",
          "balance_invariant": "exact" // Sum(In) == Sum(Out)
        }
      },

      // The Authentication
      // This tells the wallet: "Don't ask for a Judge Key. Just build the proof."
      "witness_mode": "bypass"
    }
  ]
}

```

### **D.5 Wallet Behavior Flow**

When a generic wallet loads this Manifest:

1. **Passive Scan:** It counts the UTXOs held by the Treasury script.
2. **Trigger Check:** If the count is 5, it does nothing. If the count is 50, the `trigger` condition (`> 20`) evaluates to `TRUE`.
3. **User Prompt:** The wallet displays a “Maintenance Available” icon.
4. **Auto-Execution:** Upon clicking, the wallet reads `witness_mode: "bypass"`. It immediately constructs 2 transactions merging 25 inputs each, generates the STARK proofs verifying `balance_invariant: "exact"`, and broadcasts them.

This ensures the CCS remains performant forever, even if the wallet developers never specifically wrote code for “Crowdfunding Optimization.”

* * *

reference: here is the AI conversation that culminated in this design document.

> **[Before you continue](https://consent.google.com/m?continue=https:%2F%2Fgemini.google.com%2Fshare%2Fd3f761b23a86&gl=LT&m=0&pc=bard&cm=2&hl=en-US&src=1)**

---

<div class="post-metadata">

**Author:** ![LostInTranslation](https://talk.neptune.cash/letter_avatar_proxy/v4/letter/l/e5b9ba/32.png) [@LostInTranslation](https://talk.neptune.cash/u/LostInTranslation)\
**Post date:** [December 23, 2025, 7:39pm UTC](https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206/2 "2025-12-23T19:39:38Z")

</div>

Awesome news, danda! This is no small task, but pulling it off would be a huge win and a major growth driver for the ecosystem

---

<div class="post-metadata">

**Author:** ![danda](https://talk.neptune.cash/letter_avatar_proxy/v4/letter/d/b19c9b/32.png) [@danda](https://talk.neptune.cash/u/danda)\
**Post date:** [December 24, 2025, 1:43am UTC](https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206/3 "2025-12-24T01:43:50Z")

</div>

### Appendix E: The Janitor Construction Hook

This appendix documents the **Janitor** (Manifest-Driven Aggregation) model. This architecture is intended to **fully replace** the previously considered **Leaderless UTXO** approach. While the Leaderless design provided a decentralized path for concurrent donations, it introduced significant “state bloat” and user-experience friction that the Janitor model successfully resolves through protocol-level automation.

It is intended that a future draft of the design document will flesh out the Janitor model more fully.

* * *

### 1. Architectural Shift: From Manual to Autonomous

In a standard UTXO system, transactions are “inert”—they do not move unless a user manually crafts a transaction. The Janitor model introduces a **Maintenance Layer** into the block-composition process. Instead of leaving donation fragments scattered across the ledger, we utilize an automated “sweeping” mechanism to keep the treasury consolidated. This would be performed within neptune-core nodes operating in a composer role.

#### Why it Replaces Leaderless

| Flaw of Leaderless | Janitor Solution |
| --- | --- |
| **UTXO Fragmentation:** Hundreds of donations create hundreds of tiny UTXOs, bloating the mutator set. | **Constant Consolidation:** Fragments are merged into a single “Summary UTXO” as quickly as they appear. |
| **Input Limits:** A developer might be unable to claim 1,000 donations in one TX due to protocol size limits. | **Single Output:** The developer only ever spends one “Gold Bar” summary UTXO, regardless of campaign size. |
| **Zombie Funds:** If a project fails, funds sit locked until the donor manually reclaims them. | **Automated Refunds:** The Janitor “pushes” expired funds back to donors to collect a cleanup bounty. |

* * *

### 2. The Janitor Hook (Core Logic)

The “Janitor” is implemented as a generic **Aggregator Hook** within the `neptune-core` block-composition code. It remains entirely agnostic of the CCS specifically; it simply follows the “Search and Merge” instructions provided in the on-chain IBD Manifest.

#### Step 1: Identification via Unlock Scripts

Rather than checking for specific hardcoded IDs, the Janitor scans the mempool and the confirmed UTXO set for any outputs whose Lock Scripts can be satisfied by the **Unlock Script** template provided in the Manifest. This ensures the core can support any contract that provides a valid Manifest.

#### Step 2: Native State Synthesis (The “Fast Path”)

The aggregation of data does not happen inside the Triton VM (which would be computationally expensive). Instead, the Janitor logic performs the arithmetic in **native Rust** :

- It identifies up to 25 pending donation UTXOs.
- It calculates the new treasury total (Old Summary + New Donations).
- It generates the **RemovalRecords** (inputs) and **AdditionRecords** (outputs) for the merge.

#### Step 3: Composer Integration

The Janitor hands these records to the **Block Composer**. The composer incorporates them into the next block proposal. Because the composer is already generating a ZK-STARK proof for the entire block, the “Summary Update” is proven as part of the standard mining workflow.

* * *

### 3. Economic Incentives: The Janitor Fee

To ensure this work is performed by miners, the Manifest defines a **Protocol-Level Bounty** :

- **The Aggregation Fee:** A small, mandatory portion of each donation is claimable only by the miner who successfully merges that donation into the Summary UTXO.
- **The Cleanup Bounty:** For maintenance tasks (like refunds), a specific reward is offered to the miner who “cleans” the expired state from the ledger.

This transforms the miner from a passive observer into an active **State Janitor** , financially motivated to keep the CCS optimized and user funds moving.

* * *

### 4. Handling Surge and Backlog

If a viral campaign receives more donations than can fit in a single block (e.g., more than 25 per block), the Janitor model performs **Iterative Consolidation**.

- It merges the first 25 donations into the Summary.
- In the next block, it identifies the remaining fragments and merges them as well.

The system is self-healing; it will always “catch up” until the treasury is represented by a single, optimized UTXO.

* * *

### 5. Technical Visual: State Consolidation

- **Input Phase:** Composer identifies inputs () matching the Manifest script.
- **Processing Phase:** Native Rust calculates the sum and subtracts the Janitor Fee.
- **Output Phase:** A single (the new Summary UTXO) and a Fee Output are generated.
- **Verification Phase:** Triton VM validates the final block proof, ensuring the sum matches the Manifest’s logic.

---

<div class="post-metadata">

**Author:** ![aszepieniec](https://talk.neptune.cash/user_avatar/talk.neptune.cash/aszepieniec/32/5_2.png) [@aszepieniec](https://talk.neptune.cash/u/aszepieniec)\
**Post date:** [December 24, 2025, 7:13am UTC](https://talk.neptune.cash/t/towards-a-neptune-community-crowdfunding-system-ccs-design/206/4 "2025-12-24T07:13:00Z")

</div>

This is an ambitious project, Dan. I like it 🙂

One of the motivations for the bag-of-coins treasury as opposed to the single-UTXO treasury is the inability of the latter to handle multiple donations within one block. On this note, you should know that _transaction chaining_ is not currently supported, but _is_ on the roadmap. Once it is implemented, you will be able to spend UTXOs that are produced by transactions that are not confirmed yet. However, with transaction chaining achieved, there will still be the problem that the initiator needs to be aware of the transaction that they are building on top of. So the motivation for the bag-of-coins treasury still holds in this world but the problem it avoids is slightly less acute.

> By placing both scripts on the same UTXO, the Neptune consensus engine requires both the NPT conservation rules and the CCS identity rules to return True

Technically, these scripts don’t return true or false; they either halt gracefully, or else crash and burn.

I’m not sure I understand the solution to the chicken-and-egg problem. And I’m not sure the LLM does either 😉

Maybe you can get inspiration from the chicken-and-egg problem and its solution for `SingleProof`s. One of the ways to generate a `SingleProof` for a transaction is to Update it (bumping the timestamp or mutator set accumulator), and another way is to Merge two transactions that are supported by `SingleProof`s. In either case, the `SingleProof` program needs to invoke the Triton VM verifier to verify a particular claim, and that claim consists of a program hash, an input, and an output. That program hash must be the hash of the `SingleProof` program. How does the `SingleProof`program know its own hash? It cannot be hardcoded; or rather, hardcoding it requires first solving a hard problem related to Tip5 and preimage resistance.

Here’s how it is solved. Whenever any Triton VM program starts, its stack is not empty. It contains 16 elements. The bottom 5 elements of the stack agree with the hash of the program that is being run. The very fist thing the `SingleProof` program does is store this digest to memory for later use. Then later on when it needs to compile a `Claim`with which to invoke the Triton VM verifier, the program hash field of that claim can be populated by reading the digest from memory.

> “I will only validate this transaction if the Output UTXO carrying my identity ALSO carries a cleartext public announcement of its new state.”

Announcements used to be called public announcements but we dropped that adjective because they are _always_ public. More importantly, announcements are tied to transactions, not to UTXOs.

> 1. Balance: u64 (The visible NPT amount).

You probably want to use a u128 to store the number of nau; otherwise you are losing precision.

> This [Janitorial sweeping] would be performed within neptune-core nodes operating in a composer role.

Have you considered the incentives for Composers? Because if it hurts their Composition time then are probably not going to do it.

> it simply follows the “Search and Merge” instructions provided in the on-chain IBD Manifest.

Wait, what’s the IBD Manifest?
