DocsPsy OverviewSmart Contracts

Smart Contracts on Psy

A high-level introduction to Smart Contracts on Psy

Smart contracts on Psy are fundamentally different from those on traditional blockchains like Ethereum. Psy's unique PARTH state architecture and its native integration of Zero-Knowledge Proofs (ZKPs) necessitate a novel approach to how smart contracts are defined, executed, and how their state is managed. This document provides developers with a comprehensive understanding of Psy's smart contract paradigm.

Core Principles of Psy Smart Contracts

  1. User-Centric State (PARTH):

    • Instead of a single global state tree for each smart contract, Psy employs the PARTH model. For a given smart contract, each user who interacts with it has their own separate CSTATE (Contract State Tree).
    • This CSTATE holds the storage variables pertinent only to that user for that specific contract.
    • A user's UCON (User Contract Tree) acts as a directory, mapping Contract IDs to the roots of their respective CSTATE trees.
    • Implication: User A's execution of Contract X modifies User A's CSTATE for Contract X. It cannot directly modify User B's CSTATE for Contract X, nor can it directly modify any global state of Contract X (as "global contract state" in the traditional sense doesn't exist in the same way). This isolation is key to eliminating write conflicts and enabling parallel execution.
  2. Local Execution & Proving:

    • Smart contract functions (Contract Function Circuits - CFCs) are executed locally by the user (or their client software/delegate) during their User Proving Session (UPS).
    • For each local execution, the user generates a ZK proof (a CFC Proof) attesting that the execution was performed correctly according to the contract's defined logic and given their specific starting CSTATE for that contract.
    • Implication: The Psy network (Realms, Coordinators, Proof Miners) does not re-execute smart contract logic. It only verifies the ZK proofs submitted by users. This massively offloads computational work from the network.
  3. ZK-Native by Design (Dapen Toolchain):

    • Smart contracts on Psy are written in high-level languages (e.g., a TypeScript/JavaScript-inspired syntax) and compiled into verifiable ZK circuits (CFCs) using the Dapen (DPN) toolchain.
    • The contract logic itself is embedded within these circuits.
    • Implication: Every smart contract function call is inherently a ZK-proven operation. This allows for strong privacy (sensitive inputs to a CFC need not be revealed on-chain) and verifiable computation.
  4. Global Read Access (Historical):

    • While a user's CFC execution only writes to their own CSTATE, it can read any data from the global blockchain state as it was finalized in the previous block.
    • This includes:
      • Other users' ULEAF data (e.g., balances, UCON roots) from the GUSR.
      • The CSTATE root of another user for a specific contract (via that other user's UCON root). The CFC can then request the actual CSTATE data from a DA Miner/Realm to perform read operations based on that historical root.
      • Global contract definitions (CLEAF data) from GCON.
    • Implication: Contracts can access and react to global information, but because reads are historical, read-write race conditions common in traditional systems are avoided.

Defining a Psy Smart Contract

A Psy smart contract definition involves several components:

1. Contract Logic (Source Code):

  • Written in a Dapen-compatible (Rust/TypeScript) high-level language.
  • Defines state variables (which will reside in each user's CSTATE) and functions (which will be compiled into CFCs).

2. Compilation to CFCs:

  • The Dapen toolchain compiles each public function (e.g., mint, transfer, claim) into a separate DapenContractFunctionCircuit (CFC).
  • During compilation, Dapen also generates:
    • Verifier Data for each CFC: This data is required to verify a ZK proof generated by that CFC.
    • Circuit Fingerprint for each CFC: This is the hash of the CFC's verifier data, uniquely identifying the circuit logic.
    • An ABI (Application Binary Interface) for the contract.

3. Contract Function Tree (CFT):

  • For each deployed contract, a CFT is constructed. This is a Merkle tree.
  • The leaves of the CFT are the circuit fingerprints of all the valid, executable functions (CFCs) of that contract, mapped by a Function ID.
  • The root of this CFT is a crucial piece of metadata stored on-chain.
  • Purpose: The CFT acts as a whitelist. When a user executes a CFC locally and submits its proof, the UPSCFCStandardTransactionCircuit (during the UPS) verifies that the fingerprint of the executed CFC is present in the contract's official CFT (whose root is part of the global GCON state, anchored to the session's checkpoint). This prevents users from executing arbitrary or unauthorized code versions.

Deploying a Smart Contract

Deploying a smart contract on Psy involves submitting its definition and compiled components to the network, which are then recorded in global state trees.

Process:

  1. Local Compilation: The developer compiles their smart contract source code using the Dapen toolchain. This produces:
    • The bytecode or definition of each CFC.
    • The verifier data for each CFC.
    • The circuit fingerprint for each CFC.
    • The contract's ABI.
  2. Construct CFT: The developer (or deployment tool) constructs the CFT by creating a Merkle tree from the fingerprints of all the contract's functions.
  3. Prepare CLEAF Data: The PsyContractLeaf (CLEAF) data is prepared. This includes:
    • deployer_hash: An identifier of the deploying user/entity.
    • contract_function_tree_root: The root of the CFT constructed in step 2.
    • contract_state_tree_height: The required Merkle tree height for the per-user CSTATE trees associated with this contract. This determines the maximum number of storage slots per user for this contract.
  4. Submit Deployment Transaction: The deployer initiates a special global transaction (orchestrated by a Coordinator) to deploy the contract.
    • Circuit: BatchDeployContractsCircuit (executed by Proof Miners).
    • Action: This circuit takes a batch of CLEAF data as input.
    • Proves:
      • The correct batch append of the new CLEAF(s) to the GCON (Global Contract Tree).
      • The hash of each provided CLEAF witness matches the data actually appended to the GCON.
      • The operation respects the deploy_contract_circuit_whitelist.
  5. On-Chain Storage (Conceptual):
    • The CLEAF data (including the CFT root) is stored as a new leaf in the GCON. The Contract ID is typically the index of this leaf in GCON.
    • The actual CFC bytecode/definition and verifier data are made available through a content-addressable system, often stored by Coordinators and/or DA Miners. Users' clients fetch this data when they need to execute a CFC locally for the first time. The CFT fingerprint ensures they fetch and execute the correct, whitelisted version.

Smart Contract Execution Flow (Recap)

  1. User Intention: User decides to call a function (e.g., transfer) on a contract (identified by Contract ID).
  2. Client Software:
    • Fetches the contract's CLEAF from GCON (via a Realm/Coordinator) to get the CFT root and CSTATE height.
    • Fetches the target function's CFC definition/bytecode and verifier data (if not cached), verifying its fingerprint against the CFT (using a Merkle proof for the fingerprint in the CFT).
    • Retrieves the user's current CSTATE root for this Contract ID from their UCON (as of the start of the UPS or previous step).
    • Retrieves necessary historical CSTATE leaf data (from DA Miners/Realms) if the CFC needs to read specific storage slots.
  3. Local Execution (CFC):
    • The client executes the fetched CFC locally, providing the user's current CSTATE root, function arguments, and other contextual data (e.g., session_proof_tree_root).
    • A CFC Proof is generated.
  4. UPS Integration:
    • The CFC Proof is verified by UPSCFCStandardTransactionCircuit (or similar) within the UPS.
    • This circuit also verifies:
      • The function's fingerprint is in the contract's official CFT.
      • The user's UCON is correctly updated to reflect the new CSTATE root produced by the CFC.
  5. End Cap & Submission: The UPS is finalized with an End Cap proof and submitted to a Realm.

State Management and Data Availability

  • CSTATE Data: The actual key-value pairs of a user's CSTATE for a contract are not directly part of the UCON or GUSR. Only the root hash of the CSTATE is stored in the UCON leaf for that contract.
  • State Deltas: When a user submits an End Cap proof, they also submit the "state deltas" – the actual changed leaf values in their CSTATE(s).
  • DA Miners & Realms: Realms receive these deltas, store them, and relay them to DA Miners. DA Miners are responsible for persistently storing this granular CSTATE data and making it available to users who need to read it (either their own for future transactions or others' historical state).
  • Reading State: When a CFC needs to read a value from the user's CSTATE, the client provides the leaf value and a Merkle proof showing that leaf is part of the start_contract_state_tree_root given to the CFC. The CFC verifies this proof before using the value. Similarly for reading other users' historical state.

Implications of Psy's Smart Contract Model

  • Enhanced Scalability: Massively parallel execution due to isolated user state.
  • Improved Privacy: Sensitive computation can occur within CFCs locally without exposing raw data on-chain. Only the proof of correct execution is public.
  • Verifiable Off-Chain Computation: Complex logic can be executed off-chain (locally by the user) with on-chain ZK verification, reducing on-chain load.
  • Race Condition Elimination: Localized writes and historical global reads prevent common concurrency issues.
  • Gas Efficiency for Users: The primary "cost" for a user is generating local proofs. Network fees are for proof aggregation and data storage, which are more stable and less prone to auction dynamics due to Psy's architecture. A user can bundle many local contract interactions into one End Cap proof, with network costs primarily dependent on the size of the End Cap proof (constant) and the number of distinct state slots modified across all their transactions.
  • New Design Patterns:
    • Asynchronous Interactions: The sent_to_others/claimed_from_others pattern in the token example is common for cross-user value transfer. User A proves they've "sent" (debited themselves, recorded intent). User B later proves they "claim" (credits themselves, referencing User A's recorded sent amount).
    • Agent-Oriented Programming: Contracts can be designed to interact with autonomous agents (SDKey users without private keys) whose behavior is provably constrained by their signature circuits.

Psy's smart contract system, while different, offers a powerful, scalable, and private platform for developers to build the next generation of decentralized applications. The Dapen toolchain aims to abstract much of the underlying ZK complexity, allowing developers to focus on application logic.

Copyright © 2025 Psy Protocol. All rights reserved.