diff --git a/pages/blueprints/ai-agent-sandbox/dapp-and-indexer.mdx b/pages/blueprints/ai-agent-sandbox/dapp-and-indexer.mdx index 2b65fce..0e86922 100644 --- a/pages/blueprints/ai-agent-sandbox/dapp-and-indexer.mdx +++ b/pages/blueprints/ai-agent-sandbox/dapp-and-indexer.mdx @@ -1,41 +1,69 @@ --- title: AI Agent Sandbox Dapp and Indexer -description: Dapp metadata, iframe policy, and indexer requirements for the AI Agent Sandbox blueprint. +description: Dapp metadata, iframe policy, indexed state, and live health boundaries for AI Agent Sandbox. --- -# Dapp and Indexer +# AI Agent Sandbox Dapp and Indexer -The dapp should resolve the sandbox blueprint from first-party metadata, then render the hosted sandbox app through the trusted iframe path. +Tangle Cloud should launch the hosted sandbox app from metadata, then keep the raw protocol page one click away. -## Metadata Contract +The hosted app owns the sandbox UX. The protocol page owns raw state inspection. -| Field | Value | +## Metadata the dapp should use + +| Field | Current value in repo metadata | | --------------------------------- | ----------------------------------------------- | | `blueprintUi.displayName` | `AI Agent Sandbox` | | `blueprintUi.requestedSlug` | `ai-agent-sandbox` | | `blueprintUi.publisher.namespace` | `tangle` | -| `resources.serviceNoun` | `sandbox fleet` | -| `resources.resourceNoun` | `agent` | -| `externalApp.url` | `https://agent-sandbox.blueprint.tangle.tools/` | | `externalApp.mode` | `iframe` | +| `externalApp.url` | `https://agent-sandbox.blueprint.tangle.tools/` | + +The metadata also declares cloud, dedicated instance, and TEE instance modes. Use those records to route service creation to the right blueprint ID for the selected network. + +## Indexed state + +| State | Why the dapp needs it | +| --------------------------------------- | ----------------------------------------------------------- | +| Blueprint creation and metadata updates | Find the sandbox blueprint and app policy. | +| Operator registration | Show available operators and capacity choices. | +| Service requests and approvals | Show provisioning progress. | +| Service instances | Link the hosted app to the selected instance. | +| Source acknowledgement | Show which runnable artifact an operator accepted. | +| Jobs | Show lifecycle and workflow commands. | +| Heartbeats | Separate "not ready yet" from "operator stopped reporting." | + +The indexer should preserve enough history to distinguish pending provisioning from operator failure. The hosted app should not have to guess. + +## Live checks + +Indexed state is not enough to open a terminal or inject a secret. Before showing a sandbox as usable, the app should check: + +1. operator API reachability +2. session auth challenge/session flow +3. `/readyz` or `/health` +4. `/api/capabilities` +5. one product operation when the page needs it, such as listing sandboxes or reading instance state + +For TEE mode, the app should also expose attestation status and avoid presenting confidential execution as verified when attestation is missing. -The metadata defines three modes: cloud, dedicated instance, and TEE instance. The dapp can use those mode records to keep the app surface stable while routing service creation to the right blueprint ID. +## Iframe policy -## Iframe Policy +The sandbox app is iframe-first. The parent dapp should: -The sandbox app requests read account access, chain switching, and message/contract permissions for local and Base Sepolia deployments. Popups are disabled. The dapp should still enforce the host allowlist and iframe app policy before rendering. +| Rule | Reason | +| --------------------------------------------------------------- | --------------------------------------------------------------------------- | +| Restrict iframe hosts to trusted suffixes and manifest entries. | Prevent arbitrary operator metadata from embedding a hostile app. | +| Pass parent origin and chain context explicitly. | Lets the child app request wallet operations through the parent. | +| Keep wallet approval in the parent. | Users should see the same wallet confirmation model across Tangle Cloud. | +| Keep a link to raw protocol state. | Operators and support need chain/indexer state when the hosted app is down. | -## Indexed State +## Bad copy to avoid -The dapp needs indexed state for: +Do not name the product after one harness. The sandbox may run opencode, Codex, Claude Code, Kimi, Gemini, or another advertised runtime, but the product is the sandbox service instance and operator API. -| State | Why it matters | -| ------------------------------ | -------------------------------------------------------- | -| Blueprint creation and updates | Finds the sandbox blueprint and reads current metadata. | -| Operator registration | Shows available operators and capacity choices. | -| Service creation and approval | Identifies active sandbox fleets or dedicated instances. | -| Source acknowledgement | Confirms the operator accepted the runnable artifact. | -| Job events | Shows sandbox create/delete and workflow activity. | -| Quality-of-service heartbeats | Shows liveness and operator reliability. | +Use capability language instead: -The indexer should preserve enough service-instance and operator history for the app to distinguish "not provisioned yet" from "operator failed to report readiness." Live sandbox health still comes from the operator API and runtime checks. +- "This operator advertises `all_harness` support." +- "This sidecar currently lists Claude Code, Codex, opencode, Kimi Code, and Gemini CLI." +- "The exact harness list comes from `/api/capabilities`." diff --git a/pages/blueprints/ai-agent-sandbox/index.mdx b/pages/blueprints/ai-agent-sandbox/index.mdx index 43a0a98..581bfae 100644 --- a/pages/blueprints/ai-agent-sandbox/index.mdx +++ b/pages/blueprints/ai-agent-sandbox/index.mdx @@ -1,44 +1,71 @@ --- title: AI Agent Sandbox Blueprint -description: First-party Tangle blueprint for managed AI agent sandboxes. +description: First-party Tangle blueprint for isolated AI agent sandboxes. --- # AI Agent Sandbox Blueprint -The AI Agent Sandbox blueprint defines the template for isolated agent sandbox service instances on Tangle. Operators run the sandbox runtime and sidecar containers. Users create sandboxes, trigger workflows, attach terminals, inject secrets, and inspect execution through the hosted app. +AI Agent Sandbox lets a user create an isolated agent workspace through Tangle. + +The blueprint defines the jobs, metadata, contracts, and runtime rules. Operators run the actual sandboxes: Docker containers, Firecracker microVMs, or TEE-backed instances. The hosted app gives users terminals, workflows, files, port proxies, secrets, snapshots, and prompt/task execution. Source repo: https://github.com/tangle-network/ai-agent-sandbox-blueprint -## Product Shape +## What happens when a user creates a sandbox + +1. The user chooses a sandbox mode and requests a service instance. +2. The selected operator approves the request. +3. The operator starts the runtime and reports provisioning state. +4. The app authenticates to the operator API with EIP-191 challenge signing and a PASETO session token. +5. The user works through the hosted app: terminal, files, workflows, prompts, tasks, ports, SSH, secrets, and snapshots. + +The on-chain path records lifecycle and workflow commands. The operator API handles live I/O. That split is intentional: terminal output and file lists should not be blockchain jobs. + +## Modes + +| Mode | Blueprint ID in current metadata | Service shape | +| ------------------ | -------------------------------- | ----------------------------------------------------------------------------- | +| Cloud | `10` | A fleet-style sandbox service. Users create and delete sandboxes on demand. | +| Dedicated instance | `11` | One sandbox per service instance. The operator auto-provisions it on startup. | +| TEE instance | `12` | Dedicated instance with TEE attestation and sealed-secret support. | + +Mode IDs come from the repo metadata. Treat them as network-specific config, not hard-coded truth for every chain. + +## Jobs + +| Job | Mode | Purpose | +| ------------------ | ------------------ | ---------------------------------------------------- | +| `SANDBOX_CREATE` | Cloud | Create a sandbox container or runtime instance. | +| `SANDBOX_DELETE` | Cloud | Delete the sandbox and clean up runtime attachments. | +| `WORKFLOW_CREATE` | Cloud and instance | Register a workflow template. | +| `WORKFLOW_TRIGGER` | Cloud and instance | Trigger a workflow against the service instance. | +| `WORKFLOW_CANCEL` | Cloud and instance | Cancel an active workflow. | + +The internal workflow tick is scheduler-driven and should not be treated as a public on-chain job. -| Area | Source-backed behavior | -| ----------------- | --------------------------------------------------------------------------------------------------------- | -| Cloud mode | Multi-tenant fleet; callers create and delete sandboxes on demand through on-chain jobs. | -| Instance mode | One sandbox per service instance; the operator auto-provisions on startup and reports lifecycle directly. | -| TEE instance mode | Dedicated instance with TEE attestation and sealed secrets. | -| Hosted app | `https://agent-sandbox.blueprint.tangle.tools/` | -| Metadata identity | `publisher.namespace = "tangle"`, `requestedSlug = "ai-agent-sandbox"` | +## Read and control surface -## On-Chain Jobs +The operator API owns the live product state: -| ID | Job | Mode | What it does | -| --- | ------------------ | ------------------ | ------------------------------------------------------------ | -| `0` | `SANDBOX_CREATE` | Cloud | Creates a sandbox container, microVM, or TEE-backed sandbox. | -| `1` | `SANDBOX_DELETE` | Cloud | Deletes the sandbox and releases runtime resources. | -| `2` | `WORKFLOW_CREATE` | Cloud and instance | Registers a workflow template. | -| `3` | `WORKFLOW_TRIGGER` | Cloud and instance | Starts a registered workflow. | -| `4` | `WORKFLOW_CANCEL` | Cloud and instance | Cancels active workflow execution. | +| API area | Examples | +| ------------------ | --------------------------------------------------- | +| Auth | challenge, session, revoke | +| Sandbox operations | list, exec, prompt, task, stop, resume, snapshot | +| Access | SSH key provision/revoke, port proxy | +| Secrets | inject and wipe sandbox-scoped secrets | +| Health | `/health`, `/readyz`, `/metrics` | +| Capabilities | `/api/capabilities` for runtime and harness support | -`JOB_WORKFLOW_TICK` is internal cron-driven workflow progress. It is not a public on-chain job. +Every data endpoint requires a signed wallet session. Production operators must set `SESSION_AUTH_SECRET`; otherwise sessions and encrypted secrets re-key on restart. -## Read Next +## What to read next -| Page | Use it for | -| --------------------------------------------------------------------------- | ----------------------------------------------------------------------- | -| [Operator Requirements](/blueprints/ai-agent-sandbox/operator-requirements) | Host sizing, env vars, Docker, Firecracker, TEE, ports. | -| [Runtime and Harnesses](/blueprints/ai-agent-sandbox/runtime-and-harnesses) | Sidecar capabilities, harness discovery, secrets, auth, runtime safety. | -| [Dapp and Indexer](/blueprints/ai-agent-sandbox/dapp-and-indexer) | Metadata, iframe policy, indexed events, service state. | +| Page | Use it for | +| --------------------------------------------------------------------------- | ------------------------------------------------------------------- | +| [Operator Requirements](/blueprints/ai-agent-sandbox/operator-requirements) | Host setup, ports, Docker, Firecracker, TEE, state, and secrets. | +| [Runtime and Harnesses](/blueprints/ai-agent-sandbox/runtime-and-harnesses) | Runtime backends, capability discovery, harnesses, and AI keys. | +| [Dapp and Indexer](/blueprints/ai-agent-sandbox/dapp-and-indexer) | Metadata, iframe policy, indexed state, and live health boundaries. | -## Source Material +## Sources used -This page is based on the blueprint repo's `README.md`, `docs/runbook.md`, `metadata/blueprint-metadata.json`, `ai-agent-sandbox-blueprint-lib/src/lib.rs`, `sandbox-runtime/src/operator_api.rs`, and `TEE-GUIDE.md`. +This page is grounded in the repo `README.md`, `docs/runbook.md`, `TEE-GUIDE.md`, `metadata/blueprint-metadata.json`, `sandbox-runtime/src/operator_api.rs`, and the sidecar image docs. diff --git a/pages/blueprints/ai-agent-sandbox/operator-requirements.mdx b/pages/blueprints/ai-agent-sandbox/operator-requirements.mdx index ab69dc4..6595e17 100644 --- a/pages/blueprints/ai-agent-sandbox/operator-requirements.mdx +++ b/pages/blueprints/ai-agent-sandbox/operator-requirements.mdx @@ -1,50 +1,93 @@ --- title: AI Agent Sandbox Operator Requirements -description: Host, runtime, and environment requirements for AI Agent Sandbox operators. +description: Host, runtime, state, and secret requirements for AI Agent Sandbox operators. --- -# Operator Requirements +# AI Agent Sandbox Operator Requirements -Operators run one of three binaries: sandbox cloud, dedicated instance, or TEE instance. All variants need a keystore, chain RPC, persistent state, and an authenticated operator API. +An AI Agent Sandbox operator is running untrusted compute for other people. Start from that fact. -## Common Environment +The operator needs a chain identity, persistent state, a supervised runtime, and an authenticated API. If the operator exposes TEE mode or Firecracker mode, it also needs the host-level pieces those runtimes require. -| Variable | Purpose | -| ------------------------------------------------- | ------------------------------------------------------------------ | -| `KEYSTORE_URI` | Operator keystore path or URI. | -| `HTTP_RPC_ENDPOINT` or `RPC_URL` | Tangle EVM HTTP RPC endpoint. | -| `TANGLE_WS_URL` | WebSocket endpoint for event subscriptions. | -| `BLUEPRINT_STATE_DIR` | Persistent state for sandbox records, sessions, and metadata. | -| `SESSION_AUTH_SECRET` | 32+ byte secret for PASETO sessions and at-rest secret encryption. | -| `SANDBOX_UI_AUTH_MODE`, `SANDBOX_UI_BEARER_TOKEN` | Browser-facing UI ingress auth. | +## Common requirements -## Sandbox Mode +| Requirement | Why | +| ---------------------- | ---------------------------------------------------------------------------------- | +| Operator keystore | Signs protocol actions and identifies the operator. | +| HTTP and WebSocket RPC | Reads chain state and subscribes to events. | +| `BLUEPRINT_STATE_DIR` | Stores sandbox records, sessions, workflow state, and local runtime state. | +| `SESSION_AUTH_SECRET` | Derives PASETO session tokens and at-rest encryption keys. Required in production. | +| UI/API ingress auth | Prevents the public internet from directly controlling sandboxes. | +| Supervised process | The operator must restart cleanly after crashes. | -| Requirement | Notes | -| ------------------- | ------------------------------------------------------------------------------ | -| Docker | Required for standard sidecar containers. | -| `SIDECAR_IMAGE` | Defaults to a sidecar-compatible all-harness image. | -| `OPERATOR_API_PORT` | Default `9100`. | -| `PUBLIC_HOST` | Set explicitly behind NAT or VPN; auto-detect is available for Tailscale IPv4. | +## Binary variants -## Firecracker Mode +| Variant | Binary | Shape | +| ------------------ | ------------------------------------- | ------------------------------------------------------- | +| Cloud sandbox | `ai-agent-sandbox-blueprint-bin` | Fleet mode. Users create/delete sandboxes. | +| Dedicated instance | `ai-agent-instance-blueprint-bin` | One sandbox per service instance. | +| TEE instance | `ai-agent-tee-instance-blueprint-bin` | Dedicated instance plus attestation and sealed secrets. | -Firecracker runs through the in-process `microvm-runtime` driver. The operator binary is the Firecracker host; there is no separate host-agent service. +## Docker mode -| Variable | Purpose | -| -------------------------------- | -------------------------- | -| `MICROVM_FIRECRACKER_BIN` | Firecracker binary path. | -| `MICROVM_FIRECRACKER_KERNEL` | Linux kernel image. | -| `MICROVM_FIRECRACKER_ROOTFS` | Rootfs ext4 image. | -| `MICROVM_FIRECRACKER_SOCKET_DIR` | Per-VM API socket parent. | -| `MICROVM_FIRECRACKER_STATE_DIR` | Per-VM state directory. | -| `MICROVM_FIRECRACKER_VCPU` | Default vCPU count per VM. | -| `MICROVM_FIRECRACKER_MEM_MIB` | Default memory per VM. | +Docker is the simplest path. -The Firecracker path allocates TAP, vsock, per-VM rootfs clones, and host port forwarding. Operators must bake the guest metadata daemon into the rootfs so environment and sidecar auth tokens can be injected over vsock. +| Variable | Purpose | +| -------------------------------------- | ------------------------------------------------------------------------------ | +| `SIDECAR_IMAGE` | Sidecar image, usually `ghcr.io/tangle-network/blueprint-sidecar:all-harness`. | +| `SIDECAR_PUBLIC_HOST` or `PUBLIC_HOST` | Public hostname used when returning sidecar or proxy URLs. | +| `SIDECAR_PULL_IMAGE` | Whether to pull the image on first create. | +| `OPERATOR_API_PORT` | Operator API port. Sandbox mode defaults around `9100`. | -## TEE Mode +Keep raw sidecar ports private unless the operator intentionally proxies them. -TEE instance mode supports provider-backed confidential runtimes such as Phala, AWS Nitro, GCP Confidential Space, Azure SKR, or direct operator-managed hardware. Configure the provider-specific credentials and set `TEE_BACKEND`. +## Firecracker mode -Current TEE verification should be treated as structural unless the deployment also pins quote-signature verification, expected sidecar measurements, and fresh client nonces. +Firecracker mode runs through the operator process and `microvm-runtime`. + +| Variable | Purpose | +| -------------------------------- | --------------------------------------------------- | +| `MICROVM_FIRECRACKER_BIN` | Firecracker binary path. | +| `MICROVM_FIRECRACKER_KERNEL` | Linux kernel image used for guests. | +| `MICROVM_FIRECRACKER_ROOTFS` | Default ext4 rootfs. | +| `MICROVM_FIRECRACKER_SOCKET_DIR` | Per-VM API socket parent directory. | +| `MICROVM_FIRECRACKER_STATE_DIR` | Per-VM state directory. | +| `MICROVM_FIRECRACKER_VCPU` | Default vCPU count. | +| `MICROVM_FIRECRACKER_MEM_MIB` | Default memory in MiB. | +| `MICROVM_GUEST_METADATA_PORT` | vsock port for per-VM env and auth token injection. | + +The rootfs must include the guest metadata daemon. Without it, the operator cannot inject per-VM env vars and sidecar auth tokens over vsock. + +## TEE mode + +Set `TEE_BACKEND` to one of: + +| Backend | Required setup | +| ---------------- | ------------------------------------------------------------------------------------------------------------------------------- | +| `phala` | `PHALA_API_KEY`; optional endpoint override. | +| `nitro` or `aws` | AWS region, AMI, subnet, security group, instance type, and optional KMS/profile config. | +| `gcp` | GCP project, zone, image, machine type, and optional service account/KMS config. | +| `azure` | Subscription, resource group, location, VM image/size, subnet, tenant/client secret, and optional Key Vault/attestation config. | +| `direct` | TDX, SEV-SNP, or Nitro-capable hardware and the matching device node. | + +TEE instance contracts enforce non-empty attestation when `teeRequired=true`. The operator API also exposes attestation and sealed-secret endpoints. + +## Local proof + +The repo's local runbook uses: + +```bash +SKIP_BUILD=1 ./scripts/deploy-local.sh +./scripts/test-e2e.sh +``` + +The smoke should prove: + +1. local Anvil and contracts are up +2. blueprints are registered +3. operator APIs start +4. auth works +5. lifecycle reporting reaches the chain +6. runtime/operator API actions hit a real sidecar path where enabled + +Do not replace this with mocked API tests when deploy scripts, service registration, or auth changed. diff --git a/pages/blueprints/ai-agent-sandbox/runtime-and-harnesses.mdx b/pages/blueprints/ai-agent-sandbox/runtime-and-harnesses.mdx index 12f7d51..edd947c 100644 --- a/pages/blueprints/ai-agent-sandbox/runtime-and-harnesses.mdx +++ b/pages/blueprints/ai-agent-sandbox/runtime-and-harnesses.mdx @@ -1,54 +1,94 @@ --- title: AI Agent Sandbox Runtime and Harnesses -description: Sidecar capability and harness model for the AI Agent Sandbox blueprint. +description: Runtime backends, capability discovery, harnesses, and AI credentials for the AI Agent Sandbox blueprint. --- -# Runtime and Harnesses +# AI Agent Sandbox Runtime and Harnesses -The sandbox blueprint is not one agent integration. The product contract is a sidecar-compatible sandbox plus runtime capabilities advertised by the operator. +The sandbox is the product. Harnesses are tools inside the sandbox. -## Runtime Backends +Do not describe this blueprint as an OpenCode integration, a Codex integration, or a Claude integration. A service instance asks the operator for runtime capabilities. The operator answers through `GET /api/capabilities`. -Sandbox creation selects a backend through `metadata_json.runtime_backend`. +## Runtime backends -| Backend | Behavior | -| ------------- | --------------------------------------------------------------------------------------------- | -| `docker` | Default managed sidecar container path. | -| `firecracker` | MicroVM path; installs per-VM networking, rootfs, env injection, and sidecar token injection. | -| `tee` | Forces TEE provisioning and `tee_required=true`. | +Sandbox creation accepts `metadata_json.runtime_backend`: -Firecracker and TEE are separate choices in the current release. Selecting `firecracker` forces `tee_required=false`. +| Value | Meaning | +| ------------- | -------------------------------------------------------------------------------------------- | +| `docker` | Default path. The operator starts a sidecar container. | +| `firecracker` | MicroVM path through the in-process `microvm-runtime` driver. | +| `tee` | Confidential runtime path. TEE instance mode requires attestation before service activation. | -## Sidecar Capabilities +Firecracker is driven by the operator binary. There is no separate host-agent service. Operators must provide the Firecracker binary, kernel, rootfs, socket/state paths, TAP/vsock support, and a guest metadata daemon inside the rootfs. -Provisioning accepts `capabilities_json`, a JSON-encoded string array. Accepted values are injected into the sandbox as `SIDECAR_CAPABILITIES`. +TEE mode needs a provider backend such as Phala, AWS Nitro, GCP Confidential Space, Azure SKR, or direct operator-managed hardware. Direct TDX currently does not give nonce-bound remote DCAP quotes in this runtime; use SEV-SNP, Nitro, Phala, GCP, or Azure when clients need nonce-bound verification. -| Capability | Behavior | -| -------------- | -------------------------------------------------------------------------------------------------------- | -| `computer_use` | Starts browser/computer-use sidecar services for mouse, keyboard, screenshots, and related MCP surfaces. | -| `all_harness` | Requests the multi-harness sidecar image path. | +## Capability discovery -The exact harness matrix comes from `GET /api/capabilities`. The current default all-harness image advertises multiple CLI agent harnesses. Operators should rely on capability discovery instead of treating any one harness as the integration. +The current operator API returns two categories: -The current all-harness path is source-backed for Claude Code, Codex, OpenCode, Kimi, and Gemini. That is a sidecar runtime capability, not the blueprint's product identity. The blueprint identity is the sandbox service instance plus its operator API, lifecycle jobs, workflow state, and runtime isolation. +| Capability | Meaning | +| -------------- | ---------------------------------------------- | +| `computer_use` | Enables browser/computer-use sidecar services. | +| `all_harness` | Requests the all-harness sidecar runtime. | -## Operator API +The current all-harness sidecar in this repo installs: -All data endpoints use EIP-191 challenge-response auth that issues PASETO v4.local session tokens. +| Harness | ID | +| ----------- | ------------- | +| Claude Code | `claude-code` | +| Codex | `codex` | +| opencode | `opencode` | +| Kimi Code | `kimi-code` | +| Gemini CLI | `gemini` | -| Endpoint group | Examples | -| -------------------- | -------------------------------------------------------------------------------------------- | -| Auth | `POST /api/auth/challenge`, `POST /api/auth/session`, `DELETE /api/auth/session` | -| Sandbox operations | `exec`, `prompt`, `task`, `stop`, `resume`, `snapshot`, `ssh`, `secrets`, port proxy | -| Instance operations | Same control plane under `/api/sandbox/...` for singleton service instances | -| Health and discovery | `GET /health`, `GET /readyz`, `GET /metrics`, `GET /api/provisions`, `GET /api/capabilities` | +This list is not the blueprint ABI. It is the operator's advertised capability set. A new sidecar image can add or remove harnesses while the blueprint jobs stay the same. -## Secrets and Model Credentials +## Sidecar image -Sandbox creation can succeed without model credentials. Agent prompts, tasks, and workflow steps fail only when the selected harness or model provider lacks its required secret. +The public all-harness image is built from the blueprint repo: -Operators should inject provider credentials as sandbox secrets or environment variables scoped to the service instance. The blueprint ABI stays stable as new sidecar images and sandbox SDK harnesses add support for more providers. +```bash +docker build -f sidecar/Dockerfile.all-harness \ + -t ghcr.io/tangle-network/blueprint-sidecar:all-harness . +``` -## Runtime Safety +Operators can verify the installed harness binaries: -The runtime enforces challenge-response auth, encrypted stored secrets, container hardening, rate limits, circuit breakers, session caps, and snapshot destination validation. Container hardening includes dropped capabilities, `no-new-privileges`, PID limits, localhost-bound ports, and restricted writable state. +```bash +docker run --rm --entrypoint blueprint-verify-harnesses \ + ghcr.io/tangle-network/blueprint-sidecar:all-harness +``` + +For smaller images, build with `BLUEPRINT_HARNESSES=codex,gemini` or another subset. The app should still read `/api/capabilities`; it should not infer support from the image tag alone. + +## AI credentials + +Sandbox lifecycle can work without model keys. Agent prompts, tasks, and workflow steps need whatever secret the selected harness or provider expects. + +Operators should scope provider keys to the service instance. The blueprint ABI should not change when a new provider or harness is added. + +Common credential locations remain harness-specific: + +| Harness family | Typical config | +| -------------- | ---------------------------------------------------------------------- | +| Claude Code | `/root/.claude` or `ANTHROPIC_API_KEY` style provider config. | +| Codex | `/root/.codex` or OpenAI provider config. | +| opencode | `/root/.config/opencode`, `/root/.opencode`, or opencode provider env. | +| Kimi | `/root/.kimi` or `/root/.config/kimi`. | +| Gemini | `/root/.gemini` or Google provider config. | + +The operator protects the session token, sidecar auth token, provider keys, and sandbox secrets. Losing one of those is a product incident, not a docs footnote. + +## Runtime health + +Use these probes before routing users into a sandbox: + +| Endpoint | What it proves | +| ----------------------- | ------------------------------------------------------------------------------- | +| `/health` | Runtime and state-store health. Returns degraded when a subsystem fails. | +| `/readyz` | Strict readiness. Returns `503` unless all required subsystems are healthy. | +| `/api/capabilities` | The runtime and harness features the operator says are available. | +| Product operation probe | A real exec, prompt, terminal, port, or workflow call through the operator API. | + +The indexer can tell the app that a service exists. It cannot tell the app that a sidecar is usable right now. diff --git a/pages/blueprints/ai-trading/dapp-and-indexer.mdx b/pages/blueprints/ai-trading/dapp-and-indexer.mdx index c2ef547..d285de0 100644 --- a/pages/blueprints/ai-trading/dapp-and-indexer.mdx +++ b/pages/blueprints/ai-trading/dapp-and-indexer.mdx @@ -1,46 +1,76 @@ --- title: AI Trading Dapp and Indexer -description: Arena metadata, iframe policy, and indexed state for the AI Trading blueprint. +description: Arena routing, operator discovery, and indexed state for AI Trading. --- -# Dapp and Indexer +# AI Trading Dapp and Indexer -The dapp should resolve the AI Trading blueprint from first-party metadata and render the Arena app through the trusted iframe path. +The Arena is the product app for AI Trading. Tangle Cloud should launch it from trusted metadata and preserve the protocol fallback route for raw service state. -## Metadata Contract +## Metadata the dapp should use -| Field | Value | +| Field | Current value in repo metadata | | --------------------------------- | ----------------------------------------------- | | `blueprintUi.displayName` | `AI Trading Desk` | | `blueprintUi.requestedSlug` | `ai-trading` | | `blueprintUi.publisher.namespace` | `tangle` | -| `resources.serviceNoun` | `trading instance` | -| `resources.resourceNoun` | `bot` | -| `externalApp.url` | `https://trading-arena.blueprint.tangle.tools/` | | `externalApp.mode` | `iframe` | +| `externalApp.url` | `https://trading-arena.blueprint.tangle.tools/` | + +The metadata also declares cloud, instance, and TEE modes. The Arena should use those mode records instead of hard-coding a single blueprint ID. + +## Indexed state + +| State | Why the dapp needs it | +| ----------------------------------- | ----------------------------------------------------------------- | +| Blueprint registration and metadata | Find the current trading blueprint and app policy. | +| Operator registration | Discover operator endpoints and capacity. | +| Service requests and instances | Link a user request to the running bot service. | +| Job events | Show provision/config/start/stop style commands where applicable. | +| Pricing pointers | Show quote or subscription information when available. | +| Heartbeats | Distinguish dead operators from missing data. | + +The indexer should make operator discovery reliable. It should not be treated as proof that a bot is healthy or that a trade was safe. + +## Live operator reads + +The Arena still needs operator APIs for: + +- bot roster +- bot detail +- provisions +- vault state +- paper/live state +- strategy config +- trade history +- terminal or sidecar logs +- health + +If an operator endpoint is unreachable, say that. Do not replace it with stale indexed state unless the UI labels it as stale. + +## User-facing states -The metadata includes overview cards for the risk gate, venue capabilities, and protocol adapters. It also declares actions for bot activation and pausing. +| State | Meaning | +| -------------------- | --------------------------------------------------------------------------------- | +| No operator | The blueprint exists, but nobody is serving it on the selected network. | +| Operator unreachable | The registration exists, but the public endpoint is failing. | +| Provision pending | The service exists, but no bot is ready yet. | +| Paper | The bot is using live data and simulated fills. | +| Live | The bot can submit real execution through its configured venues and vault policy. | +| Policy blocked | The bot generated an intent that the policy or validator path rejected. | -## Dapp Behavior +These states should be visible in the app. "Loading" is not enough. -| Surface | Behavior | -| ----------------- | ----------------------------------------------------------------------------------------- | -| Blueprint route | Claim metadata with `requestedSlug = "ai-trading"` under the `tangle` namespace. | -| External app | Render the Arena iframe only after host and iframe policy checks pass. | -| Chain switching | Allow only the chain IDs declared in iframe policy. | -| Protocol fallback | Keep the generic blueprint detail route available for raw on-chain service-instance data. | +## Iframe policy -## Indexed State +Trading is iframe-first under `trading-arena.blueprint.tangle.tools`. -The Arena and Tangle Cloud need: +The parent dapp should: -| State | Why it matters | -| -------------------------------------- | ------------------------------------------------------------------------ | -| Blueprint and source updates | Finds current binaries and metadata. | -| Operator registration and endpoint URL | Discovers live operators and their APIs. | -| Service instances | Shows bot fleets and dedicated trading instances. | -| Job events | Tracks provision, configure, start, stop, status, and workflow activity. | -| Pricing state | Shows operator quote surfaces and service-instance cost. | -| QoS heartbeats | Ranks and filters operators by liveness. | +1. restrict the iframe to the trusted host +2. pass parent origin and chain context +3. keep wallet approvals in the parent +4. expose the service instance link +5. keep the raw protocol fallback route available -Because operator endpoint URLs are self-reported at registration time, the dapp should treat the indexer as discovery, not proof that an endpoint is honest or healthy. +The Arena owns product workflow. Tangle Cloud owns the shell, wallet safety, and route policy. diff --git a/pages/blueprints/ai-trading/index.mdx b/pages/blueprints/ai-trading/index.mdx index 78ffd6f..97deaee 100644 --- a/pages/blueprints/ai-trading/index.mdx +++ b/pages/blueprints/ai-trading/index.mdx @@ -1,54 +1,67 @@ --- title: AI Trading Blueprint -description: First-party Tangle blueprint for autonomous trading agents. +description: First-party Tangle blueprint for operator-run trading bots. --- # AI Trading Blueprint -The AI Trading blueprint defines the template for autonomous trading service instances with strategy workers, vault policy, and decentralized risk validation. Operators host bot sandboxes and trading APIs. Users create and monitor trading service instances through the Arena app. +AI Trading lets a user create a trading bot as a Tangle service instance. + +The blueprint defines the bot lifecycle, vault contracts, risk policy, metadata, and operator runtime. Operators run the bot sandboxes and APIs. The Arena app is the user surface for creating bots, watching paper/live execution, managing vaults, and inspecting risk state. Source repo: https://github.com/tangle-network/ai-trading-blueprint -## Product Shape - -| Area | Source-backed behavior | -| ----------------- | ---------------------------------------------------------------- | -| Cloud fleet | Multi-bot operator process for shared capacity. | -| Instance | One dedicated bot per service instance. | -| TEE instance | Single bot with confidential runtime selection. | -| Hosted app | `https://trading-arena.blueprint.tangle.tools/` | -| Metadata identity | `publisher.namespace = "tangle"`, `requestedSlug = "ai-trading"` | - -## Protocol Coverage - -| Category | Supported adapters | -| ---------- | ------------------------------ | -| Perpetuals | Hyperliquid, GMX v2, Vertex | -| DEX | Uniswap V3, Aerodrome | -| Lending | Aave V3, Morpho | -| Prediction | Polymarket | -| Execution | TWAP and statistical arbitrage | - -## Strategy Packs - -| Pack | Default cadence | Max turns | -| ------------ | --------------- | --------- | -| `prediction` | 15 minutes | 20 | -| `dex` | 5 minutes | 12 | -| `yield` | 15 minutes | 10 | -| `perp` | 2 minutes | 15 | -| `volatility` | 10 minutes | 12 | -| `mm` | 1 minute | 15 | -| `multi` | 5 minutes | 20 | - -## Read Next - -| Page | Use it for | -| --------------------------------------------------------------------- | -------------------------------------------------------------- | -| [Operator Requirements](/blueprints/ai-trading/operator-requirements) | VPS sizing, ports, install flow, service IDs, env vars. | -| [Runtime and Risk](/blueprints/ai-trading/runtime-and-risk) | Runtime backends, paper mode, AI cost, validation trust modes. | -| [Dapp and Indexer](/blueprints/ai-trading/dapp-and-indexer) | Arena metadata, iframe policy, indexed service state. | - -## Source Material - -This page is based on the blueprint repo's `README.md`, `OPERATORS.md`, `docs/runbook.md`, `metadata/blueprint-metadata.json`, `settings.env.example`, and trading runtime contract/risk code. +## What happens when a user activates a bot + +1. The user chooses a blueprint mode and creates a service request. +2. The selected operator approves the request. +3. The operator provisions a bot sandbox and records bot state. +4. The bot starts in paper mode by default in the operator install path. +5. The Arena reads operator APIs for bot roster, provisions, vault state, logs, and execution history. +6. Risk policy decides whether a trade can move from signal to execution. + +The chain is the service and settlement spine. The operator API is the live product API. + +## Modes + +| Mode | Blueprint ID in current Base Sepolia notes | Service shape | +| ------------------ | ------------------------------------------ | -------------------------------------------------- | +| Cloud fleet | `13` | One operator process can host many bots. | +| Dedicated instance | `14` | One bot per service instance. | +| TEE instance | `15` | Dedicated bot with confidential runtime selection. | + +Do not copy these IDs blindly to another network. Read the deployed manifest or metadata for the target chain. + +## What the bot controls + +| Area | Examples | +| --------------- | ------------------------------------------------------------------------------------------------------- | +| Strategy | Prompt, strategy pack, runtime config, tick cadence, learning state. | +| Venues | Hyperliquid, Uniswap, Aave, GMX, Morpho, Vertex, Polymarket, Aerodrome, and execution helpers. | +| Vault policy | Allowed assets, position size, borrowed-exposure cap, total exposure, drawdown, and stop-loss distance. | +| Trust mode | Per-trade validation, envelope validation, or self-operated mode. | +| Execution state | Paper fills, live fills, open positions, fees, impact, gas, and PnL. | + +The same strategy config is meant to drive backtesting, paper trading, and live execution. Treat that as a safety requirement, not a marketing line. + +## Validation trust + +| Trust level | What happens | +| -------------- | -------------------------------------------------------------------------------------------------------- | +| `PerTrade` | Each trade needs validator EIP-712 signatures before execution. Higher latency, stronger external check. | +| `Envelope` | A depositor pre-approves a policy envelope. Trades inside that envelope execute immediately. | +| `SelfOperated` | A trusted/self-hosted operator uses local policy. The envelope still bounds execution. | + +On-chain guards live in contracts such as `PolicyEngine`, `TradeValidator`, vault contracts, and fee distribution. Operator-side checks are not a substitute for the vault policy. + +## What to read next + +| Page | Use it for | +| --------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| [Operator Requirements](/blueprints/ai-trading/operator-requirements) | VPS sizing, install flow, service IDs, ports, env, admission, and upgrade rules. | +| [Runtime and Risk](/blueprints/ai-trading/runtime-and-risk) | Paper mode, agent keys, runtime backend, risk gates, and validation trust. | +| [Dapp and Indexer](/blueprints/ai-trading/dapp-and-indexer) | Arena iframe metadata, operator discovery, and indexed service state. | + +## Sources used + +This page is grounded in the repo `README.md`, `OPERATORS.md`, `docs/runbook.md`, `metadata/blueprint-metadata.json`, `settings.env.example`, Arena operator discovery code, and the trading runtime/risk contract docs. diff --git a/pages/blueprints/ai-trading/operator-requirements.mdx b/pages/blueprints/ai-trading/operator-requirements.mdx index b80547b..7f2a7c0 100644 --- a/pages/blueprints/ai-trading/operator-requirements.mdx +++ b/pages/blueprints/ai-trading/operator-requirements.mdx @@ -1,52 +1,88 @@ --- title: AI Trading Operator Requirements -description: Host and configuration requirements for AI Trading blueprint operators. +description: Host, install, state, admission, and provider requirements for AI Trading operators. --- -# Operator Requirements +# AI Trading Operator Requirements -Trading operators run one of three binaries and expose an operator API that the Arena discovers from on-chain registration. +A trading operator is accepting bots that can spend compute, disk, model credits, and possibly capital. -## Operator Shapes +Run allowlist admission and paper mode first. Move to public admission or live trading only after you have watched the operator run and fail safely. -| Blueprint ID | Binary | Shape | -| ------------ | -------------------------------- | --------------------------------------------- | -| `13` | `trading-blueprint` | Cloud fleet; many bots per operator instance. | -| `14` | `trading-instance-blueprint` | One bot per service instance. | -| `15` | `trading-tee-instance-blueprint` | TEE instance; requires TEE hardware. | +## Host requirements -## Host Requirements +| Requirement | Minimum | Recommended | +| ----------- | -------------------------------------------- | ------------------------------- | +| CPU | 2 vCPU | 4 vCPU | +| RAM | 4 GB | 8 GB | +| Disk | 40 GB SSD | 80 GB SSD | +| OS | Ubuntu 22.04/24.04 or another systemd distro | Ubuntu 24.04 | +| Arch | x86_64 | x86_64 | +| Docker | Engine 24+ | Engine 24+, daemon supervised | +| Network | Public IPv4, inbound 22 and 443 | TLS through Caddy or equivalent | -| Resource | Minimum | Recommended | -| -------- | ------------------------------- | ---------------------------------------- | -| CPU | 2 vCPU | 4 vCPU | -| RAM | 4 GB | 8 GB | -| Disk | 40 GB SSD | 80 GB SSD | -| OS | Ubuntu 22.04 or 24.04 | Ubuntu 24.04 | -| Arch | x86_64 | x86_64 | -| Runtime | Docker 24+ | Docker 24+ with sidecar image pre-pulled | -| Network | Public IPv4, inbound 22 and 443 | Public IPv4, TLS, low-latency RPC | +The sidecar image is large and bot state grows. Do not run this on a tiny box and expect useful results. -The public sidecar image is multi-GB and bots accumulate state, so disk sizing should include image cache, bot workspaces, logs, and chain metadata. +## Operator binaries -## Required Service Configuration +| Blueprint ID | Binary | Shape | +| ------------ | -------------------------------- | --------------------------------------------------- | +| `13` | `trading-blueprint` | Cloud fleet. Many bots per operator instance. | +| `14` | `trading-instance-blueprint` | One bot per service instance. | +| `15` | `trading-tee-instance-blueprint` | One bot per service instance with TEE requirements. | -| Variable | Purpose | -| --------------------------------------------------------------------------------------------- | ----------------------------------------------------- | -| `SERVICE_ID` | Existing service instance. The binary exits if unset. | -| `BLUEPRINT_ID` | Blueprint variant being served. | -| `CHAIN_ID` | Base Sepolia is `84532`. | -| `HTTP_RPC_URL`, `WS_RPC_URL` | Chain reads, writes, and event watching. | -| `BLUEPRINT_STATE_DIR` | Persistent operator state. | -| `OPERATOR_PRIVATE_KEY` | Operator signer. | -| `VAULT_FACTORY`, `TRADE_VALIDATOR`, `POLICY_ENGINE`, `FEE_DISTRIBUTOR`, `ASSET_TOKEN_ADDRESS` | Trading contract addresses. | +The production install script verifies release binary checksums and writes a systemd unit. Re-running the installer with a new tag upgrades the binary while leaving keystore, settings, and bot state alone. -## Ports and Discovery +## Required state -| Port | Purpose | -| ------ | -------------------------------------------- | -| `9200` | Operator API default. | -| `9100` | Trading API default. | -| `443` | TLS public endpoint used by Arena discovery. | +| Value | Why | +| ---------------------------- | ------------------------------------------------------------------------------ | +| `SERVICE_ID` | The service instance the operator serves. The binary exits if this is missing. | +| `BLUEPRINT_ID` | The blueprint ID registered on the target network. | +| `CHAIN_ID` | Drives chain-specific behavior and paper/live defaults. | +| `HTTP_RPC_URL`, `WS_RPC_URL` | Contract reads and event subscriptions. | +| `BLUEPRINT_STATE_DIR` | Bot state, learning state, envelopes, and operator records. | +| `OPERATOR_API_PORT` | Admin/control API. Current examples use `9200`. | +| `TRADING_API_PORT` | Bot-facing trading API. Current examples use `9100`. | -Operators register their public API URL on-chain. The Arena reads that registration and calls the operator API for bot state, pricing, and service-instance controls. +Keep secrets in an untracked `settings.env`. The tracked `settings.env.example` is only a template. + +## Admission and capacity + +| Setting | Default stance | +| ---------------------------------- | ------------------------------------------------------------------------------ | +| `TRADING_REQUESTER_ACCESS_MODE` | `allowlist`. Stay there until you want anyone to consume your capacity. | +| `TRADING_REQUESTER_ALLOWLIST` | Addresses allowed to request bots. The operator address is included by policy. | +| `OPERATOR_MAX_CAPACITY` | Keep a hard number. `0` or unset means unlimited. | +| `TRADING_ENABLE_DIRECT_BOT_CREATE` | Keep `false` outside local/dev harnesses. | + +Public admission means public cost exposure. Every accepted bot can use CPU, disk, and model budget. + +## Paper mode and AI keys + +The operator install path defaults new bots to paper trading. Paper mode uses live market data and simulated fills; it should not move capital. + +AI keys are optional. If you set `ZAI_API_KEY`, `ANTHROPIC_API_KEY`, `TANGLE_API_KEY`, or opencode provider env vars, agentic activation and chat can use your provider account. The operator docs are clear: there is no built-in per-bot, per-day, or total LLM spend cap today. Use provider-side billing limits. + +## Public endpoint + +The Arena discovers operators from on-chain registration and then calls the advertised operator endpoint. + +Check from outside the host: + +```bash +curl https:///health +curl https:///api/bots +``` + +Ports `9100` and `9200` should not be publicly exposed directly. Put TLS on 443 and proxy only what the product expects. + +## Registration proof + +After funding gas and TNT stake, the operator install flow can register and self-request a service instance: + +```bash +sudo ./deploy/operator-install.sh --register --request-service +``` + +Verify registration against the deployed Tangle contract, then hit the public health endpoint. Keep the service ID and operator address in your runbook. diff --git a/pages/blueprints/ai-trading/runtime-and-risk.mdx b/pages/blueprints/ai-trading/runtime-and-risk.mdx index 1eb4c51..e6db4aa 100644 --- a/pages/blueprints/ai-trading/runtime-and-risk.mdx +++ b/pages/blueprints/ai-trading/runtime-and-risk.mdx @@ -1,48 +1,96 @@ --- title: AI Trading Runtime and Risk -description: Runtime backend, safety, and AI cost model for AI Trading operators. +description: Runtime backend, paper/live mode, model keys, and risk boundaries for AI Trading. --- -# Runtime and Risk +# AI Trading Runtime and Risk -Trading service instances use sandboxed bots, explicit runtime backends, paper-first defaults, and validation modes that control when capital can move. +Trading docs should start from risk, not from agents. -## Runtime Backend Selection +The bot can reason with an AI harness, but capital moves only when the runtime, validator path, and vault policy allow it. If those boundaries are unclear, the operator should stay in paper mode. -Trading provision requests use `strategy_config_json.runtime_backend`. +## Runtime backend -| Value | Behavior | -| ------------- | ------------------------------------------------------------------------------------- | -| `docker` | Standard bot sandbox path. | -| `firecracker` | Maps to sandbox runtime metadata; current provider wiring must be enabled before use. | -| `tee` | Confidential runtime selection; TEE instance blueprints pin this by default. | +Provision requests can set: -## Safety Knobs +```json +{ + "strategy_config_json": { + "runtime_backend": "docker" + } +} +``` -| Setting | Default | Why it matters | -| ---------------------------------- | ---------------------------------- | -------------------------------------------------------------------- | -| `TRADING_REQUESTER_ACCESS_MODE` | `allowlist` | Keeps bot creation limited to allowed addresses. | -| `TRADING_REQUESTER_ALLOWLIST` | Operator plus configured addresses | Defines who can request bots in allowlist mode. | -| `OPERATOR_MAX_CAPACITY` | `10` in installer templates | Caps concurrent bots. Unset or `0` means unlimited. | -| `DEFAULT_PAPER_TRADE` | `true` in templates | New bots use live data and simulated fills, with no on-chain trades. | -| `TRADING_ENABLE_DIRECT_BOT_CREATE` | `false` | Prevents unauthenticated direct bot creation. | +Supported values: -## AI Spend +| Value | Meaning | +| ------------- | ------------------------------------------------------------------------------------------------------------------ | +| `docker` | Default sandbox sidecar path. | +| `firecracker` | Intended microVM path. Current trading docs note this returns a validation error until provider wiring is enabled. | +| `tee` | Confidential runtime selection. TEE instance blueprints pin this mode. | -Deterministic strategy ticks can run without model credentials. Agentic activation and chat require provider credentials. If an operator sets model keys, inference is billed to that operator's account. +Runtime choice is separate from trust mode. A TEE bot can still have bad policy, and a Docker bot can still be paper-only. -The repo supports credentials such as `ZAI_API_KEY`, `ANTHROPIC_API_KEY`, and `TANGLE_API_KEY`. Treat these as provider secrets for the selected bot harness, not as the product integration boundary. +## Paper mode -There is no built-in per-bot, per-day, or total LLM spend cap. Operators should enforce spend limits at the provider account, admission allowlist, and capacity levels. +Paper mode is the safe default in the operator install path. It uses live market data and simulated fills. The operator repo has done work to model fees, impact, and gas so paper PnL is less fantasy than a frictionless simulator. -The trading product boundary is a bot with strategy config, vault policy, risk limits, paper/live mode, and performance history. Agent harnesses are runtime backends for agentic work; deterministic ticks and risk checks continue without a model key. +Paper mode should still be treated as real production behavior: -## Validation Trust +1. The bot consumes CPU, disk, and model budget. +2. Strategy bugs still matter. +3. The same config may later be promoted to live execution. +4. The Arena should label paper/live state clearly. -| Mode | Behavior | Latency | -| -------------- | ---------------------------------------------------------------------- | ------------------- | -| `PerTrade` | Validator EIP-712 signatures required per trade. | About 5-30 seconds. | -| `Envelope` | Depositor-approved bounds allow instant execution inside the envelope. | Near-zero. | -| `SelfOperated` | Local policy only; envelope still enforced. | Near-zero. | +## Validation trust -On-chain guards enforce token allowlists, position caps, leverage limits, rate limits, and replay protection through the policy and validator contracts. +| Mode | Who checks trades | Latency profile | Use when | +| -------------- | ----------------------------------------------------- | ------------------------------ | ------------------------------------------------------------------------- | +| `PerTrade` | Validator committee signs each trade intent. | 5 to 30 seconds. | The operator is untrusted or the vault needs external approval per trade. | +| `Envelope` | A depositor-approved envelope bounds what can happen. | Immediate inside the envelope. | The user accepts bounded autonomy. | +| `SelfOperated` | Local operator policy, still inside envelope limits. | Immediate. | The operator and depositor are the same trust domain. | + +The envelope covers assets, position size, borrowed exposure, total exposure, drawdown, and stop-loss distance. Cancels can be instant. + +## Model keys + +Trading bots can run deterministic ticks without model provider keys. Agentic activation and chat require keys. + +Current repo examples include: + +| Key | Used for | +| ------------------- | ------------------------------------------------------------------------ | +| `ZAI_API_KEY` | Z.ai based agentic flows. | +| `ANTHROPIC_API_KEY` | Anthropic model access. | +| `TANGLE_API_KEY` | Tangle-hosted/Router-backed model or telemetry paths depending on setup. | +| `OPENCODE_MODEL_*` | opencode provider/model routing inside the sidecar. | + +If an operator sets keys, the operator pays unless another billing path is wired. There is no default per-bot LLM budget guard. Use allowlists, capacity caps, and provider billing limits. + +## What the dapp must not imply + +Do not show "AI approved" as if that is a safety property. The useful safety facts are: + +- paper or live +- trust mode +- envelope present and not expired +- validators reachable when required +- vault policy loaded +- trade blocked or signed +- operator health +- model spend source + +Those are the states a user can act on. + +## Runtime evidence + +Before calling a trading operator production-ready, capture: + +1. build and contract tests +2. operator health +3. bot roster fetch +4. one provisioned bot +5. paper tick output +6. policy or validator state +7. service ID and operator address +8. Arena route that resolves the bot from operator data diff --git a/pages/blueprints/dapp-integration.mdx b/pages/blueprints/dapp-integration.mdx index aca47c1..0a82fa7 100644 --- a/pages/blueprints/dapp-integration.mdx +++ b/pages/blueprints/dapp-integration.mdx @@ -1,66 +1,102 @@ --- -title: Blueprint Dapp Integration -description: How first-party blueprint apps, Tangle Cloud routing, indexer state, and local release gates fit together. +title: Dapp Integration +description: How Tangle Cloud should route blueprint apps, use indexed state, and prove local staking flows. --- -# Blueprint Dapp Integration +# Dapp Integration -Tangle Cloud should treat first-party blueprint apps as product surfaces backed by protocol state, not as hand-written one-off pages. +Tangle Cloud should not hand-code a separate product page every time a first-party blueprint ships. -## Routing Contract +The app already has the right inputs: blueprint metadata, operator registrations, service instances, first-party app policy, and the generic protocol fallback route. The job is to route users to the right product surface without hiding the underlying service instance. -| Field | Purpose | -| --------------------------------- | --------------------------------------------------------------------------------------------------------- | -| `blueprintUi.publisher.namespace` | Identifies the publisher namespace. First-party entries use `tangle`. | -| `blueprintUi.requestedSlug` | Stable app slug such as `ai-agent-sandbox`, `ai-trading`, or `surplus`. | -| `blueprintUi.externalApp` | Declares whether the app renders as a trusted iframe or a trusted link-out. | -| Curated registry entry | Temporary or first-party override when on-chain metadata is incomplete or needs a hardened iframe policy. | -| Protocol fallback route | Raw indexed blueprint and service-instance view for debugging, operators, and auditors. | +## Routing rule -Sandbox and Trading are iframe-first apps under `*.blueprint.tangle.tools`. Surplus is currently a trusted link-out to `surplus-market.pages.dev` until it publishes equivalent rich `blueprintUi` metadata and iframe hosting. +Use the hosted product app when the blueprint publishes trusted app metadata. Keep the generic protocol route available for debugging, operators, and auditors. -## Current First-Party App Surfaces +| Field or route | Why it matters | +| --------------------------------- | --------------------------------------------------------------------------------------------- | +| `blueprintUi.publisher.namespace` | Identifies first-party entries. Tangle-owned entries use `tangle`. | +| `blueprintUi.requestedSlug` | Gives the dapp a stable product route such as `ai-agent-sandbox`, `ai-trading`, or `surplus`. | +| `blueprintUi.externalApp` | Tells the dapp whether to iframe the app or link out. | +| Mode records | Map one product to several blueprint IDs, such as cloud, instance, and TEE modes. | +| Generic protocol route | Shows raw blueprint, operator, service, and job state when the product app cannot. | -| App | Slug | Surface mode | Why | +Sandbox and Trading are iframe-first apps under `*.blueprint.tangle.tools`. Surplus is currently a trusted link-out to `surplus-market.pages.dev`; it should move to the same rich metadata and iframe policy when that hosting path is ready. + +## Current app policy + +| Product | Slug | Mode | Why | | ---------------- | ------------------ | -------------- | ------------------------------------------------------------------------------------------------ | -| AI Agent Sandbox | `ai-agent-sandbox` | Trusted iframe | The hosted sandbox app owns workflow, terminal, file, port, and secret UX. | -| AI Trading | `ai-trading` | Trusted iframe | The Arena owns bot creation, monitoring, risk settings, and operator API controls. | -| Surplus Market | `surplus` | Trusted link | The market app is live at `surplus-market.pages.dev`; rich iframe metadata is not yet published. | +| AI Agent Sandbox | `ai-agent-sandbox` | Trusted iframe | The hosted app owns workflow, terminal, file, port, and secret UX. | +| AI Trading | `ai-trading` | Trusted iframe | The Arena owns bot creation, monitoring, vaults, risk settings, and operator controls. | +| Surplus Market | `surplus` | Trusted link | The market app is live, but rich `blueprintUi` metadata and iframe hosting are not complete yet. | + +Do not build around one agent harness, one venue, or one operator URL. Route from metadata and then verify the live endpoint. + +## State the dapp should show + +| State | Source | +| ----------------------------- | ---------------------------------------------------------------------------------------------------------- | +| Blueprint exists | Indexer over blueprint creation and metadata updates. | +| Operator can serve it | Operator registration and endpoint metadata. | +| Service instance exists | Service request, approval, and activation events. | +| Job was submitted | Indexed job events. | +| Product is healthy | Operator API, app-level probe, or blueprint-specific proof path. | +| Product result is trustworthy | Contract state, attestation, settlement receipt, SP1 proof, signed report, or product-specific validation. | + +The indexer is discovery infrastructure. It tells the dapp what the protocol saw. It does not replace runtime health checks. + +## Failure states worth showing + +Users need to know which layer failed. + +| State | Meaning | +| -------------------- | -------------------------------------------------------------------------------------- | +| No blueprint | The selected network does not have the blueprint registered. | +| No operators | The blueprint exists, but no operator registered for it. | +| Pending service | The request exists, but operators have not approved or provisioned it yet. | +| Operator unreachable | The operator registered an endpoint, but the dapp cannot reach it. | +| Runtime unhealthy | The operator API answers, but the product-specific health check fails. | +| Proof missing | The product result exists, but the expected attestation, receipt, or proof is missing. | + +Do not collapse these into "not available." That hides the next action. -## Indexer Coverage +## Local release gates -The dapp needs indexed protocol state for discovery and routing: +Before shipping dapp changes that touch staking, blueprint routing, iframe policy, or local deployment wiring, run the local gates against Anvil. -| State | Required for | -| ----------------------------------------------------- | ------------------------------------------------------------------------------------ | -| Blueprint creation and metadata updates | Catalog, product cards, app slug resolution, and fallback pages. | -| Source acknowledgement | Showing which runnable artifact an operator accepted. | -| Operator registration and endpoint metadata | Operator selection, endpoint routing, and reliability screens. | -| Service request, approval, extension, and termination | Service-instance lifecycle and customer history. | -| Job events | Provision, configure, start, stop, status, workflow, and settlement-trigger history. | -| Pricing and payment events | Operator quote surfaces, service cost, and fee reconciliation. | -| Quality-of-service heartbeats | Liveness filtering, operator rankings, and incident investigation. | +```bash +yarn build:tangle-dapp +yarn build:tangle-cloud +yarn nx test tangle-cloud --run +yarn nx run dapp-config:build +yarn test:staking:local +``` -The indexer does not prove endpoint honesty. It tells the app what the protocol saw. The app still needs operator API probes, settlement evidence, TEE verification, or blueprint-specific checks before making stronger claims. +For browser coverage, run: -## Local Release Gates +```bash +yarn test:staking:local-ui +``` -Before shipping dapp changes that touch staking, blueprint routing, iframe policy, or local deployment wiring, run the local gates against an Anvil testnet: +The direct local staking gate must exercise real contract calls for: -| Gate | What it proves | -| ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `yarn test:staking:local` | Contract path for deposit, delegate, rewards distribution, claim, unstake, and withdraw works against local protocol contracts. | -| `yarn test:wallet-flows:staking:gate` | Browser wallet-flow reports contain the required staking flows with no blocker partials. | -| `yarn test:staking:local-release` | Runs the contract-path gate and the browser-flow release gate together. | +1. deposit +2. delegate +3. claim rewards +4. schedule undelegate +5. execute undelegate +6. schedule withdraw +7. execute withdraw -These gates are local proof, not deployment proof. A production release still needs the hosted dapp URL, docs URL, and indexer endpoint verified after deploy. +The browser gate should prove the same actions through the UI. If local GraphQL/indexer noise blocks the browser run, say that plainly and keep the direct contract gate as the hard proof. Do not claim the browser gate passed unless it did. -## Integration Rules +## Implementation rules -| Rule | Reason | -| ------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------ | -| Prefer metadata and iframe policy over bespoke React modules. | Keeps every blueprint on the same host contract. | -| Keep protocol fallback pages available. | Operators and auditors need raw state even when a hosted app is down. | -| Keep link-out mode for apps without a trusted iframe host. | Prevents widening iframe permissions before the publisher app is ready. | -| Show unavailable, pending, failed, and healthy as distinct states. | Users need to know whether the chain, indexer, operator API, or hosted app is the failing layer. | -| Treat local release gates as required for staking changes. | Staking regressions are expensive to discover through a deployed browser app. | +| Rule | Reason | +| ------------------------------------------------------------- | ------------------------------------------------------------------------------- | +| Prefer metadata and iframe policy over bespoke React modules. | New first-party apps should not require a dapp redeploy for every route change. | +| Keep the generic protocol route. | Operators and auditors need raw chain/indexer state. | +| Use operator APIs for live product state. | The indexer cannot tell whether a bot, sandbox, or venue is healthy right now. | +| Keep jobs for commands, not reads. | Job history should mean work was requested. | +| Show unavailable, pending, failed, and healthy separately. | Each state has a different fix. | diff --git a/pages/blueprints/index.mdx b/pages/blueprints/index.mdx index b5b155c..4df0049 100644 --- a/pages/blueprints/index.mdx +++ b/pages/blueprints/index.mdx @@ -1,42 +1,53 @@ --- title: Production Blueprints -description: First-party Tangle blueprints available to operators and app builders. +description: First-party Tangle blueprints, written for users, operators, and app builders. --- # Production Blueprints -These blueprints are first-party capability templates built on the Tangle protocol and runtime stack. Each one defines software operators can run, on-chain service-instance state the dapp can index, and an application surface users can open from Tangle Cloud. +A Tangle blueprint is a product template that operators can run. It is not the live service by itself. -Start with the [protocol model](/blueprints/protocol-model) if you are mapping the moving parts. A blueprint defines the template, operators register to serve it, users request service instances, and apps combine indexed protocol state with operator APIs. +The live unit is a service instance. A user requests it, picks registered operators, and then sends jobs to that instance. Tangle Cloud should make that lifecycle obvious: template first, operator capacity second, service instance third. -An indexer is the service that reads contract events and turns them into queryable app state. These blueprints expect the indexer to track blueprint creation, operator registration, service-instance creation, service extension, source acknowledgement, job activity, pricing, and quality-of-service heartbeats. +## Start here -Use the [operator matrix](/blueprints/operator-matrix) for host sizing, AI credential planning, runtime isolation, and proof boundaries across all three products. Use [dapp integration](/blueprints/dapp-integration) for Tangle Cloud routing, iframe/link mode, indexer state, and local release gates. +If you only remember one model, use this: -## Blueprint Catalog +| Layer | Plain meaning | +| --------------------- | ---------------------------------------------------------------------------------------------- | +| Blueprint | The recipe: jobs, metadata, binaries, contracts, and app policy. | +| Operator registration | An operator says, on-chain, "I can run this recipe." | +| Service request | A user chooses parameters and the operators that should serve them. | +| Service instance | The running service created from that request. | +| Job | A command against one service instance. Jobs change state or ask operators to do work. | +| Query | A read from contracts, the indexer, or an operator API. Queries should not be modeled as jobs. | -| Blueprint | Capability template | Runtime model | App surface | -| ------------------------------------------------ | ------------------------------------------------------------------------------------ | --------------------------------------------------------- | -------------------------------------- | -| [AI Agent Sandbox](/blueprints/ai-agent-sandbox) | Service instances for agent sessions, workflow runs, terminals, files, and tool use | Docker, Firecracker microVM, or TEE-backed instance | `agent-sandbox.blueprint.tangle.tools` | -| [AI Trading](/blueprints/ai-trading) | Service instances for trading bots, risk checks, vault policy, and strategy workers | Cloud fleet, per-service instance, or TEE-backed instance | `trading-arena.blueprint.tangle.tools` | -| [Surplus Market](/blueprints/surplus-market) | Service instances for inference credit markets, order books, settlement, and serving | Operator HTTP service plus real inference backend | `surplus-market.pages.dev` | +The indexer turns protocol events into app state. It can tell the dapp which blueprints exist, which operators registered, which service instances were created, which jobs landed, and which endpoints operators advertised. It does not prove that an endpoint is healthy, honest, or serving the right model. Product pages still need operator API checks, contract reads, attestations, settlement receipts, or proof systems. -## Operator Planning +## First-party blueprint products -| Question | Where to decide | -| ------------------------------------ | ------------------------------------------------------------------------------------------------------------- | -| What machine size do I need? | Start with [operator sizing](/operators/manager/sizing), then use the blueprint-specific resource tables. | -| Which isolation mode should I run? | Use [sandboxing and safety](/infrastructure/sandboxing) for runtime policy, then follow the blueprint page. | -| Which secrets are required? | Each blueprint page lists the required chain keys, provider credentials, inference backends, and app secrets. | -| How does the dapp route users? | The dapp uses indexed blueprint metadata plus first-party registry entries for curated app routes. | -| What state should be on-chain? | Use jobs for service-instance commands and contract/indexer/operator APIs for reads. | -| How do I compare blueprint products? | Use the [operator matrix](/blueprints/operator-matrix) for side-by-side host, AI, and proof requirements. | -| How do I prove the dapp still works? | Use [dapp integration](/blueprints/dapp-integration) for local release gates and routing rules. | +| Product | What users get | What operators run | App surface | +| ------------------------------------------------ | ---------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | -------------------------------------- | +| [AI Agent Sandbox](/blueprints/ai-agent-sandbox) | Sandboxes for agent sessions, workflows, terminals, files, ports, and secrets. | Docker, Firecracker, or TEE-backed sandbox runtimes. | `agent-sandbox.blueprint.tangle.tools` | +| [AI Trading](/blueprints/ai-trading) | Trading bots with vault policy, strategy config, paper/live mode, and execution history. | Cloud fleet, dedicated instance, or TEE instance operator. | `trading-arena.blueprint.tangle.tools` | +| [Surplus Market](/blueprints/surplus-market) | A market for prepaid inference credits, RFQs, fills, redemption, and settlement. | A venue operator, settlement keys, and real inference capacity when bonded. | `surplus-market.pages.dev` | -## Source Repositories +## Which page should I read? -| Blueprint | Repository | -| ---------------- | ------------------------------------------------------------ | -| AI Agent Sandbox | https://github.com/tangle-network/ai-agent-sandbox-blueprint | -| AI Trading | https://github.com/tangle-network/ai-trading-blueprint | -| Surplus Market | https://github.com/tangle-network/surplus | +| Question | Page | +| --------------------------------------------------------------------- | ------------------------------------------------------------------------------ | +| "How does the protocol lifecycle work?" | [Protocol model](/blueprints/protocol-model) | +| "What size machine do I need?" | [Operator matrix](/blueprints/operator-matrix) plus the product operator page. | +| "Which AI keys or model backends are required?" | [Operator matrix](/blueprints/operator-matrix) and the product runtime page. | +| "How should Tangle Cloud route these apps?" | [Dapp integration](/blueprints/dapp-integration) | +| "How do I prove staking and blueprint UI changes still work locally?" | [Dapp integration](/blueprints/dapp-integration#local-release-gates) | + +## Source repos + +| Product | Source | +| ---------------- | -------------------------------------------------------------------- | +| AI Agent Sandbox | https://github.com/tangle-network/ai-agent-sandbox-blueprint | +| AI Trading | https://github.com/tangle-network/ai-trading-blueprint | +| Surplus Market | Internal Tangle repository; public app at `surplus-market.pages.dev` | + +These docs describe the current repo contracts and the public app integration shape. If a repo says a path is not live yet, the docs should say the same thing. diff --git a/pages/blueprints/operator-matrix.mdx b/pages/blueprints/operator-matrix.mdx index e966b45..0c6c6f7 100644 --- a/pages/blueprints/operator-matrix.mdx +++ b/pages/blueprints/operator-matrix.mdx @@ -1,52 +1,81 @@ --- -title: Blueprint Operator Matrix -description: Cross-blueprint host, AI, runtime, and proof requirements for Tangle blueprint operators. +title: Operator Matrix +description: Host, AI, runtime, and proof requirements for first-party Tangle blueprint operators. --- -# Blueprint Operator Matrix +# Operator Matrix -Use this page to compare the first-party blueprint products before sizing hosts, buying GPUs or inference credits, or publishing an operator endpoint. +Use this page before you buy a VPS, expose an operator endpoint, or set model provider keys. -## Product Comparison +The three first-party blueprints do not fail the same way. A sandbox operator runs isolated compute. A trading operator runs bots and protects capital. A Surplus operator runs a market venue and backs inference credits. Treat those as different businesses. -| Blueprint | Operator job | Customer-facing resource | Default app | Runtime isolation | -| ---------------- | -------------------------------------------------------------------------------- | ---------------------------------------------------------------------- | -------------------------------------- | ----------------------------------------------------------------------------- | -| AI Agent Sandbox | Run isolated agent sandboxes and authenticated sidecar APIs. | Sandbox, workflow, terminal, files, ports, secrets, and snapshots. | `agent-sandbox.blueprint.tangle.tools` | Docker, Firecracker microVM, or TEE instance. | -| AI Trading | Run trading bots, strategy workers, risk checks, and trading APIs. | Bot, vault policy, strategy config, trade log, and operator report. | `trading-arena.blueprint.tangle.tools` | Docker sidecar by default; instance and TEE variants available. | -| Surplus Market | Run an inference-credit venue, quote market, serve redemption, and settle fills. | Credit lot, order book, RFQ, redemption receipt, and settlement batch. | `surplus-market.pages.dev` | Operator HTTP service plus controlled inference backend; settlement on-chain. | +## What each operator is responsible for -## Minimum Host Plan +| Blueprint | Operator responsibility | Main failure to avoid | +| ---------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | +| AI Agent Sandbox | Start sandboxes, keep sidecars reachable, protect session tokens and secrets, and report lifecycle state. | Exposing a sandbox or secret outside the service instance that owns it. | +| AI Trading | Run bot sandboxes, preserve bot state, enforce paper/live policy, expose the operator API, and keep risk checks online. | Letting a bot spend capital outside its envelope or provider budget. | +| Surplus Market | Operate a venue, quote or match inference credits, settle fills, and redeem credits against real capacity when bonded. | Selling a credit lot that cannot be served, redeemed, or settled. | -| Blueprint | Minimum | Recommended | Ports | Notes | -| ---------------- | --------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | -| AI Agent Sandbox | Docker host with Rust 1.88+, Foundry, Node 22+/pnpm for UI work. | Separate persistent state volume, TLS ingress, explicit public host, pre-pulled all-harness sidecar image. | Operator API defaults around `9100`; sidecar HTTP and SSH are container-internal by default. | Firecracker hosts also need kernel, rootfs, TAP/vsock support, and guest metadata daemon. | -| AI Trading | 2 vCPU, 4 GB RAM, 40 GB SSD, Docker 24+, public IPv4. | 4 vCPU, 8 GB RAM, 80 GB SSD, TLS on 443, low-latency RPC. | Operator API `9200`, trading API `9100`, public TLS on `443`. | The sidecar image is multi-GB and each bot accumulates state. | -| Surplus Market | Rust operator, chain RPC, persistent book/outbox state, settlement submitter key. | Dedicated venue host, supervised process, private settlement key handling, real inference backend. | HTTP venue default `9100`; sidecar default `9110` for market-making. | Bonded issuers must back lots with inference they run or control. | +## Host shape -## AI And Secret Requirements +| Blueprint | Minimum host | Recommended host | Notes | +| ---------------- | --------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------- | +| AI Agent Sandbox | Docker host, Rust 1.88+, Foundry, Node 22+/pnpm for UI work. | Dedicated state volume, TLS ingress, public host, pre-pulled sidecar image. | Firecracker needs kernel, rootfs, TAP/vsock support, and the guest metadata daemon. | +| AI Trading | Ubuntu 22.04/24.04, x86_64, Docker 24+, 2 vCPU, 4 GB RAM, 40 GB SSD. | 4 vCPU, 8 GB RAM, 80 GB SSD, public IPv4, ports 22 and 443 open. | Releases currently target x86_64. Build from source on other arches. | +| Surplus Market | Rust operator, chain RPC, persistent venue state, settlement submitter key. | Dedicated venue host, supervised process, private key separation, real inference backend. | Bonded issuers must back lots with inference they run or control. | -| Blueprint | Can run without model keys? | When model keys are needed | Secrets operators must protect | -| ---------------- | ------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------ | -| AI Agent Sandbox | Yes for sandbox lifecycle and non-model commands. | Prompt, task, and workflow execution need the selected harness or model provider secret. | `SESSION_AUTH_SECRET`, sidecar auth tokens, provider keys, sandbox secrets, TEE provider credentials. | -| AI Trading | Yes for deterministic strategy ticks and paper trading. | Agentic activation, chat, and model-driven strategy work need provider keys such as `ZAI_API_KEY`, `ANTHROPIC_API_KEY`, or `TANGLE_API_KEY`. | Operator key, bot secrets, provider keys, vault and trading contract config, admission allowlist. | -| Surplus Market | Yes for the order book and dry-run venue. | Bonded credit redemption needs an inference backend: managed vLLM, external OpenAI-compatible API, or controlled provider capacity. | Operator attester key, submitter key, inference API key, router or ShieldedCredits credentials, venue state. | +## Public ports -## Harness Reality +| Blueprint | Public surface | Keep private | +| ---------------- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- | +| AI Agent Sandbox | TLS ingress to the operator API when intentionally exposed. Default operator API is around `9100`. | Sidecar HTTP and SSH ports should stay internal unless explicitly proxied. | +| AI Trading | Caddy or equivalent TLS on 443 to the operator API. | Raw trading API ports such as `9100` and `9200` should not be exposed directly. | +| Surplus Market | Venue HTTP endpoint, optionally an onion endpoint for privacy mode. | Settlement keys, submitter keys, mm-sidecar, and inference provider credentials. | -Model harnesses as runtime capabilities, not as the product boundary. +## AI and inference credentials -The sandbox product advertises runtime capabilities through `GET /api/capabilities`. Its current all-harness sidecar path includes Claude Code, Codex, OpenCode, Kimi, and Gemini. Operators should treat that endpoint as the live contract because the harness list can grow without changing the blueprint ABI. +| Blueprint | Can boot without model keys? | Keys needed for | Budget risk | +| ---------------- | ---------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- | +| AI Agent Sandbox | Yes. Lifecycle, terminals, files, ports, snapshots, and non-model commands can work without provider keys. | Prompt, task, and workflow execution through a selected harness or model provider. | Provider spend belongs to whoever injects the key into the service instance. | +| AI Trading | Yes. Deterministic strategy ticks and paper bots can run without model keys. | Agentic activation, chat, and model-driven strategy work. Current examples include `ZAI_API_KEY`, `ANTHROPIC_API_KEY`, `TANGLE_API_KEY`, and opencode model env vars. | The operator pays unless the product adds a separate customer billing rail. Default operator docs warn there is no built-in per-bot spend cap. | +| Surplus Market | The order book and dry-run venue can run without inference. | Bonded credit redemption needs a real backend such as managed vLLM or an OpenAI-compatible API the operator controls. | A bonded issuer is financially exposed if it sells credits it cannot redeem. Router fallback is not acceptable for bonded issuance. | -AI Trading uses the same sidecar direction for agentic work, but the trading product boundary is the bot, vault policy, strategy config, and risk gate. A harness is one execution backend for the bot's agentic mode, not the product itself. +## Harnesses are not the product boundary -Surplus can run deterministic market-making through `@surplus/mm-loop`. Agentic quoting is a sidecar mode that uses the same risk gate before quotes reach the venue. +The sandbox product is the sandbox service instance plus its operator API. The current all-harness sidecar in the sandbox blueprint advertises Claude Code, Codex, opencode, Kimi Code, and Gemini CLI through `GET /api/capabilities`. -## Proof Requirements +That endpoint is the contract the app should read. Do not make docs or UI copy pretend OpenCode, Codex, or any one harness is the integration. Harness support can change by publishing a new sidecar image without changing the blueprint ABI. -| Blueprint | What the indexer can prove | What still needs runtime or settlement proof | -| ---------------- | -------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| AI Agent Sandbox | Blueprint, operator, service, job, source, and heartbeat state. | Endpoint health, sandbox readiness, prompt output, secret handling, and TEE quote validity. | -| AI Trading | Blueprint registration, service instances, operator endpoint metadata, jobs, pricing pointers, and heartbeats. | Bot health, market execution, paper/live mode, model spend, and trade policy enforcement. | -| Surplus Market | Blueprint, operator, service, job, endpoint, and heartbeat state. | Order-book correctness, fill settlement, credit redemption, attester quorum, SP1 batch proof, and inference delivery. | +AI Trading uses the same sidecar direction for agentic work, but the trading product is the bot, vault policy, risk gate, paper/live state, and execution history. The agent harness is one backend for a bot. -The indexer is discovery infrastructure. Product surfaces should still use operator APIs, contract reads, attestation records, settlement receipts, or proof systems for claims that are not visible in Tangle protocol events. +## Runtime isolation + +| Blueprint | Runtime modes | Operator decision | +| ---------------- | ------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- | +| AI Agent Sandbox | Docker, Firecracker, TEE instance. | Docker is the simple path. Firecracker adds VM isolation and host setup. TEE mode adds provider credentials and attestation handling. | +| AI Trading | Docker sidecar by default, dedicated instance mode, TEE instance mode. | Start with paper mode and allowlist admission. Use TEE only when strategy confidentiality is worth the hardware or provider complexity. | +| Surplus Market | Operator HTTP venue plus optional mm-sidecar, shared CLOB, Tor onion, settlement submitter. | Decide whether you are a dry-run venue, an attester, or a bonded issuer. Bonded issuers need real inference and settlement discipline. | + +## Proof boundary + +| Blueprint | Indexer can show | Product must still prove | +| ---------------- | ------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------- | +| AI Agent Sandbox | Blueprint registration, operator registration, service requests, jobs, source updates, and heartbeats. | Endpoint health, sandbox readiness, secret handling, TEE attestation, and sidecar capability support. | +| AI Trading | Blueprint registration, service instances, operator endpoints, jobs, pricing pointers, and heartbeats. | Bot health, paper/live mode, model spend, vault policy, trade execution, and validator status. | +| Surplus Market | Blueprint registration, operator registration, service instances, jobs, endpoints, and heartbeats. | Order-book correctness, fill settlement, credit redemption, attester quorum, SP1 proof path, and inference delivery. | + +## Operator preflight + +Before advertising capacity: + +1. Build the operator binary and run the repo's local smoke. +2. Set persistent state, keystore, RPC, and public endpoint values. +3. Register on the restaking layer if the blueprint requires stake. +4. Register for the specific blueprint ID. +5. Request or join a service instance. +6. Hit the operator health endpoint from outside the host. +7. Submit one real job or product action through the local or testnet path. +8. Keep the command output, IDs, and transaction hashes in the PR or runbook. + +"It builds" is not enough for an operator. A blueprint operator is real only after it can register, serve a service instance, and prove one non-mocked path. diff --git a/pages/blueprints/protocol-model.mdx b/pages/blueprints/protocol-model.mdx index 4b9dc6f..76861c7 100644 --- a/pages/blueprints/protocol-model.mdx +++ b/pages/blueprints/protocol-model.mdx @@ -1,65 +1,95 @@ --- -title: Blueprint Protocol Model -description: How Tangle blueprints, operators, service instances, jobs, apps, and indexers fit together. +title: Protocol Model +description: "The blueprint lifecycle: template, operator registration, service request, service instance, jobs, and reads." --- -# Blueprint Protocol Model - -A Tangle blueprint is a reusable capability definition. It does not run user workloads by itself. Operators register for a blueprint, users request service instances from registered operators, and those service instances execute the concrete workload. - -## Core Terms - -| Term | Plain meaning | -| --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- | -| Blueprint | The template: metadata, binaries, job definitions, pricing rules, and optional blueprint-specific contracts. | -| Operator registration | An operator's on-chain statement that it can serve a blueprint, usually with endpoint metadata, pricing, capacity, and source acknowledgement. | -| Service request | A user asks one or more registered operators to instantiate the blueprint for a concrete purpose. | -| Service instance | The live unit created from a service request. It has selected operators, service state, jobs, and runtime-specific resources. | -| Job | A command sent to a service instance. Jobs change state or ask operators to perform work. They are not the read path for normal app queries. | -| Operator API | The off-chain HTTP or RPC surface exposed by an operator runtime. Apps use it for live product state, controls, files, books, terminals, and quotes. | -| Indexer | The service that reads chain events and contract state, then turns them into queryable app state. It discovers state; it does not prove honesty. | -| Hosted app | The product UI for users. It is not the blueprint itself, even when it is first-party and launched from Tangle Cloud. | -| BSM | Blueprint Service Manager contract logic. When present, it handles blueprint-specific on-chain rules such as validation, payment, or slashing hooks. | - -## Lifecycle - -| Step | What happens | Who cares most | -| ---- | -------------------------------------------------------------------------------------------------- | -------------------------------------------------- | -| `1` | A developer publishes a blueprint definition, binaries, metadata, and optional BSM contracts. | Developers and auditors. | -| `2` | Operators register for the blueprint and expose their runtime endpoint, capacity, and pricing. | Operators, dapps, and indexers. | -| `3` | A user requests a service instance and selects the registered operators that should serve it. | Users and operators. | -| `4` | Operators run the runtime for that service instance and submit acknowledgements, results, or jobs. | Operators, users, and dispute or settlement logic. | -| `5` | Apps read indexed chain state plus operator APIs to present the product experience. | Users, support teams, and product surfaces. | - -## Audience Map - -| Audience | What they need to know | -| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Consumer | They request a concrete service instance and use the app or API output. They should not need to understand operator internals. | -| Developer | They define the blueprint, job schema, metadata, app policy, contracts, and any BSM or settlement logic. | -| Operator | They register for the blueprint, keep the runtime online, expose the right endpoint, manage keys and provider credentials, and meet the resource profile. | -| App builder | They use indexed protocol state for discovery and operator APIs for live product behavior. They should keep protocol fallback pages available for raw state. | -| Indexer owner | They must preserve enough event and state history to distinguish unavailable data, pending provisioning, operator failure, and normal service termination. | - -## Jobs And Reads - -Jobs are for service-instance commands: create a sandbox, trigger a workflow, list an instrument, start a trading bot, or report status. Reads should use the cheapest accurate source: - -| Need | Preferred read path | -| ---------------------------- | ------------------------------------------------------------------------------------------------------- | -| Blueprint and operator lists | Indexer over blueprint creation, source updates, operator registration, pricing, and endpoint metadata. | -| Current contract state | Direct contract call or indexed state, depending on latency and UX needs. | -| Live runtime state | Operator API, because terminals, files, books, quotes, and bot status are off-chain runtime state. | -| Settlement evidence | Blueprint-specific settlement contracts, attestation records, proofs, or venue APIs. | - -The indexer is a discovery layer. It can show which operators registered, which endpoints they published, which jobs were emitted, and which heartbeats landed. Endpoint health, response quality, model behavior, trade execution, and inference redemption still need runtime checks, app-level validation, or blueprint-specific proof paths. - -## Layer Boundaries - -| Do not conflate | Correct distinction | -| ----------------------------- | -------------------------------------------------------------------------------------------------------- | -| Blueprint vs service instance | The blueprint is the template. The service instance is the live runtime unit created from that template. | -| Operator vs hosted app | Operators run the runtime for selected service instances. The hosted app is the user's UI. | -| Indexer vs proof | The indexer reports protocol-visible state. It does not prove an endpoint is honest or healthy. | -| Job vs query | A job requests work or state change. A query reads state from contracts, the indexer, or operator APIs. | -| Sidecar vs BSM | A sidecar is runtime software. A BSM is contract-side service-management logic. | +# Protocol Model + +Blueprints are easy to explain badly because one word gets used for too many things. Keep the layers separate. + +A blueprint is the template. It defines what can be run: jobs, metadata, binaries, app routing, and optional Blueprint Service Manager logic. Operators register for that template. A user requests a service instance from a set of registered operators. That service instance is the thing the user actually uses. + +## The lifecycle + +1. A developer publishes a blueprint definition, runnable artifact, metadata, and any blueprint-specific contracts. +2. Operators register for the blueprint and publish the endpoint or metadata the app needs to find them. +3. A user requests a service instance and selects one or more registered operators. +4. Operators approve or join the request. +5. The service instance becomes active. +6. The user submits jobs to that service instance. +7. Apps read chain state, indexed state, and operator APIs to show what happened. + +The service instance is the boundary for state, auth, and billing. If a page says the template itself is live, read that as a wording bug. The service instance is live. + +## Names that should not drift + +| Term | Use it for | +| --------------------- | ------------------------------------------------------------------------------------- | +| Blueprint | The abstract capability definition. | +| Operator registration | An operator's on-chain opt-in for a blueprint. | +| Service request | The user's request to instantiate the blueprint with chosen operators and parameters. | +| Service instance | The live unit created from a request. | +| Job | A state-changing command against a service instance. | +| Query | A read through `eth_call`, the indexer, or an operator API. | +| Operator API | The off-chain API an operator exposes for live product state and controls. | +| Hosted app | The product UI. It may be first-party, but it is not the blueprint. | +| BSM | Blueprint Service Manager contract logic for blueprint-specific rules. | + +## Jobs are not reads + +Jobs mutate state or ask the operator to perform work. They are the wrong tool for normal app reads. + +Use reads for: + +- service and operator lists +- health checks +- bot rosters +- order books +- terminal state +- file lists +- price quotes +- proof or attestation lookups + +Use jobs for: + +- provisioning or deprovisioning +- workflow triggers +- market-making ticks +- service-level commands that should be recorded as protocol activity + +This split matters. If reads become jobs, the app gets slow, operators pay more gas than needed, and the protocol history stops meaning "work was requested." + +## What the indexer can prove + +The indexer can show what the chain observed: + +| Indexed state | Useful for | +| ------------------------------------- | ------------------------------------------------------------------------- | +| Blueprint creation and source updates | Catalogs, audits, and app routing. | +| Operator registration | Discovery, capacity lists, and endpoint metadata. | +| Service requests and approvals | Provisioning status and operator participation. | +| Service instances | Instance pages, ownership, selected operators, and lifecycle. | +| Jobs | User-visible commands, support traces, and billing or settlement context. | +| Heartbeats or status events | Liveness history and incident timelines. | + +The indexer cannot prove endpoint honesty, model output quality, exchange execution, or credit redemption. Those need product-specific evidence: operator API probes, contract state, attestations, settlement receipts, SP1 proofs, or signed reports. + +## Reader map + +| Reader | What they need from these docs | +| ------------- | ------------------------------------------------------------------------------------------------------------------- | +| Consumer | Which service instance they are using, who operates it, what evidence backs the result, and what can fail. | +| Developer | The job schema, query paths, metadata, contracts, app policy, and validation steps. | +| Operator | Hardware, ports, keys, provider credentials, pricing, capacity, health checks, and rollback steps. | +| App builder | How to route the app from metadata, when to use the generic protocol page, and where live product state comes from. | +| Indexer owner | Enough event history to distinguish pending provisioning, operator failure, normal shutdown, and missing data. | + +## Common mistakes + +| Bad wording | Better wording | +| --------------------------------------------- | ---------------------------------------------------------------------------- | +| "Deploy the blueprint for a user." | "Request a service instance from a blueprint." | +| "The operator provisions the blueprint." | "The operator provisions the service instance." | +| "The dapp reads the blueprint for bot state." | "The dapp reads indexed service state and the operator API for bot state." | +| "Submit a job for a normal read." | "Read from the contract, indexer, or operator API." | +| "The hosted app is the blueprint." | "The hosted app is the UI for service instances created from the blueprint." | diff --git a/pages/blueprints/surplus-market/dapp-and-indexer.mdx b/pages/blueprints/surplus-market/dapp-and-indexer.mdx index 650ea28..fd21bda 100644 --- a/pages/blueprints/surplus-market/dapp-and-indexer.mdx +++ b/pages/blueprints/surplus-market/dapp-and-indexer.mdx @@ -1,44 +1,72 @@ --- title: Surplus Market Dapp and Indexer -description: Dapp routing and indexer requirements for the Surplus Market blueprint. +description: Dapp routing, metadata gaps, and indexer requirements for the Surplus Market blueprint. --- -# Dapp and Indexer +# Surplus Market Dapp and Indexer -Surplus currently has a hosted market app at `https://surplus-market.pages.dev/`. Tangle Cloud should expose it as a first-party link-out app until a dedicated `blueprint.tangle.tools` iframe host and iframe policy are deployed. +Surplus is live as a hosted app at `https://surplus-market.pages.dev/`. -## Metadata Contract +Tangle Cloud should treat it as a first-party link-out until the repo publishes rich `blueprintUi` metadata and a `*.blueprint.tangle.tools` iframe host. Do not pretend it has the same iframe contract as Sandbox and Trading yet. -The deployed metadata currently declares: +## Current metadata -| Field | Value | -| ----------------- | ------------------------------------------- | -| `name` | `surplus` | -| `category` | `inference-market` | -| `author` | `Tangle` | -| `code_repository` | `https://github.com/tangle-network/surplus` | +The current deployed metadata is minimal: -Unlike Sandbox and Trading, this metadata does not yet carry a rich `blueprintUi` object. The dapp should keep the first-party registry entry for `surplus` until the repo publishes equivalent metadata on-chain. +| Field | Current value | +| ----------------- | ------------------------------- | +| `name` | `surplus` | +| `category` | `inference-market` | +| `code_repository` | Internal Surplus repository URL | -## Dapp Behavior +It does not yet include the rich `blueprintUi` object used by Sandbox and Trading. The dapp should keep a first-party registry entry for `surplus` until that changes. -| Surface | Behavior | -| ------------------ | ----------------------------------------------------------------------------------------------------- | -| Tangle Cloud route | Reserve the `surplus` slug and match first-party Surplus metadata. | -| Hosted app | Open `https://surplus-market.pages.dev/` as a trusted link, not an iframe. | -| Protocol fallback | Preserve the raw indexed blueprint and service-instance route for operator and settlement inspection. | +## Routing rule -## Indexed State +| Route | Behavior | +| ----------------- | -------------------------------------------------------------- | +| Product app | Link to `https://surplus-market.pages.dev/`. | +| Protocol fallback | Preserve the raw indexed blueprint and service-instance route. | +| Future iframe | Use only after a trusted host and iframe policy are published. | -The indexer should expose: +The product app owns market UX. The protocol fallback owns chain and service inspection. -| State | Why it matters | -| ------------------------------------- | -------------------------------------------------------- | -| Blueprint creation and source updates | Finds the Surplus operator binary and metadata. | -| Operator registration | Discovers venues and issuer/attester operators. | -| Service creation | Distinguishes independent books from shared CLOB books. | -| Job events | Tracks `list_instrument`, `status`, and `workflow_tick`. | -| Operator endpoint metadata | Lets the app discover venue endpoints. | -| QoS heartbeats | Shows venue liveness and reliability. | +## Indexed state -Settlement-specific fills, lots, redemption receipts, and attestation state live in Surplus settlement contracts and venue APIs. The Tangle indexer should at least preserve pointers so product surfaces can reconcile protocol service instances with market state. Endpoint liveness and venue honesty still need venue checks, settlement evidence, or proof paths. +| State | Why the dapp needs it | +| ------------------------------------- | --------------------------------------------------------------- | +| Blueprint creation and source updates | Find the Surplus operator artifact and metadata. | +| Operator registration | Discover venues, issuers, and attesters. | +| Service requests and instances | Show which operators are serving a market instance. | +| Jobs | Show `list_instrument`, `status`, and `workflow_tick` activity. | +| Endpoint metadata | Route app checks and operator inspection. | +| Heartbeats | Distinguish dead venues from quiet books. | + +## Product state that does not belong only in the indexer + +The app needs live product checks for: + +- order book depth +- reference price +- operator inventory +- RFQ response +- settlement outbox +- fill settlement +- credit redemption +- attester quorum +- inference backend health + +The indexer can show that a job happened. It cannot prove that a credit lot was redeemed or that a model request was served honestly. Use settlement receipts, spend vouchers, attester signatures, SP1 proofs, or operator API responses for those claims. + +## User-facing states + +| State | Meaning | +| ----------------------- | ------------------------------------------------------------------ | +| No venue | No operator endpoint is available for the selected market. | +| Venue unreachable | The endpoint is registered, but the app cannot call it. | +| Quote rejected | The risk gate blocked the sidecar quote. | +| Fill pending settlement | The order matched, but the fill is still in the outbox. | +| Credit redeemable | A lot exists and can be spent against a live backend. | +| Credit defaulted | Redemption failed and the settlement/default path must resolve it. | + +Those states are the product. Hide them and users cannot reason about the market. diff --git a/pages/blueprints/surplus-market/index.mdx b/pages/blueprints/surplus-market/index.mdx index c572f73..b2033a1 100644 --- a/pages/blueprints/surplus-market/index.mdx +++ b/pages/blueprints/surplus-market/index.mdx @@ -5,51 +5,72 @@ description: First-party Tangle blueprint for an AI inference credit market. # Surplus Market Blueprint -The Surplus Market blueprint defines the template for a prepaid AI inference credit market. Buyers acquire discounted inference capacity through service instances. Operators make markets in credit lots, serve or back redemption, and settle fills on-chain. +Surplus is a market for prepaid inference credits. -Source repo: https://github.com/tangle-network/surplus +Buyers acquire discounted credits. Operators sell or make markets in those credits. Settlement happens on-chain, while the order book and quoting run off-chain inside the operator venue. When an operator is bonded as an issuer, it must back credit lots with inference it runs or controls. -## Product Shape +Source repo: internal Tangle repository. The public surface is the hosted app and these docs until the repo is public. -| Area | Source-backed behavior | -| ------------------ | ----------------------------------------------------------------------------------------------------- | -| Operator binary | `surplus-operator` for the full Tangle runner; `surplus-operator-lite` for HTTP-only local operation. | -| Blueprint category | `inference-market` | -| Default port | `9100` | -| Hosted app | `https://surplus-market.pages.dev/` | -| Settlement | `SurplusSettlement` with attested quorum or SP1 proof boundary. | +## What happens in the product + +1. An operator runs a venue. +2. Buyers and sellers place orders or request firm quotes. +3. The venue matches orders and emits settlement intents. +4. Signed fills settle on-chain. +5. Credit lots redeem against inference capacity. +6. If an issuer defaults, settlement and slashing paths decide the remedy. + +The order book is only the entry point. The hard part is making a credit redeemable. + +## Operator shapes + +| Binary | Use | +| ----------------------- | ------------------------------------------------------------------------------------------ | +| `surplus-operator-lite` | HTTP venue only. Good for local and venue API work. | +| `surplus-operator` | Full Tangle runner, built with the `blueprint` feature. Runs as a real blueprint operator. | + +The full operator runs the venue inside a Tangle `BlueprintRunner`. The venue starts as a background service, and jobs can drive actions such as listing an instrument, status checks, and workflow ticks. + +## Venue API + +| Route | Purpose | +| ------------------------ | ------------------------------------------------------------------------- | +| `POST /order` | Place a limit order and produce fills or settlement intents. | +| `POST /cancel` | Cancel a resting order. | +| `POST /book` | Read depth, reference price, and operator inventory. | +| `POST /mm-tick` | Pull risk-gated quotes from the market-making sidecar and replace quotes. | +| `POST /ref` | Push a reference price. | +| `POST /order-signed` | Place an EIP-712 signed firm order. | +| `POST /rfq` | Request a signed short-TTL quote. | +| `POST /rfq/fill` | Cross a firm quote with a countersigned taker order. | +| `GET /settlement/outbox` | Read fills waiting for settlement. | +| `POST /settlement/flush` | Submit the outbox through the chain path when enabled. | + +The operator is the venue. The mm-sidecar suggests quotes. The risk gate decides whether those quotes can be placed. ## Jobs -| ID | Job | Status | -| ---- | ----------------- | --------------------------------------- | -| `0` | `list_instrument` | Implemented. | -| `1` | `configure` | Reserved placeholder. | -| `2` | `start_making` | Reserved placeholder. | -| `3` | `stop_making` | Reserved placeholder. | -| `4` | `status` | Implemented. | -| `30` | `workflow_tick` | Implemented; drives market-maker ticks. | - -## Operator API - -| Route | Purpose | -| -------------------------------- | --------------------------------------------------- | -| `POST /order` | Place limit orders and emit settlement intents. | -| `POST /cancel` | Cancel a resting order. | -| `POST /book` | Read depth, reference price, and inventory. | -| `POST /mm-tick` | Pull risk-gated quotes and replace operator quotes. | -| `POST /rfq` and `POST /rfq/fill` | Quote and fill signed firm RFQs. | -| `GET /settlement/outbox` | Read settleable fills. | -| `POST /settlement/flush` | Submit fills when chain settlement is enabled. | - -## Read Next - -| Page | Use it for | -| ------------------------------------------------------------------------------- | ------------------------------------------------------------- | -| [Operator Requirements](/blueprints/surplus-market/operator-requirements) | Env vars, CLOB setup, privacy mode, app env. | -| [Settlement and Inference](/blueprints/surplus-market/settlement-and-inference) | Real inference backend, credit lots, redemption, quorum, SP1. | -| [Dapp and Indexer](/blueprints/surplus-market/dapp-and-indexer) | Dapp link-out, metadata gaps, indexed market state. | - -## Source Material - -This page is based on the Surplus repo's `README.md`, `BLUEPRINT.md`, `blueprint.toml`, `deploy/blueprint-definition.toml`, `deploy/blueprint-metadata.json`, `docs/testnet-release.md`, `operator/src/config.rs`, and `operator/src/inference.rs`. +The blueprint manifest defines: + +| Job | Current status | +| ----------------- | -------------------------------------------------------------------------------- | +| `list_instrument` | Implemented. | +| `configure` | Reserved placeholder in the current compact definition. | +| `start_making` | Reserved placeholder in the current compact definition. | +| `stop_making` | Reserved placeholder in the current compact definition. | +| `status` | Implemented. | +| `workflow_tick` | Implemented. Pulls reference price, sidecar quotes, and updates operator quotes. | + +The placeholders preserve compact job index compatibility. Do not remove them without changing the runtime assumptions. + +## What to read next + +| Page | Use it for | +| ------------------------------------------------------------------------------- | --------------------------------------------------------------------------------- | +| [Operator Requirements](/blueprints/surplus-market/operator-requirements) | Venue host, settlement keys, inference backend, CLOB, and privacy mode. | +| [Settlement and Inference](/blueprints/surplus-market/settlement-and-inference) | Credit lots, redemption, attester quorum, SP1 path, and inference proof boundary. | +| [Dapp and Indexer](/blueprints/surplus-market/dapp-and-indexer) | Current link-out app, metadata gap, and indexed market state. | + +## Sources used + +This page is grounded in the repo `README.md`, `BLUEPRINT.md`, `blueprint.toml`, `deploy/blueprint-definition.toml`, `deploy/blueprint-metadata.json`, `docs/testnet-release.md`, `operator/src/bin/blueprint.rs`, and `operator/src/http.rs`. diff --git a/pages/blueprints/surplus-market/operator-requirements.mdx b/pages/blueprints/surplus-market/operator-requirements.mdx index 8c265f8..8f56ccd 100644 --- a/pages/blueprints/surplus-market/operator-requirements.mdx +++ b/pages/blueprints/surplus-market/operator-requirements.mdx @@ -1,52 +1,92 @@ --- title: Surplus Market Operator Requirements -description: Host and configuration requirements for Surplus Market operators. +description: Host, key, inference, CLOB, settlement, and privacy requirements for Surplus operators. --- -# Operator Requirements +# Surplus Market Operator Requirements -Surplus operators run a market venue and, when bonded as issuers, must back credit lots with real inference capacity. +A Surplus operator can be a venue, an attester, a market maker, a bonded issuer, or some combination of those roles. The obligations are different. -## Required Runtime +Do not run as a bonded issuer unless you can redeem the credits you sell. -| Requirement | Notes | -| ------------------- | ------------------------------------------------------------------- | -| `surplus-operator` | Full Tangle runner built with the `blueprint` feature. | -| HTTP venue | Default port `9100`. | -| Settlement contract | `SURPLUS_SETTLEMENT_ADDR` and chain RPC. | -| Operator key | Signs RFQ quotes and batch attestations. | -| Submitter key | Pays gas and submits settlement transactions. | -| Persistent state | Order book, settlement outbox, fills, lots, and redemption records. | +## Base host -## Environment +| Requirement | Why | +| ---------------------- | ---------------------------------------------------------------------- | +| Rust operator build | Runs `surplus-operator-lite` or `surplus-operator`. | +| Persistent venue state | Keeps books, outbox, inventory, settlement state, and operator config. | +| Chain RPC | Reads contracts and submits settlement when chain mode is enabled. | +| Supervised process | The venue should restart without losing book/accounting state. | +| HTTP endpoint | Serves the market API used by the app and other clients. | +| Private key storage | Protects issuer, attester, and submitter keys. | -| Variable | Purpose | -| ------------------------- | ----------------------------------------------------------------- | -| `SURPLUS_CHAIN_ID` | EIP-712 settlement chain ID. | -| `SURPLUS_SETTLEMENT_ADDR` | `SurplusSettlement` contract address. | -| `SURPLUS_RPC_URL` | RPC endpoint for settlement submission. | -| `SURPLUS_OPERATOR_KEY` | Attester or issuer signing key. | -| `SURPLUS_SUBMITTER_KEY` | Hot transaction key. | -| `SURPLUS_SIDECAR_URL` | Market-maker sidecar URL; default `http://127.0.0.1:9110`. | -| `SURPLUS_INSTRUMENT` | Boot market, defaulting to an Anthropic output-credit instrument. | -| `SURPLUS_MM_SIZE` | Quote size; minimum `1000`, default `50000`. | +Key separation matters. The operator key signs issuer/attester actions. The submitter key can be a separate gas/nonce key. -## Shared Books and Privacy +## Inference backend -| Mode | Variables | -| ------------- | ----------------------------------------------------------------------- | -| Shared CLOB | `SURPLUS_CLOB_OPERATORS`, `SURPLUS_CLOB_BOOK`, `SURPLUS_CLOB_THRESHOLD` | -| Attester-only | `SURPLUS_ATTESTER_ONLY=1` | -| Tor privacy | `PRIVACY_MODE=tor`, `SURPLUS_TOR_SOCKS`, `SURPLUS_ONION_FILE` | +Bonded issuance needs real inference capacity. -The privacy layer uses Arti/Tor for outbound calls and `.onion` operator services. It is not custom cryptography. +| Setting | Use | +| --------------------------- | ------------------------------------- | +| `SURPLUS_VLLM_MODEL` | Managed vLLM model backend. | +| `SURPLUS_INFERENCE_URL` | OpenAI-compatible inference endpoint. | +| `SURPLUS_INFERENCE_API_KEY` | Credential for that endpoint. | -## App Environment +Router-proxy mode is useful for tests and non-bonded flows. A bonded issuer must not rely on router fallback because the credit lot must be backed by capacity the issuer runs or controls. -The hosted app needs: +## Settlement keys and config -| Variable | Purpose | -| ------------------------------- | -------------------------------------------------------- | -| `VITE_SURPLUS_VENUE_URL` | Default venue URL. | -| `VITE_TANGLE_ROUTER_URL` | Tangle Router endpoint. | -| `VITE_WALLETCONNECT_PROJECT_ID` | WalletConnect project ID; do not ship a shared fallback. | +| Setting | Use | +| ------------------------- | ---------------------------------------------- | +| `SURPLUS_CHAIN_ID` | Chain ID used in EIP-712 and settlement calls. | +| `SURPLUS_SETTLEMENT_ADDR` | Settlement contract address. | +| `SURPLUS_RPC_URL` | RPC endpoint for settlement submissions. | +| `SURPLUS_OPERATOR_KEY` | Issuer or attester key. | +| `SURPLUS_SUBMITTER_KEY` | Optional separate transaction key. | + +Do not put these in frontend env. They are operator secrets. + +## Shared CLOB and attesters + +For shared books, configure: + +| Setting | Use | +| ------------------------- | ----------------------------------------------------- | +| `SURPLUS_CLOB_OPERATORS` | Peer operator list. | +| `SURPLUS_CLOB_BOOK` | Book identifier. | +| `SURPLUS_CLOB_THRESHOLD` | Attestation threshold. | +| `SURPLUS_ATTESTER_ONLY=1` | Runs a quorum member that attests but does not issue. | + +The CLOB path depends on operator signatures. Peers must prove their operator address by signature recovery before joining the transport. + +## Privacy mode + +Surplus can publish and use onion endpoints through Arti, the Rust Tor implementation. + +| Setting | Use | +| -------------------- | ---------------------------------------------------- | +| `SURPLUS_ONION_URL` | Fixed onion endpoint. | +| `SURPLUS_ONION_FILE` | Path where Arti writes the generated onion hostname. | +| `PRIVACY_MODE=tor` | Route outbound operator calls through Tor. | + +This is Tor, not custom cryptography. The privacy goal is to avoid concentrating a seller's redemptions on the same identifiable operator endpoint. + +## Operator preflight + +Run the repo proof paths before claiming a venue is ready: + +```bash +pnpm -r test +cargo test --workspace +cd contracts && forge test +``` + +For settlement and spend paths, the repo uses: + +```bash +bash scripts/settlement-e2e.sh +bash scripts/spend-e2e.sh +bash scripts/prove-batch.sh execute +``` + +Those prove more than "the server boots." They exercise atomic fill settlement, redemption, collateral default, attested batch settlement, spend billing, and circuit parity. diff --git a/pages/blueprints/surplus-market/settlement-and-inference.mdx b/pages/blueprints/surplus-market/settlement-and-inference.mdx index 7ddb505..1023ea3 100644 --- a/pages/blueprints/surplus-market/settlement-and-inference.mdx +++ b/pages/blueprints/surplus-market/settlement-and-inference.mdx @@ -1,45 +1,90 @@ --- title: Surplus Market Settlement and Inference -description: Settlement, inference backend, and redemption model for the Surplus Market blueprint. +description: Settlement, credit redemption, inference backend, attester quorum, and SP1 proof boundaries for Surplus. --- -# Settlement and Inference +# Surplus Market Settlement and Inference -Surplus is a market for inference credits, so the operator must prove two things: fills settle correctly and credits redeem against real inference capacity. +Surplus only works if a bought credit can be redeemed. -## Inference Backend Selection +The order book can be off-chain. The quote brain can be a sidecar. But the settlement and redemption guarantees have to survive operator mistakes, missing receipts, and issuer default. -The operator uses an OpenAI-compatible chat-completions interface. Backend selection is environment-driven. +## Settlement model -| Priority | Backend | Variables | -| -------- | ---------------------- | -------------------------------------------------------------------------------- | -| 1 | Managed vLLM | `SURPLUS_VLLM_MODEL`, optional `SURPLUS_VLLM_PORT`, optional `SURPLUS_VLLM_ARGS` | -| 2 | External inference API | `SURPLUS_INFERENCE_URL`, optional `SURPLUS_INFERENCE_API_KEY` | -| 3 | Router fallback | `SURPLUS_ROUTER_URL`, `SURPLUS_ROUTER_API_KEY` | +The settlement contract clears signed fills atomically: -Router fallback is for non-bonded testing. A bonded issuer must not use router mode; the operator fails closed because a lot must be backed by inference it runs or controls. +1. debit buyer escrow +2. pay seller +3. mint or update a collateral-backed credit lot +4. enforce redemption/default rules +5. slash or penalize when configured conditions fail -## Settlement Spine +The repo supports three rails in the blueprint manifest: -| Component | Purpose | -| ------------------- | ------------------------------------------------------------------------------- | -| `SurplusSettlement` | Clears signed fills atomically and mints collateral-backed credit lots. | -| Attester quorum | Compresses batch verification through operator signatures. | -| SP1 proof | Optional proof path for batch verification when volume warrants it. | -| Redemption receipt | Lets holders prove delivery or trigger collateral default. | -| `SurplusBSM` | Connects redemption defaults to Tangle slashing on top of settlement penalties. | +| Rail | Meaning | +| ---------------- | -------------------------------------------------------- | +| `router-credits` | Router credit balance path. | +| `shielded` | ShieldedCredits path. | +| `firm` | EIP-712 signed orders settled through SurplusSettlement. | -## Verified Paths +The firm rail is the main settlement spine for signed fills. -The testnet release docs require these checks before and after deploy: +## Attested and proven batches -| Check | What it proves | -| ---------------------------------- | ------------------------------------------------------------------------------------------- | -| `scripts/settlement-e2e.sh` | Atomic fill, receipt redemption, collateral default, attested batch, proven batch. | -| `scripts/spend-e2e.sh` | API-key mint, OpenAI-compatible calls, streaming, on-chain billing, forged voucher refusal. | -| `scripts/prove-batch.sh execute` | SP1 guest public values match host recomputation. | -| `forge test` and Rust parity tests | Contract invariants and digest parity. | +| Path | What it verifies | +| --------------------- | ------------------------------------------------------------------------------ | +| `settleBatchAttested` | A configured attester quorum signs the batch. | +| `settleBatchProven` | An SP1 proof verifies the delegated signature check over the batch commitment. | -## Market-Making Loop +The SP1 program currently proves the delegated signature check and commits to `abi.encode(domainSeparator, fillsHash)`. Matching logic and account rules remain contract-enforced unless a future state-root rollup extends the proof. -The market-making sidecar can run deterministic Avellaneda-Stoikov quoting or a sandboxed agent strategy. The risk desk is fail-closed and validates quote size, inventory, deviation, spread, and drawdown before the operator places quotes. +## Inference backend + +Bonded credit issuance requires an inference backend the operator runs or controls. + +| Backend shape | Use | +| --------------------- | ------------------------------------------------------------------ | +| Managed vLLM | Operator-controlled model service. | +| OpenAI-compatible API | External or internal API with compatible chat-completions surface. | +| Router fallback | Testing or non-bonded operation only. | + +If a lot is bonded, router fallback should fail closed. A credit sold as backed capacity must be redeemable against backed capacity. + +## Market-making loop + +The operator can use a market-making sidecar. The sidecar can run a deterministic Avellaneda-Stoikov quoter or an agentic strategy. Both pass through the same risk gate. + +The risk gate is the safety boundary: + +| Check | Why | +| ----------- | ------------------------------------------------- | +| quote size | Prevents oversized exposure. | +| inventory | Keeps the operator from selling beyond capacity. | +| deviation | Rejects quotes too far from reference price. | +| spread | Avoids broken or inverted markets. | +| drawdown | Pulls quotes when the session is losing too much. | +| kill switch | Stops quoting when hard limits are crossed. | + +The operator places quotes only after the risk verdict allows them. + +## What is proven locally + +The repo's release checklist names these proof paths: + +| Proof | Command | +| -------------------- | ------------------------------------- | +| Trader path | `bash scripts/settlement-e2e.sh` | +| Developer spend path | `bash scripts/spend-e2e.sh` | +| Circuit parity | `bash scripts/prove-batch.sh execute` | + +Those checks cover atomic fill, receipt redemption, collateral default, attested batch settlement, proven batch path, streaming and buffered spend calls, on-chain billing, and forged voucher refusal. + +## What is still a deployment decision + +| Decision | Why it matters | +| ------------------------------ | ------------------------------------------------------------------------ | +| 1-of-1 vs M-of-N books | Changes quorum and peer requirements. | +| Attester set | Decides who can sign settlement batches. | +| SP1 verifier and vkey | Enables or disables the proven path on that deployment. | +| Inference backend | Determines whether bonded credits can actually redeem. | +| Timelock/Gnosis Safe ownership | Controls owner actions such as registering books and rotating attesters. | diff --git a/pages/developers/api/reference/IPaymentAdapterRegistry.mdx b/pages/developers/api/reference/IPaymentAdapterRegistry.mdx index 681b695..ba78995 100644 --- a/pages/developers/api/reference/IPaymentAdapterRegistry.mdx +++ b/pages/developers/api/reference/IPaymentAdapterRegistry.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # IPaymentAdapterRegistry -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### IPaymentAdapterRegistry diff --git a/pages/developers/api/reference/ISablierAdapter.mdx b/pages/developers/api/reference/ISablierAdapter.mdx index 8df737c..84bdcc4 100644 --- a/pages/developers/api/reference/ISablierAdapter.mdx +++ b/pages/developers/api/reference/ISablierAdapter.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # ISablierAdapter -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### ISablierAdapter diff --git a/pages/developers/api/reference/IStreamingPaymentAdapter.mdx b/pages/developers/api/reference/IStreamingPaymentAdapter.mdx index 37a09f1..6fc7bcb 100644 --- a/pages/developers/api/reference/IStreamingPaymentAdapter.mdx +++ b/pages/developers/api/reference/IStreamingPaymentAdapter.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # IStreamingPaymentAdapter -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### IStreamingPaymentAdapter diff --git a/pages/developers/api/reference/ISuperfluidAdapter.mdx b/pages/developers/api/reference/ISuperfluidAdapter.mdx index 3f11783..6458517 100644 --- a/pages/developers/api/reference/ISuperfluidAdapter.mdx +++ b/pages/developers/api/reference/ISuperfluidAdapter.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # ISuperfluidAdapter -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### ISuperfluidAdapter diff --git a/pages/developers/api/reference/generated/IPaymentAdapterRegistry.mdx b/pages/developers/api/reference/generated/IPaymentAdapterRegistry.mdx index 681b695..ba78995 100644 --- a/pages/developers/api/reference/generated/IPaymentAdapterRegistry.mdx +++ b/pages/developers/api/reference/generated/IPaymentAdapterRegistry.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # IPaymentAdapterRegistry -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### IPaymentAdapterRegistry diff --git a/pages/developers/api/reference/generated/ISablierAdapter.mdx b/pages/developers/api/reference/generated/ISablierAdapter.mdx index 8df737c..84bdcc4 100644 --- a/pages/developers/api/reference/generated/ISablierAdapter.mdx +++ b/pages/developers/api/reference/generated/ISablierAdapter.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # ISablierAdapter -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### ISablierAdapter diff --git a/pages/developers/api/reference/generated/IStreamingPaymentAdapter.mdx b/pages/developers/api/reference/generated/IStreamingPaymentAdapter.mdx index 37a09f1..6fc7bcb 100644 --- a/pages/developers/api/reference/generated/IStreamingPaymentAdapter.mdx +++ b/pages/developers/api/reference/generated/IStreamingPaymentAdapter.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # IStreamingPaymentAdapter -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### IStreamingPaymentAdapter diff --git a/pages/developers/api/reference/generated/ISuperfluidAdapter.mdx b/pages/developers/api/reference/generated/ISuperfluidAdapter.mdx index 3f11783..6458517 100644 --- a/pages/developers/api/reference/generated/ISuperfluidAdapter.mdx +++ b/pages/developers/api/reference/generated/ISuperfluidAdapter.mdx @@ -5,7 +5,7 @@ description: Auto-generated Solidity API reference. # ISuperfluidAdapter -Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentAdapter.sol +Source: https://github.com/tangle-network/tnt-core/blob/main/src/interfaces/IStreamingPaymentManager.sol ### ISuperfluidAdapter diff --git a/pages/developers/auth-surface.mdx b/pages/developers/auth-surface.mdx index 9643f08..9e006f7 100644 --- a/pages/developers/auth-surface.mdx +++ b/pages/developers/auth-surface.mdx @@ -40,27 +40,27 @@ Tangle is the protocol entrypoint, composed of mixins under `src/core/`. Every s ### Contract Administration -| Function | Caller | Source | -| -------------------------------------- | ---------------------------------- | ------------------------------------------------------------------------------------------ | -| `pause()` | `PAUSER_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `unpause()` | `PAUSER_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `_authorizeUpgrade(newImpl)` | `UPGRADER_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setMBSMRegistry(addr)` | `ADMIN_ROLE` (when not paused) | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setMetricsRecorder(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setOperatorStatusRegistry(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setServiceFeeDistributor(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setPriceOracle(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setTreasury(addr)` | `ADMIN_ROLE` (NOT `whenNotPaused`) | [Payments.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Payments.sol) | -| `setPaymentSplit(split)` | `ADMIN_ROLE` (NOT `whenNotPaused`) | [Payments.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Payments.sol) | -| `setTntToken(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setRewardVaults(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setMaxBlueprintsPerOperator(n)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setDefaultTntMinExposureBps(bps)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setTntPaymentDiscountBps(bps)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setMinServiceTtl(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setMaxServiceTtl(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setRequestExpiryGracePeriod(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | -| `setMaxQuoteAge(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| Function | Caller | Source | +| -------------------------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------- | +| `pause()` | `PAUSER_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `unpause()` | `PAUSER_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `_authorizeUpgrade(newImpl)` | `UPGRADER_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setMBSMRegistry(addr)` | `ADMIN_ROLE` (when not paused) | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setMetricsRecorder(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setOperatorStatusRegistry(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setServiceFeeDistributor(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setPriceOracle(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setTreasury(addr)` | `ADMIN_ROLE` (NOT `whenNotPaused`) | [PaymentsRewards.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsRewards.sol) | +| `setPaymentSplit(split)` | `ADMIN_ROLE` (NOT `whenNotPaused`) | [PaymentsRewards.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsRewards.sol) | +| `setTntToken(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setRewardVaults(addr)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setMaxBlueprintsPerOperator(n)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setDefaultTntMinExposureBps(bps)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setTntPaymentDiscountBps(bps)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setMinServiceTtl(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setMaxServiceTtl(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setRequestExpiryGracePeriod(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | +| `setMaxQuoteAge(seconds)` | `ADMIN_ROLE` | [Base.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Base.sol) | Most admin setters in `Base.sol` are `whenNotPaused`. The two exceptions, both in `Payments.sol`, are `setTreasury` and `setPaymentSplit`. Paused governance can still rewire payment routing; this is intentional so a halted protocol can fix a known-bad treasury before resuming. diff --git a/pages/developers/system-architecture/rewards.mdx b/pages/developers/system-architecture/rewards.mdx index a178e56..9211707 100644 --- a/pages/developers/system-architecture/rewards.mdx +++ b/pages/developers/system-architecture/rewards.mdx @@ -15,18 +15,18 @@ Tangle separates **service fees** (paid by customers) from **incentives** (TNT b alt="Incentives flow for service fees and TNT budgets" />
- Service fees split through Payments.sol; TNT budgets flow through InflationPool, - RewardVaults, and ServiceFeeDistributor. + Service fees split through PaymentsDistribution.sol; TNT budgets flow through + InflationPool, RewardVaults, and ServiceFeeDistributor.
Claim paths: staker fees + staker inflation via `ServiceFeeDistributor`, TNT staking incentives via `RewardVaults`, and operator/customer/developer TNT via `InflationPool`. -Code references: [Payments.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Payments.sol), [ServiceFeeDistributor.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/ServiceFeeDistributor.sol), [InflationPool.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/InflationPool.sol), [RewardVaults.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/RewardVaults.sol), [TangleMetrics.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/TangleMetrics.sol) +Code references: [PaymentsDistribution.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsDistribution.sol), [PaymentsRewards.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsRewards.sol), [ServiceFeeDistributor.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/ServiceFeeDistributor.sol), [InflationPool.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/InflationPool.sol), [RewardVaults.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/RewardVaults.sol), [TangleMetrics.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/TangleMetrics.sol) ## Service Fee Split (Developer / Protocol / Operator / Stakers) -When a service pays a fee, `Payments.sol` calculates and routes the split: +When a service pays a fee, `PaymentsDistribution.sol` calculates and routes the split: - Developer payment (blueprint owner or manager override) - Protocol payment (treasury) @@ -34,10 +34,10 @@ When a service pays a fee, `Payments.sol` calculates and routes the split: - Staker share (via `ServiceFeeDistributor`, when configured) ## Staker Distribution (USD-weighted) diff --git a/pages/network/incentives-developers.mdx b/pages/network/incentives-developers.mdx index 5bfd9b0..287b957 100644 --- a/pages/network/incentives-developers.mdx +++ b/pages/network/incentives-developers.mdx @@ -19,7 +19,7 @@ If the protocol is running `InflationPool` incentives, developers can earn addit - `InflationPool`: https://github.com/tangle-network/tnt-core/blob/main/src/rewards/InflationPool.sol - `TangleMetrics`: https://github.com/tangle-network/tnt-core/blob/main/src/rewards/TangleMetrics.sol -- `Payments` (fee split + payouts): https://github.com/tangle-network/tnt-core/blob/main/src/core/Payments.sol +- `PaymentsDistribution` (fee split + payouts): https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsDistribution.sol For a readable breakdown and links to contracts, see [Rewards Architecture](/developers/system-architecture/rewards). diff --git a/pages/network/incentives-overview.mdx b/pages/network/incentives-overview.mdx index bf8f40e..6c02b71 100644 --- a/pages/network/incentives-overview.mdx +++ b/pages/network/incentives-overview.mdx @@ -11,14 +11,14 @@ Tangle’s incentives come from two sources: alt="Incentives flow for service fees and TNT budgets" />
- Service fees split through Payments.sol; TNT budgets flow through InflationPool, - RewardVaults, and ServiceFeeDistributor. + Service fees split through PaymentsDistribution.sol; TNT budgets flow through + InflationPool, RewardVaults, and ServiceFeeDistributor.
Claim paths: staker fees + staker inflation via `ServiceFeeDistributor`, TNT staking incentives via `RewardVaults`, and operator/customer/developer TNT via `InflationPool`. -Code references: [Payments.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/Payments.sol), [ServiceFeeDistributor.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/ServiceFeeDistributor.sol), [InflationPool.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/InflationPool.sol), [RewardVaults.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/RewardVaults.sol), [TangleMetrics.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/TangleMetrics.sol) +Code references: [PaymentsDistribution.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsDistribution.sol), [PaymentsRewards.sol](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsRewards.sol), [ServiceFeeDistributor.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/ServiceFeeDistributor.sol), [InflationPool.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/InflationPool.sol), [RewardVaults.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/RewardVaults.sol), [TangleMetrics.sol](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/TangleMetrics.sol) ## Service Fees @@ -60,7 +60,8 @@ The protocol can optionally record activity into a metrics contract (`TangleMetr ## Source Contracts (GitHub) -- [`Payments.sol`](https://github.com/tangle-network/tnt-core/blob/main/src/core/Payments.sol) +- [`PaymentsDistribution.sol`](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsDistribution.sol) +- [`PaymentsRewards.sol`](https://github.com/tangle-network/tnt-core/blob/main/src/core/PaymentsRewards.sol) - [`ServiceFeeDistributor.sol`](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/ServiceFeeDistributor.sol) - [`InflationPool.sol`](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/InflationPool.sol) - [`RewardVaults.sol`](https://github.com/tangle-network/tnt-core/blob/main/src/rewards/RewardVaults.sol)