● Documentation

Carpe Diem Protocol — Whitepaper

How the Carpe Diem protocol works — a decentralized marketplace for AI inference on Base.

Decentralized Marketplace for AI Inference Credits


Version: 5.0 Date: May 2026 Authors: Carpe Diem Core Team — Lumen Labs

This whitepaper describes the Carpe Diem protocol as deployed and live on Base mainnet (since May 2026), following the closure of the internal AudiBot security audit (2026-05-02). The fee + treasury layer is described in full. A future tokenomics layer is intentionally not covered here and will be detailed in a separate document published only after an external security audit, funded by accumulated protocol revenue, is completed.


Table of Contents

  1. Executive Summary
  2. Introduction
  3. Technical Architecture
  4. Product
  5. Economic Model
  6. Security
  7. Roadmap
  8. Risk Framework
  9. Conclusion

1. Executive Summary

Carpe Diem is a decentralized protocol that creates the first AI inference credit marketplace for the Venice.ai ecosystem. It allows holders of unused API credits to monetize them, and consumers to access AI inference at a reduced price — with no prior DIEM staking required.

The protocol rests on three pillars: a secure proxy in a Trusted Execution Environment (TEE) that handles multi-provider API request routing and billing without ever exposing provider keys; an on-chain escrow on Base L2 that secures deposits, executes settlements, and distributes revenue via automatic swap to DIEM; and a credit system where consumers purchase credits (100 credits = $1) to pay for inference on a pay-as-you-go basis.

For providers, Carpe Diem turns idle Venice API credits into passive income paid in DIEM (65% of dynamic revenue), strengthening the Venice ecosystem with every transaction. For consumers, the protocol offers pay-as-you-go access to Venice AI inference at a lower cost than direct Venice AI use, with dynamic pricing and the ability to deposit from any token on any chain.


2. Introduction

2.1 Context: Venice.ai

Venice.ai is a decentralized AI inference platform that provides private, uncensored access to leading large language models (see Venice documentation). Its economic model is built around a dual-token system. VVV is the foundational token: staking it grants a pro-rata share of Venice's total AI compute capacity, measured in DIEM. Staked VVV can be further locked to mint DIEM — a tokenized compute asset where each DIEM staked grants $1 per day in renewable API credits across all available models. DIEM is freely tradeable on decentralized exchanges, making AI compute a liquid, ownable asset. For users who prefer not to hold tokens at all, Venice also offers direct credit purchases through Pro accounts or developer API access.

This model positions VVV holders as owners of a share of Venice's inference infrastructure — as GPUs get cheaper and models more efficient, the same stake produces more compute over time.

2.2 The Problem

Venice's model creates structural inefficiencies on both sides of the market. Large DIEM stakers accumulate daily credits they do not fully consume; these credits expire at the end of each day, representing latent uncaptured value. DIEM holders who believe in the long-term compute thesis but do not need the inference capacity have no way to earn yield on their tokens beyond credits they may never use. And on the demand side, consumers who purchase access — whether through a Pro account or by buying API credits directly — pay full price, with no way to benefit from the surplus capacity sitting idle in the staking pool.

2.3 The Solution: Carpe Diem

Carpe Diem is a peer-to-peer marketplace and an API liquidity protocol that solves this dual inefficiency.

Providers delegate their Venice API keys into a secure environment (TEE), where their keys never leave volatile memory. The protocol routes consumer requests across multiple providers using a composite scoring algorithm, maximizing uptime and distributing load. Consumers purchase credits (100 credits = $1) using any token from any chain, and access Venice inference via a standard OpenAI-compatible API at a lower cost than direct Venice AI use. After each request, the protocol bills the consumer per token consumed, accumulates debt off-chain, and periodically settles on-chain — deducting a fixed protocol fee, then splitting the dynamic portion — 65% to providers as DIEM and 35% retained as protocol revenue.

The result is a system where every idle Venice API credit finds a user, every consumer pays only for what they consume, and every transaction generates buy pressure on DIEM — turning Carpe Diem into a permanent buy engine for the Venice ecosystem.

2.4 Competitive Landscape

The decentralized AI inference space is increasingly active. Carpe Diem's positioning is not "another LLM gateway" but a TEE-attested marketplace for surplus Venice capacity — a category with very specific structural moats.

DIEMpool (announced 2026-04-13 by Will Harborne, founder of Rhino.fi / DeversiFi) attacks the same pool of idle Venice credits. As of this writing the project has no public technical documentation, no live frontend, and no published architecture; positioning is presumed to lean on Rhino.fi's existing DEX distribution. Carpe Diem differentiates on three axes that are hard to replicate after the fact: hardware-attested TEE custody of provider keys, OpenAI and Anthropic Messages compatibility from day one, and a credits-not-deposits design that keeps the protocol within the regulatory perimeter of a service vendor (Lumen Labs, Swiss association under Art. 60 CC) rather than a financial intermediary.

Bittensor inference subnets — Chutes (SN64) and Targon (SN4) — sell raw decentralized inference at prices subsidized by TAO emissions ($0–0.30 per million tokens for Chutes; Manifold's Targon adds Intel TDX confidential compute backed by 1500 GPUs and an Intel-co-authored paper). They compete on price and infrastructure, not on arbitrage of pre-paid surplus. Carpe Diem does not try to undercut their floor; it offers a categorically different product — a discount on Venice-specific models (uncensored, privacy-first) that simply do not exist on Bittensor subnets, with an end-user experience indistinguishable from any OpenAI-compatible client.

Centralized aggregators — OpenRouter, Together.ai, Replicate, Helicone — are excellent comparables for the developer experience layer (one API, many models) but operate as for-profit pass-through resellers (typically Venice base price + 5–15% markup) without any TEE guarantees. Carpe Diem's dynamic pricing curve, capped at 100% of Venice base price, makes the protocol structurally cheaper than these aggregators at any utilization level, while its TEE attestation gives it a privacy posture none of them can match.

Adjacent TEE-inference projects — Atoma Network (Sui), Phala's own inference offering, and others — build similar hardware guarantees but on different ecosystems and without an existing surplus-capacity pool to monetize. They are technical peers, not market substitutes.

The summary is: Carpe Diem owns a category — TEE-attested arbitrage of Venice surplus — that is bounded above by Venice's base price (no downside risk on competitive pressure from generic aggregators), bounded below by hardware-rooted privacy (no commoditization race against subsidized DePIN), and protected by a regulatory framing (credits not deposits) that any token-based or wallet-based competitor would have to relitigate from scratch.


3. Technical Architecture

3.1 Overview

  ┌──────────────┐ 1. Request  ┌──────────────────────────┐ 2. Forward  ┌────────────────┐
  │   Consumer   │────────────▶│      Operator (TEE)       │────────────▶│  Venice.ai API │
  │              │             │                           │             │                │
  │  SDK / HTTP  │◀────────────│  KeyVault (RAM)            │◀────────────│  Provider 1    │
  │  cdm_ Key    │ 4. Response │  Multi-Provider Router     │ 3. Response │  Provider 2    │
  └──────────────┘             │  Billing Engine            │             │  Provider N    │
                               │  Credit System             │             └────────────────┘
                               │  (100 credits = $1)        │
                               └─────────────┬─────────────┘
                                             │
                                             │ 5. Settlement (periodic)
                                             ▼
                               ┌────────────────────────────┐
                               │  Smart Contracts (Base L2)  │
                               │  CarpeEscrow (UUPS Proxy)   │
                               └─────────────┬──────────────┘
                                             │
                                             │ Fee + 65/35 Split
                                            │ (surcharge → protocol,
                                            │  dynamic → 65% provider / 35% protocol)
                                             ▼
                               ┌────────────────────────────┐
                               │     DEX Swap (LI.FI)        │
                               │     USDC → DIEM             │
                               └────────────────────────────┘

The architecture comprises three independent modules.

The TEE Operator is a proxy server running inside a Trusted Execution Environment. It receives requests from consumers, verifies their credit balance, selects the best available provider through a composite scoring algorithm, injects the provider's API key, and relays the request to Venice.ai. The response is streamed back directly to the consumer without buffering. Multiple providers are supported simultaneously, with automatic failover and load distribution.

The Smart Contracts on Base L2 manage deposits (in USDC or any supported token via cross-chain swap), escrow, consumption settlement, and revenue distribution through automatic USDC→DIEM conversion with a two-component fee structure: a fixed protocol fee plus a 65/35 split of the dynamic portion between providers and the protocol.

The Frontend is a Next.js interface allowing providers and consumers to manage their accounts, track activity, purchase credits, and interact with the protocol.

3.2 Blockchain: Base L2

Carpe Diem is deployed on Base, the Ethereum Layer 2 incubated by Coinbase. This choice aligns naturally with Venice.ai, whose VVV and DIEM tokens already live on Base. Transaction fees cost a fraction of a cent, making batch settlement of micro-payments viable. Confirmations take approximately 2 seconds, compatible with the protocol's billing rhythm. Base also offers deep native USDC liquidity (via Coinbase) and access to swap aggregators like LI.FI for USDC→DIEM conversion.

3.3 TEE Operator (Trusted Execution Environment)

The Operator is the central component of the protocol. It acts as a secure proxy between consumers and Venice.ai.

3.3.1 KeyVault — Volatile Memory Key Management

The KeyVault is the secrets management module. Plaintext keys are never written to disk, never logged, serialized, or transmitted — they exist only in volatile RAM. An optional AES-256-GCM encrypted backup allows persistence across reboots; providers may opt out to keep their key strictly in RAM. Key provisioning is authenticated via cryptographic signature from the administrator. At rest in memory, keys are encrypted and obfuscated, ensuring that even a memory dump would not reveal plaintext secrets. Keys are decrypted only for the minimum duration needed to authenticate a request to Venice, then immediately zeroed.

3.3.2 HTTP 402 Proxy — Payment Required

The protocol implements the HTTP 402 (Payment Required) standard for programmable micro-payments. When a consumer sends an API request, the proxy identifies their wallet, calculates the available credit balance (their on-chain deposit minus the consumption tracked in the operator's credit ledger), and either forwards the request to Venice or returns an HTTP 402 response indicating the credits available and credits required to proceed. After a successful request, the cost — calculated from the prompt and completion tokens reported by Venice.ai — is drawn from the consumer's ledger balance and added to the batch owed at the next on-chain settlement.

3.3.3 Authentication

The protocol supports two authentication methods. For interactive use, the consumer signs a unique message with their wallet to generate a JWT session token, linked to the wallet address with a configurable validity duration. The token is used via a standard Authorization: Bearer <token> header, without requiring a new signature for each request. Sessions are proactively refreshed before expiry, and expired tokens trigger an automatic refresh-and-retry cycle for a seamless experience.

For programmatic and long-lived integrations, the protocol issues persistent API keys (prefixed cdm_) that function identically to the JWT tokens but do not expire. This allows developers and AI agents to integrate Carpe Diem without wallet interaction after initial setup.

3.3.4 Multi-Provider Routing

The operator supports multiple Venice API providers simultaneously and distributes requests across them using a composite scoring algorithm. Each provider is scored on three dimensions: success rate (50% weight, time-decayed), latency (30% weight), and remaining capacity (20% weight, based on recent request volume). Providers are selected via weighted random sampling — higher-scoring providers receive more traffic, but all providers maintain a minimum selection probability to allow recovery from temporary failures.

When a request fails, the operator automatically retries with an alternate provider, cycling through all available providers before returning an error to the consumer. Specific failure modes trigger targeted responses: authentication errors cause the offending provider's key to be removed, while rate limits and capacity exhaustion simply route to the next available provider. After a period of inactivity, a provider's score resets to a neutral value, giving it a fresh chance to prove its reliability. Each successful response includes an X-Provider-Id header — an HMAC-SHA256 truncation of the upstream provider — so SDK clients can pseudonymously attribute failures to a specific marketplace participant for debugging without exposing the provider's wallet address.

3.3.5 API Surface

The operator exposes more than the OpenAI Chat Completions endpoint. Three families of routes are wired in:

  • OpenAI-compatible (/v1/chat/completions, /v1/models) — drop-in replacement for any OpenAI SDK.
  • Anthropic Messages (/v1/messages) — Claude-style API for direct compatibility with Claude Code, Cursor, Cline, and other Anthropic-native clients. The operator translates between OpenAI-format upstreams and Anthropic-format clients transparently.
  • Image and video generation (/v1/image/generate, /v1/image/edit, /v1/video/...) — pay-per-asset routes that bill at fixed prices set per model.

A public /v1/capacity?model=... endpoint exposes the active provider count, available requests-per-minute, queue depth, and a health: healthy | degraded | saturated indicator, allowing batch clients to calibrate concurrency before submitting jobs. A public /v1/models endpoint lists supported models with their dynamic and Venice base prices, plus tier rate limits when known.

3.3.6 Settlement-Time Resilience

Each consumer hold (the credit reservation placed before forwarding a request to Venice) is wrapped in a BillingUnitOfWork — an idempotent settle abstraction that guarantees the hold is released even if the proxy throws between balance check and provider response. Holds and pending debts are persisted to encrypted SQLite (pending_debts table) so an operator restart does not lose any in-flight billing state. The settlement loop adapts its frequency to the total pending debt — gas-frugal at low volume, more aggressive when exposure rises.

3.4 Smart Contracts (Base L2)

The financial core of the protocol relies on a set of smart contracts deployed on Base.

3.4.1 CarpeEscrow — Main Contract

The CarpeEscrow contract manages the entire financial cycle. Consumers deposit USDC into the contract, crediting their on-chain balance. For consumers who hold other tokens or are on a different chain, the contract also supports depositWithSwap(), which accepts any supported ERC-20 token, swaps it to USDC via a pre-approved router contract, and credits the resulting balance — all in a single transaction. Cross-chain deposits are handled through LI.FI integration at the frontend level.

Credits purchased through the escrow are non-refundable — there is no withdrawal function. This simplifies the contract's security model and aligns with the protocol's credit-based design: consumers buy a service (AI inference), they do not deposit funds with a custodian. This positions the protocol as a service vendor rather than a financial intermediary, keeping it within the regulatory perimeter of a Swiss association (Lumen Labs) and avoiding heavier statutes such as PSAN/MSB licensing.

When the operator settles accumulated consumption, it calls the batchCharge() function, which settles every provider in a single transaction: it draws the aggregate consumption from the escrow's pooled USDC, executes one USDC→DIEM swap via a whitelisted DEX router, and applies a two-step fee structure — a fixed protocol fee is deducted first, then the remaining dynamic portion is split 65% in DIEM to each provider and 35% retained as protocol revenue. Consumer balances are tracked in the operator's credit ledger and drawn down per request; batchCharge() reconciles the aggregate on-chain, rather than charging each user individually.

V8 Treasury — Multi-Stablecoin Diversification. While consumers always deposit and are charged in USDC, the protocol's accumulated treasury is not forced to remain in USDC alone. The V8 upgrade adds a token catalogue (registered via addToken) that allows the treasury to hold sUSDS, USDS, GHO and other audited stablecoins alongside USDC, each with a maximum allocation in basis points. A whitelisted-router swapTreasury() function rebalances between stablecoins, enforced by a post-swap invariant that the liquid USDC balance must remain greater than or equal to the sum of all consumer balances — depositors are never starved of redeemable USDC by treasury operations. Treasury holdings can also be parked in yield-bearing vaults (Morpho, Aave, sUSDS) via depositToYield / withdrawFromYield, with snapshot-based accounting that handles vault deposit fees and rounding without drift. A Chainlink-fed depeg guard automatically pauses any token whose price strays beyond a configured threshold, blocking new treasury swaps into the affected token until a guardian or operator confirms the price has returned to peg.

The contract follows the UUPS proxy pattern, allowing the logic to be upgraded while preserving the contract address and all user balances. Upgrades are gated by upgradeToAndCallVersion(impl, initData, expectedVersion) — an atomic wrapper that asserts both that the target version is exactly current + 1 (no skips) and that the post-upgrade _initializedVersion() actually reached the expected value. This pattern catches the four upgrade-time failure modes (forgotten init, wrong selector, version skip, silent init revert) at the transaction boundary rather than after the fact.

3.4.2 On-Chain Security

The contracts are built with Solidity 0.8.22 and inherit from OpenZeppelin's Upgradeable v5 library. Access control distributes responsibilities across four roles: OPERATOR_ROLE (the TEE proxy, sole account authorized to trigger settlements and emissions), TREASURY_ROLE (treasury swaps and yield routing), GUARDIAN_ROLE (pause / depeg response), and DEFAULT_ADMIN_ROLE (parameter changes and role management). All critical functions are protected against recursive call attacks via OpenZeppelin's ReentrancyGuard.

Swap call protection — three layers. Swap operations (charge and depositWithSwap) execute arbitrary calldata against external DEX routers, which would normally be an unbounded attack surface if the operator key were compromised. The protocol restricts this in three independent ways:

  1. Per-target selector whitelistallowedSelectors[router][selector] is an admin-controlled mapping that lists exactly which function selectors on which routers are allowed. This blocks alternate selectors on the same router (e.g. swapAndCall, transferFrom, multicall) that could be coerced into draining funds. A master switch (requireSelectorWhitelist) enables staged rollout — admin populates the selector list, then flips the flag.
  2. Allowance reset around the call — the contract approves the router for exactly the swap amount immediately before the call, then resets the allowance to zero immediately after. This bounds the maximum funds the router can pull in any single transaction to the explicitly-approved amount.
  3. Delta balance check — after the call returns, the contract asserts usdcBefore - usdcAfter <= amount. Even a regression in the allowance reset cannot let the swap consume more than the user authorized.

Settlement guard rails. Each settlement enforces a minimum acceptable DIEM amount (slippage protection against MEV sandwiches), a per-transaction cap (maxChargePerTx = 100 USDC), and a per-wallet daily cap (maxChargePerDayPerWallet = 500 USDC) — bounding the worst-case damage of a compromised operator key.

Governance — Multisig + Timelock. On mainnet, DEFAULT_ADMIN_ROLE is held by a Gnosis Safe (3-of-N signers) wired into a TimelockController with a 48-hour-to-7-day delay on sensitive operations. All upgrades, parameter changes, and role grants flow through the timelock, giving users a window to inspect proposed changes and exit before execution. An emergency pause mechanism allows the guardian to suspend operations within a single block if a vulnerability is discovered, without going through the timelock.

3.4.3 Mainnet Release Process

Mainnet deployments are gated by a CI-driven release workflow (.github/workflows/release.yml) that triggers automatically on every v* tag push. The workflow re-runs the full CI matrix on the tagged commit, compiles the contracts with deterministic settings, and emits a release-manifest.json containing the SHA-256 of the runtime bytecode for each contract the deployment will publish. The same workflow also runs the deployment script against a Hardhat fork of Base mainnet, capturing a full transcript so any post-merge regression (missing init, wrong selector, broken role grant) surfaces before any real ETH is spent.

The manifest and dry-run transcript are attached to a draft GitHub Release. Each multisig signer, before signing the on-chain admin transaction on Safe, recompiles the contracts locally at the same tag and compares hashes against the manifest. A mismatch means CI built different code than what the signer is about to authorize — and the signer refuses. This pattern, standard in the L2 governance ecosystem, gives the multisig a tamper-evident artifact to verify against, closing the supply-chain gap between code review and deployment.

3.5 Billing Engine

The billing system combines on-chain verification and off-chain tracking to optimize gas costs while preventing credit overruns.

3.5.1 Real-Time Verification

For each request, the proxy calculates the actual available balance from the operator's credit ledger, anchored to the consumer's on-chain deposit:

available_balance = on_chain_deposits (cached) - consumed_in_operator_ledger - active_holds

The operator ledger is the live source of the spendable balance — it is drawn down on every request, while the on-chain escrow is reconciled in aggregate at settlement. If the available balance is insufficient to cover the estimated request cost, the request is rejected with HTTP 402. Holds are placed atomically before forwarding each request, preventing concurrent requests from spending the same balance.

3.5.2 Adaptive Settlement

The operator periodically settles accumulated off-chain debts on-chain. Rather than a fixed interval, settlement frequency adapts to the total pending debt: small debts are settled less frequently to save gas, while large debts trigger more frequent settlement to reduce exposure. Each settlement aggregates the pending amounts owed to every provider into a single batchCharge() call on the escrow contract, allowing hundreds of API requests across all providers to be settled in one on-chain transaction.

3.5.3 Pricing

The cost per request is calculated from the tokens consumed (prompt + completion) as reported by Venice.ai, multiplied by a dynamic price factor plus a fixed protocol fee. The demand factor is the higher of two signals: (1) a sigmoid function of how much of the daily DIEM pool has been consumed network-wide — capturing time-of-day scarcity — and (2) a per-request footprint, the request's size relative to the remaining capacity of the providers that can serve it. Taking the maximum means a consumer pays for their own demand: a large request (e.g. a video) consuming a big share of scarce capacity is priced higher than a small one at the same moment, while small requests track the pool price. Prices range between 15% and 100% of Venice's direct rates — always at least as cheap as Venice, and significantly cheaper at low utilization. The pool sigmoid stays near the floor while the pool is healthy and ramps up around the 70% utilization mark, where the daily pool begins to run scarce.


4. Product

4.1 Credit System

The protocol's unit of account is the credit: 100 credits equals $1, which equals 1 USDC on-chain. Consumers purchase credits through a unified deposit interface powered by LI.FI: the user selects any token on any supported chain, and the widget handles bridging, swapping, and depositing into the escrow contract in a single flow. For users already holding USDC on Base, a direct deposit is also available.

Credits are non-refundable. Once purchased, they can only be consumed through API usage. This one-way design simplifies the escrow contract, eliminates withdrawal-related attack vectors, and aligns incentives: every credit deposited will eventually flow through the protocol as revenue.

Balances are displayed with one decimal place and comma separators (e.g., "5,000.0 credits"). All user-facing interfaces use credits as the primary unit; the underlying USDC accounting remains internal to the smart contracts and billing engine.

4.2 Provider Flow

A provider is a DIEM holder staked on Venice.ai who wishes to monetize their unused API credits.

The provider connects their wallet on the Carpe Diem dashboard and signs a session. They then submit their Venice API key via the dashboard — the key is transmitted to the TEE and its plaintext stored exclusively in volatile memory. An encrypted backup may persist on disk unless the provider opts for RAM-only mode. The provider can revoke their key at any time.

Each time a consumer uses the provider's credits, the protocol bills the consumer, deducts a fixed protocol fee, and converts 65% of the remaining dynamic revenue into DIEM via automatic swap. The resulting DIEM is held by the escrow contract until the provider claims it through the dashboard — a deliberate design choice that follows the "pull over push" pattern, preventing any single provider from blocking settlements for others. The protocol fee plus 35% of the dynamic revenue is retained as protocol revenue.

The provider tracks their activity in real time on a dedicated dashboard: routed requests, consumed credits, generated DIEM revenue, model breakdown, and daily trends. Multiple providers can operate simultaneously — the protocol's routing algorithm distributes traffic across all active providers based on performance.

4.3 Consumer Flow

A consumer is a developer, application, or AI agent that wishes to access Venice.ai inference without staking DIEM.

The consumer connects their wallet on the dashboard and purchases credits through the deposit interface, using any token from any supported chain. Their credit balance is immediately available. To authenticate API requests, the consumer either signs a message with their wallet to generate a session token, or generates a persistent API key (prefixed cdm_) for long-lived integrations.

From there, the consumer sends requests to the Carpe Diem endpoint, which is fully compatible with the OpenAI API format. The experience is identical to using any standard AI API — existing OpenAI client libraries work out of the box by simply changing the base URL and API key. The consumer is billed per token consumed, and their available credit balance is visible in real time on the dashboard. When the balance becomes insufficient, the API returns an HTTP 402 response with the credits available and credits required to proceed.

4.4 Dynamic Pricing

The per-request price is not fixed. It is determined dynamically as the higher of two demand signals, so each consumer pays for their own demand rather than inheriting the previous user's:

  1. Pool utilization — a sigmoid function of how much of the daily DIEM pool has been consumed. When the pool is mostly free, the price drops to as low as 15% of Venice's direct rates; as it is consumed, the price rises toward the ceiling, ramping up around the 70% utilization mark where the daily pool runs scarce.
  2. Request footprint — the request's size relative to the remaining capacity of the providers that can serve it. A large request (e.g. a video) that consumes a big share of scarce capacity pays a premium for its footprint, while a small request stays near the pool price.

Both signals are bounded to a floor of 15% and a ceiling of 100% of Venice's direct rates (the protocol fee included), so a consumer never pays more than going to Venice directly, and using the footprint of remaining (not static) capacity keeps the pool's scarcity-rationing intact.

This mechanism creates a natural equilibrium: low prices attract consumers (increasing demand), while higher prices attract providers (increasing supply). The price always remains at or below the cost of using Venice directly, preserving the marketplace's core value proposition.

4.5 Developer SDK

Carpe Diem is fully compatible with the OpenAI API format. No custom SDK is required — any existing OpenAI client library works by simply pointing it to the Carpe Diem endpoint.

Python:

from openai import OpenAI

client = OpenAI(
    base_url="https://carpe-diem.xyz/api/operator/v1",
    api_key="cdm_your_api_key"
)

response = client.chat.completions.create(
    model="llama-3.3-70b",
    messages=[{"role": "user", "content": "Hello"}]
)
print(response.choices[0].message.content)

JavaScript / TypeScript:

import OpenAI from 'openai';

const client = new OpenAI({
    baseURL: 'https://carpe-diem.xyz/api/operator/v1',
    apiKey: 'cdm_your_api_key',
});

const response = await client.chat.completions.create({
    model: 'llama-3.3-70b',
    messages: [{ role: 'user', content: 'Hello' }],
});
console.log(response.choices[0].message.content);

This zero-integration approach means any application already using the OpenAI API format can switch to Carpe Diem with a two-line configuration change. Models from multiple providers — including open-source and frontier models — are accessible through this single, unified interface.


5. Economic Model

5.1 Fee Structure

Every settlement transaction follows a two-step process. The consumer's USDC debt is swapped to DIEM via a decentralized exchange, and the resulting DIEM is distributed through a two-component fee structure.

Step 1 — Protocol Fee: A fixed percentage of the Venice base cost is deducted as a protocol fee, regardless of demand. This fee goes entirely to the protocol.

Step 2 — Dynamic Split: The remaining portion — which varies with demand — is split between the provider (65%) and the protocol (35%).

                   100% USDC (consumer debt)
                           │
                      USDC → DIEM swap
                       (via DEX on Base)
                           │
                    ┌──────┴──────┐
                    │             │
            Dynamic portion   Protocol fee
                    │         (100% protocol)
             ┌──────┴──────┐      │
             │             │      │
          65% DIEM     35% DIEM   │
         (Provider)  (Protocol)───┘
              │            │
         Claimable    Protocol revenue
         on dashboard

This structure is enforced on-chain by the escrow contract and cannot be altered by the operator. At low demand, the protocol fee represents a larger share of the total cost, ensuring sustainable protocol revenue even during quiet periods. At high demand, the dynamic portion dominates, and the effective split approaches 65/35.

Providers receive DIEM — not USDC — ensuring that every transaction generates direct buy pressure on the DIEM token.

During the incubation phase, protocol revenue funds operations: security audits, infrastructure, and ongoing development. In a later phase, the protocol's DIEM will be staked on Venice to generate its own API credits, making the protocol itself a provider and guaranteeing a minimum service capacity at all times — creating a self-reinforcing flywheel where usage funds the protocol's own compute infrastructure.

5.2 DIEM Buy Pressure

An important consequence of the protocol's design is the constant buy pressure on DIEM. Every dollar of consumption flowing through Carpe Diem is converted to DIEM on the open market — the protocol fee, the provider's share, and the protocol's share of the dynamic portion are all settled in DIEM, meaning 100% of marketplace volume translates into DIEM purchases.

Carpe Diem effectively acts as a permanent buy engine for the Venice ecosystem: the more inference volume the marketplace processes, the more DIEM is purchased on decentralized exchanges. This aligns the interests of Carpe Diem participants with DIEM holders and the broader Venice ecosystem.

5.3 Provider Incentives

Providers earn 65% of the dynamic portion of every transaction processed through their API credits, paid in DIEM. This revenue is proportional to the traffic routed through their keys — the more requests they serve, the more they earn. Revenue accumulates in the escrow contract and is claimable at any time through the provider dashboard.

For DIEM holders who are not fully utilizing their Venice API credits, this represents a new yield source: idle compute capacity that would otherwise expire daily is converted into additional DIEM income without any active management beyond the initial key provisioning.


6. Security

Security is at the core of the Carpe Diem architecture. The protocol handles third-party API keys and user funds — two assets that demand the highest protection standards.

6.1 TEE — Hardware-Enforced Zero-Knowledge

The operator runs inside a Confidential Virtual Machine (CVM) on Phala Cloud, protected by Intel TDX (Trusted Domain Extensions). The CPU hardware encrypts all RAM — even the hosting provider cannot read the operator's memory.

SSH access is permanently disabled. The Docker image is distroless (no shell, no debugging tools). No human — not even the protocol team — can access the running system. This is verifiable through public attestation at trust.phala.com.

Provider API keys are XOR-obfuscated in memory and AES-256-GCM encrypted at rest. They are decrypted only for the instant needed to authenticate a request to Venice, then immediately wiped from memory. Keys survive operator restarts through an encrypted backup mechanism protected by Phala's end-to-end encrypted secrets.

A comprehensive security crash test confirmed that all attack vectors are blocked: SSH, docker inspect, tcpdump, /proc memory dumps, and shell execution all fail against the production system.

6.2 Escrow — Fund Protection

The smart contracts protect user funds via several mechanisms. All critical functions are protected against recursive call attacks. Access control separates roles with minimum necessary privileges — only the TEE operator can trigger settlements. Swap operations are restricted to pre-approved router contracts. Credits are non-refundable by design, eliminating an entire class of withdrawal-related attack vectors.

The contract follows the UUPS proxy pattern, allowing logic upgrades while preserving the contract address and all user balances. Upgrade authority is restricted to the administrator role, and each upgrade is a deliberate, auditable on-chain transaction.

6.3 Protection Against MEV Attacks

USDC→DIEM swaps are protected against sandwich attacks — a type of market manipulation where an attacker front-runs a swap to profit from the price impact. Each settlement call includes a minimum acceptable DIEM amount, guaranteeing a worst-case exchange rate. If the actual rate falls below this threshold, the transaction reverts entirely rather than executing at a loss. Token approvals are reset before each operation to prevent accumulation of unused authorizations.

6.4 Circuit Breaker — Emergency Pause

The contract implements an emergency pause mechanism. If a vulnerability is discovered, the administrator can instantly suspend all operations — deposits, settlements, and swaps. Resumption requires an explicit action from the administrator after the issue is resolved. This provides a safety net against zero-day exploits while the protocol is in its early stages.

6.5 Privacy

The protocol is designed to minimize the personal data it handles. Consumer wallet addresses are pseudonymized before storage using HMAC-SHA256 — a one-way cryptographic hash that cannot be reversed. Logs are redacted: request bodies, authorization headers, and response content are never written to logs or metrics.

User prompts and LLM responses are never stored anywhere on the server. The only data recorded per request is the pseudonymized wallet hash, model name, token count, and cost. Conversation history exists exclusively in the user's browser (localStorage) and never leaves their device.

The protocol's privacy guarantees are publicly verifiable. A dedicated privacy page at carpe-diem.xyz/privacy displays live TEE status, and the hardware attestation can be independently verified at trust.phala.com. The protocol's privacy audit score is 9/10.

6.6 Audit and Transparency

The smart contract code is open-source and verifiable on blockchain explorers. The protocol maintains a comprehensive test suite of more than 600 unit and integration tests covering contracts, operator logic, and the frontend build.

A first internal security audit (AudiBot, 2026-05-02) covering 562 findings across the operator, smart contracts, frontend, and TEE infrastructure was completed and fully responded to (see docs/audit-response-2026-05-03.md). All critical findings were resolved or formally cadred — including the V9 per-target swap selector whitelist (C#1), the atomic upgrade pattern (C#2.1), the persistent debt SQLite store (C#5), and the wiring of the Safe multisig into the mainnet deployment script (C#7). The remaining critical concerns (key-management hardware module, on-chain replay nonce) have been deferred to the post-mainnet roadmap with an explicit risk rationale, on the basis that the credits-not-deposits design caps the worst-case impact of an operator key compromise to bounded credit burn rather than unbounded fund extraction.

The build pipeline includes SBOM (Software Bill of Materials) generation and cryptographic image signing for the operator, and a mainnet release CI workflow (see §3.4.3) that produces a tamper-evident bytecode manifest signers verify locally before authorizing on-chain deployments. An external security audit will be commissioned as soon as the protocol's accumulated DIEM revenue covers the cost — this audit is a hard prerequisite for any future tokenomics layer, and its delivery is the trigger condition for the publication of the companion Whitepaper v5-bis.


7. Roadmap

Phase 1 — Incubation (Completed)

The protocol is live on Base Sepolia (testnet) with all core components operational: hardware TEE proxy (Intel TDX on Phala Cloud) with multi-provider routing, on-chain escrow with UUPS upgradeability and the V8 multi-stablecoin treasury layer, credit system, adaptive billing engine with persistent debt store and idempotent hold lifecycle, OpenAI-compatible and Anthropic-compatible API surfaces, image and video generation routes, provider and consumer dashboards, privacy page with public attestation, and real-time monitoring with alerting. The first internal security audit (AudiBot, 2026-05-02) was completed and closed; all critical remediations are merged. The build pipeline includes SBOM generation, cryptographic image signing, and a mainnet release workflow that publishes a bytecode manifest for multisig-signer verification.

Phase 2 — Mainnet Launch (In Progress)

Deployment on Base mainnet with real USDC and DIEM. Swaps executed through LI.FI aggregator against live liquidity pools, gated by the V9 per-target selector whitelist. Legal entity (Lumen Labs, Swiss association under Art. 60 CC) established. Custom domain with HTTPS (carpe-diem.xyz). Production-grade TEE infrastructure on Phala Cloud (Intel TDX). Migration to a dedicated RPC provider (Alchemy or equivalent) for write-path resilience. DEFAULT_ADMIN_ROLE transferred to a Gnosis Safe multisig (3-of-N signers) wired into a 48-hour-to-7-day TimelockController. The protocol begins accumulating DIEM revenue in the multi-stablecoin treasury, with surplus optionally deployed into yield vaults (Morpho, Aave, sUSDS) via the V8 treasury functions — laying the groundwork for the self-sustaining flywheel described in Section 5.

Phase 3 — External Audit & Tokenomics Activation

Once accumulated protocol revenue covers the cost, an external security audit is commissioned. This audit is a hard prerequisite for any tokenomics layer. Upon successful completion of the audit, the protocol activates the tokenomics layer described in Whitepaper v5-bis — provider emissions, staking, and treasury buybacks — published as a separate document on the day of activation. The current document (v5) intentionally describes only the deployed and audited fee + treasury layer.

Phase 4 — Scale & Progressive Decentralization

Growth of marketplace volume, Venice end-to-end-encrypted inference integration (where supported by upstream models), progressive decentralization of operator and admin functions, and ongoing audit cadence funded by protocol revenue.


8. Risk Framework

8.1 Smart Contract Risks

Despite the use of audited libraries and a comprehensive test suite, smart contracts are experimental software. A bug could result in loss of funds. The UUPS proxy pattern allows upgrades to fix discovered vulnerabilities, but upgrades themselves carry risk — a faulty upgrade could compromise the contract's state. An external audit will be conducted as soon as the protocol's financial conditions allow.

8.2 TEE Risks

If the operator server goes down, the service is interrupted. Funds remain safe in the on-chain escrow, but API requests can no longer be served until the operator is restored. Provider API keys survive restarts through an encrypted backup mechanism. The operator runs in a hardware TEE (Intel TDX) with SSH disabled and a distroless Docker image — extraction of keys from memory is blocked at the hardware level. The TEE depends on the hosting provider (Phala Cloud) maintaining the confidential computing infrastructure; a failure at this level would require migration to an alternative TEE provider.

8.3 Market Risks

Carpe Diem depends on Venice.ai as the upstream inference provider. A change in Venice's terms of use, API key revocation, or service shutdown would directly impact the protocol. The automatic USDC→DIEM swap depends on liquidity available on Base DEXes — low liquidity could result in high slippage, though the minimum DIEM amount protection prevents execution at unfavorable rates.

8.4 AI-Specific Risks

The protocol proxies requests to large language models whose outputs may be incomplete, incorrect, or unreliable. Carpe Diem does not control, filter, or endorse model outputs. Users should not rely on AI-generated content as a sole source of truth, particularly for decisions with legal or financial consequences. The uncensored nature of Venice's inference models means that the protocol may relay content that would be restricted on mainstream AI platforms.

8.5 Operational Risks

The off-chain billing system introduces a risk of loss in case of operator failure between two settlements. Adaptive settlement intervals minimize this exposure, but a small window of unbilled consumption always exists. During the incubation phase, the protocol depends on the core team for operator management, key provisioning, and upgrades.

8.6 Regulatory Risks

The regulatory framework for DeFi protocols and AI services is evolving rapidly. Legislative changes in either domain could impact the protocol's ability to operate. Emerging AI regulations may impose content moderation or compliance obligations that conflict with the protocol's decentralized architecture. Lumen Labs, a Swiss association under Art. 60 CC, provides the jurisdictional framework for the protocol.


9. Conclusion

Carpe Diem solves a real inefficiency in the Venice.ai ecosystem: the under-utilization of API credits by DIEM stakers. By creating a decentralized marketplace, the protocol transforms idle compute capacity into revenue for providers and affordable inference access for consumers.

The architecture — TEE for key security, on-chain escrow for fund protection, HTTP 402 for programmable billing — is designed to be both secure and invisible to the end user. A developer integrates Carpe Diem like any other AI API, without worrying about the underlying blockchain mechanics.

Every transaction flowing through the protocol purchases DIEM on the open market, making Carpe Diem a permanent buy engine for the Venice ecosystem. As usage grows, the protocol accumulates the resources to stake its own DIEM on Venice, becoming self-sustaining — a flywheel where marketplace activity directly funds its own compute infrastructure.


This document is a technical whitepaper and does not constitute investment advice. Participation in the Carpe Diem protocol involves risks described in Chapter 8. Users should conduct their own research before engaging.