From 77a2456a63b3eebcc53573839c13127c7cbfb697 Mon Sep 17 00:00:00 2001 From: Eras256 <219895655+Eras256@users.noreply.github.com> Date: Wed, 2 Dec 2026 22:05:30 -0600 Subject: [PATCH 1/2] sync: site and README from core at 7a08a40 Brings the public copy of apps/web and the README up to date with the private source (last sync was 25 Nov 2026). - Site: link previews refreshed, /chains added, Treasury and Payouts pages replaced by the archive page (both were tested only with the team's own funds and discontinued on 30 Nov 2026), SCF removed from the site, the Codigo 402 and treasury-node blog posts removed. - README: current state, Treasury and Payouts mentioned once, closed routes listed, package versions re-checked on 2 Dec 2026. - pnpm-lock.yaml regenerated in this tree for nirium-pollar-adapter ^0.7.0. Only apps/web, README.md and the lockfile change. Packages, contracts and workflows are untouched. Co-Authored-By: Claude Opus 5.5 --- README.md | 346 +- apps/web/app/(app)/agents/layout.tsx | 4 +- apps/web/app/(app)/agents/page.tsx | 131 +- apps/web/app/(app)/analytics/layout.tsx | 4 +- apps/web/app/(app)/analytics/page.tsx | 178 +- .../(app)/blog/bbva-open-deal-room/layout.tsx | 2 +- .../codigo-402-agentes-que-pagan/layout.tsx | 12 - .../codigo-402-agentes-que-pagan/page.tsx | 261 -- apps/web/app/(app)/blog/page.tsx | 2 +- apps/web/app/(app)/blog/posts.ts | 12 +- .../layout.tsx | 15 - .../treasury-node-verify-it-yourself/page.tsx | 226 -- apps/web/app/(app)/build/layout.tsx | 2 +- apps/web/app/(app)/build/page.tsx | 54 +- apps/web/app/(app)/chains/layout.tsx | 11 + apps/web/app/(app)/chains/page.tsx | 395 ++ apps/web/app/(app)/coc/page.tsx | 28 +- apps/web/app/(app)/compliance/page.tsx | 6 +- apps/web/app/(app)/dashboard/layout.tsx | 2 +- apps/web/app/(app)/dashboard/page.tsx | 3358 +---------------- apps/web/app/(app)/developers/layout.tsx | 2 +- apps/web/app/(app)/developers/page.tsx | 111 +- apps/web/app/(app)/disclaimers/page.tsx | 65 +- apps/web/app/(app)/docs/page.tsx | 70 +- apps/web/app/(app)/how-to-use/layout.tsx | 2 +- apps/web/app/(app)/keys/layout.tsx | 2 +- apps/web/app/(app)/keys/page.tsx | 4 +- apps/web/app/(app)/manifesto/layout.tsx | 2 +- apps/web/app/(app)/payouts/layout.tsx | 4 +- apps/web/app/(app)/payouts/page.tsx | 478 +-- .../pollar-adapter-documentation/page.tsx | 11 +- apps/web/app/(app)/pricing/page.tsx | 95 +- apps/web/app/(app)/privacy/page.tsx | 42 +- apps/web/app/(app)/ramp/page.tsx | 62 +- apps/web/app/(app)/risk-disclosure/layout.tsx | 2 +- apps/web/app/(app)/risk-disclosure/page.tsx | 4 +- apps/web/app/(app)/security/layout.tsx | 2 +- apps/web/app/(app)/security/page.tsx | 345 +- apps/web/app/(app)/stats/StatsClient.tsx | 58 +- .../app/(app)/treasury/builder/CustomNode.tsx | 90 - .../web/app/(app)/treasury/builder/layout.tsx | 4 +- apps/web/app/(app)/treasury/builder/page.tsx | 886 +---- apps/web/app/(app)/treasury/layout.tsx | 4 +- apps/web/app/(app)/treasury/page.tsx | 337 +- apps/web/app/(app)/treasury/vault/layout.tsx | 4 +- apps/web/app/(app)/treasury/vault/page.tsx | 109 +- apps/web/app/(app)/verify/page.tsx | 248 +- apps/web/app/api/chain-stats/route.ts | 59 + apps/web/app/api/reporting-summary/route.ts | 5 +- apps/web/app/api/stats/statsData.ts | 29 +- apps/web/app/blocked/page.tsx | 4 +- apps/web/app/build/niriumtober/page.tsx | 76 +- apps/web/app/globals.css | 12 +- apps/web/app/layout.tsx | 18 +- apps/web/app/page.tsx | 206 +- apps/web/app/sitemap.ts | 8 +- .../web/components/analytics/NodeActivity.tsx | 88 +- .../analytics/ReceiptsSettlements.tsx | 9 +- .../web/components/dashboard/MarketTicker.tsx | 255 -- .../components/home/BuiltWithEcosystem.tsx | 50 +- apps/web/components/home/HeroSeal.tsx | 191 + apps/web/components/home/SocialProof.tsx | 4 +- .../components/home/TreasuryPlainTerms.tsx | 21 +- apps/web/components/layout/AppLayout.tsx | 36 +- apps/web/components/layout/Footer.tsx | 152 +- apps/web/components/layout/Navbar.tsx | 91 +- apps/web/components/layout/OpsConsole.tsx | 54 +- apps/web/components/layout/TestnetBanner.tsx | 10 +- apps/web/components/legal/LegalDisclaimer.tsx | 8 +- .../components/shared/NetworkSwitchModal.tsx | 56 +- .../components/shared/SecurityDisclaimer.tsx | 13 +- apps/web/components/ui/ChatBot.tsx | 71 +- apps/web/components/ui/ComplianceBanner.tsx | 3 +- apps/web/dictionaries/en.json | 253 +- apps/web/dictionaries/es.json | 249 +- apps/web/lib/og/sections.ts | 125 +- apps/web/lib/statsEs.ts | 4 +- apps/web/middleware.ts | 14 + apps/web/package.json | 2 +- apps/web/public/legal/payouts-terms-v1.md | 14 +- .../legal/restricted-jurisdictions-v1.md | 45 +- apps/web/public/llms.txt | 12 +- apps/web/public/nirium-api.yaml | 1509 -------- apps/web/vercel.json | 100 +- pnpm-lock.yaml | 10 +- 85 files changed, 2205 insertions(+), 9753 deletions(-) delete mode 100644 apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/layout.tsx delete mode 100644 apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/page.tsx delete mode 100644 apps/web/app/(app)/blog/treasury-node-verify-it-yourself/layout.tsx delete mode 100644 apps/web/app/(app)/blog/treasury-node-verify-it-yourself/page.tsx create mode 100644 apps/web/app/(app)/chains/layout.tsx create mode 100755 apps/web/app/(app)/chains/page.tsx delete mode 100644 apps/web/app/(app)/treasury/builder/CustomNode.tsx create mode 100755 apps/web/app/api/chain-stats/route.ts delete mode 100644 apps/web/components/dashboard/MarketTicker.tsx create mode 100755 apps/web/components/home/HeroSeal.tsx delete mode 100644 apps/web/public/nirium-api.yaml diff --git a/README.md b/README.md index 58851f27..352eb09f 100644 --- a/README.md +++ b/README.md @@ -3,44 +3,43 @@ [![CI](https://github.com/nirium-protocol/nirium-core/actions/workflows/ci.yml/badge.svg)](https://github.com/nirium-protocol/nirium-core/actions/workflows/ci.yml) [![Security Gate](https://github.com/nirium-protocol/nirium-core/actions/workflows/security-gate.yml/badge.svg)](https://github.com/nirium-protocol/nirium-core/actions/workflows/security-gate.yml) -Payment rails, audit and execution on Stellar. +Money moves because of a document that can change. Nirium records the version it moved on, signed by whoever declares it, so anyone can check which one it was: Audit Trail, Reporting and x402 payments, live on Stellar mainnet. -This is the full Nirium monorepo: the Soroban contracts, the nirium.xyz web app, the fuzz targets and copies of the client packages. The packages published to npm and PyPI (SDKs, CLI, MCP server) are developed and released from [nirium-protocol/nirium](https://github.com/nirium-protocol/nirium); the copies under `packages/` here can trail those releases. The source-verified NiriumVault build on Stellar Expert points to this repository. +This is the Nirium monorepo: the Soroban contracts, the nirium.xyz web app, the fuzz targets and copies of the client packages. The packages published to npm and PyPI (TypeScript and Python packages, CLI, MCP server) are developed and released from [nirium-protocol/nirium](https://github.com/nirium-protocol/nirium); the copies under `packages/` here can trail those releases. The source-verified NiriumVault build on Stellar Expert points to this repository. + +Nirium also runs on other chains, each in its own repo: [nirium-solana](https://github.com/nirium-protocol/nirium-solana) and [nirium-avalanche](https://github.com/nirium-protocol/nirium-avalanche), with first versions on Base and Arbitrum. See [nirium.xyz/chains](https://nirium.xyz/chains). **Reviewing Nirium?** [`FOR-REVIEWERS.md`](https://github.com/nirium-protocol/nirium/blob/main/docs/FOR-REVIEWERS.md) is a ten-minute path through things you can check yourself, and every piece of evidence, with its network and date, is in [`EVIDENCE.md`](https://github.com/nirium-protocol/nirium/blob/main/EVIDENCE.md). Verify any receipt with no account at [nirium.xyz/verify](https://nirium.xyz/verify). --- -> **⚠️ MANDATORY LEGAL DISCLAIMER** +> **⚠️ LEGAL DISCLAIMER** > -> Nirium is **experimental software**. Nirium's own **NiriumVault** treasury contract remains on **Stellar Testnet, audit-gated**: no independent third-party audit has occurred yet, and no real client funds ever reach that contract. +> Nirium is **experimental software**. Nirium's own **NiriumVault** contract remains on **Stellar Testnet, audit-gated**: no independent third-party audit has occurred yet, and no real client funds ever reach it. > -> The **autonomous treasury node runs on mainnet over a DeFindex vault the client owns**: a third-party contract audited by OtterSec, not ours. Nirium holds only the vault's `RebalanceManager` role, which by the contract's own design cannot withdraw funds, change roles, or pause anything. Autonomous rebalancing on mainnet is **invite-only** until we have a written legal opinion. A separate set of receive-only nodes (x402 micropayments, IPFS audit anchoring, non-custodial Payouts, Reporting) also run in **mainnet early access**; several move real USDC under the client's own wallet signature - see the evidence table below for which ones. **MPP Charge is testnet-only and experimental**: verified with settled payments on testnet (15 Oct 2026), but it has never settled on mainnet - see the evidence table's MPP row for the exact status. **Nirium never custodies funds.** +> On mainnet, Nirium runs receive-only nodes: x402 micropayments, IPFS audit anchoring and Reporting. The mainnet API box holds **no signing key**; the client signs every payment. **MPP Charge is experimental**: verified with settled payments on testnet (15 Oct 2026), never settled on mainnet. **Nirium never custodies funds.** > -> **Update, 2026-10-08 (checked against the live `/api/tickers` on both networks that day):** until today the site, the API and the docs showed a CETES rate of 5.57% under labels such as "Banxico ref", "Today" and, on one dashboard card, "LIVE". It was a fixed reference value read once from app.etherfuse.com/b/cetes in June 2026, not a live reading and not from Banxico. The labels are corrected; the value itself is unchanged and still not live. The same release stops publishing `1 / xlmPrice` as the USDC price in `/api/tickers`: that figure (about 5.25) was how many XLM one dollar buys, and is now `null`. +> Treasury and Payouts were tested only with the team's own funds and discontinued on 30 Nov 2026. > -> **Nirium is not financial advice. It is not an investment product. It does not guarantee yields, dividends, asset appreciation, or returns of any kind.** Reference rate data shown on the dashboard (Blend supply rate, Etherfuse CETES rate) is **public protocol information only**, not projections or promises of return. XLM and Stellar assets are volatile. Smart contracts carry risk even when audited. Use at your own risk. +> **Nirium is not financial advice. It is not an investment product. It does not guarantee yields, dividends, asset appreciation, or returns of any kind.** Reference rate data shown on the site is **public protocol information only**. XLM and Stellar assets are volatile. Smart contracts carry risk even when audited. Use at your own risk. > > This project does not use grant funds for speculation, trading, investment advice, or marketing of products promising interest or appreciation, in accordance with the [Stellar Community Fund Official Rules](https://stellar.gitbook.io/scf-handbook/scf-awards/official-rules-for-submissions). --- -**Nirium is software, not a financial service**: autonomous treasury and agentic payments (x402; MPP experimental) on Stellar/Soroban, for B2B fintechs and developers rather than consumers. - -**The product is the rail, not the data.** A 102-endpoint API and TypeScript/Python SDKs that let a fintech both *pay* for machine-to-machine services and *charge* for its own, plus execution nodes that run treasury operations on their own, inside limits the client sets and can revoke. +**Nirium is software, not a financial service**, for fintechs, developers and AI agents rather than consumers. -### Execution Nodes +### Nodes | # | Node | Status | Network | What it does | |---|---|---|---|---| -| 1 | **Settlement** (x402 active; MPP Charge experimental) | x402 ✅ Active · MPP ⚠️ Experimental | both | Per-request micropayments for AI agents. Pay for others' APIs with `initX402()` today - x402 has confirmed mainnet settlements (see the evidence table below). MPP Charge is implemented but experimental: verified on testnet on 15 Oct 2026 with settled payments in pull and push mode (it had rejected a valid payment on 1 Oct); mainnet is unverified. **Update, 2026-10-07:** this previously said charging for your own with `x402Serve()` was invite-only, same gate as Treasury and Payouts - there is no such gate. `x402Serve()` is a general-purpose library that runs on the integrator's own server; Nirium does not operate or gate it. Third-party use is an open legal question, with no written legal opinion yet - compliance is the integrator's own responsibility. | -| 2 | **Audit Trail** | ✅ Active | both | Evidence anchored to IPFS as tamper-evident receipts (a changed document no longer matches its CID), optionally **signed by the agent that produced it** (ed25519 over a domain-separated statement), so the CID proves not just *that* a fact is unaltered but *who declared it*. | -| 3 | **Payouts** | ✅ Active (mainnet invite-only) | both | Non-custodial batch disbursements, up to 100 recipients per transaction. Mainnet is invite-only; independent service payments only (contractors, freelancers, B2B); never subordinate-employee salary. A milestone variant (Trustless Work Multi-Release - one contract, a distinct receiver per milestone) runs on testnet: `GET /api/payroll/escrow/info`. | -| 4 | **Treasury Rebalance** | ✅ Active (mainnet invite-only) | both | Moves idle capital into a CETES strategy and back, on its own, over a **DeFindex vault the client owns**. Live on mainnet, invite-only until a written legal opinion. | -| 5 | **Reporting** | ✅ Active | both | Institutional-format summaries and CSV/JSON exports over anchored receipts. Read-only; regulatory filings remain the client's responsibility. | -| 6 | **Policy Gate** | ✅ Active | both | Routes every outgoing x402 payment through your own policy engine before it is signed (`initX402({ policy })`, #96). Binds the decision to the exact authorization; a deny, timeout, or stale answer signs nothing. Not a remote key-custody control - it wraps the signing call inside the same process that holds the key, so direct access to that signer bypasses it. See the roadmap for a stronger, not-yet-designed alternative. | +| 1 | **Settlement** (x402; MPP Charge experimental) | x402 ✅ Active · MPP ⚠️ Experimental | both | Per-request micropayments for AI agents. Pay for others' APIs with `initX402()`, charge for your own with `x402Serve()`. `x402Serve()` is a library that runs on the integrator's own server; Nirium does not operate or gate it, and compliance is the integrator's own responsibility. | +| 2 | **Audit Trail** | ✅ Active | both | Evidence anchored to IPFS as tamper-evident receipts (a changed document no longer matches its CID), optionally **signed by whoever declares it** (ed25519 over a domain-separated statement). A receipt is worth what the ledger doesn't hold: what a payment was for, payments a policy refused, off-chain records. | +| 3 | **Reporting** | ✅ Active | both | Summaries and CSV/JSON exports over anchored receipts. Read-only; regulatory filings remain the client's responsibility. | +| 4 | **Policy Gate** | ✅ Active | both | Routes every outgoing x402 payment through your own policy engine before it is signed (`initX402({ policy })`). A deny, timeout or stale answer signs nothing. It wraps the signing call inside the same process that holds the key, so direct access to that signer bypasses it. | +| - | Treasury Rebalance, Payouts | Discontinued 30 Nov 2026 | - | Tested only with the team's own funds. Code archived, not deleted; the node answers `410`. | -The framework supports up to 10 nodes per vault. Live catalog: `GET /api/nodes`. +Live catalog: `GET /api/nodes`. --- @@ -48,21 +47,18 @@ The framework supports up to 10 nodes per vault. Live catalog: `GET /api/nodes`. Every claim below is a link. Nothing here asks to be believed. -Who holds what. Your keys stay on your side: you sign every payment and every vault deposit or withdrawal. The mainnet API box holds no signing key, and receipts are hashes on IPFS that anyone can check. - ```mermaid flowchart TB subgraph YOU["Your side: your keys"] - APP["Your app, backend or AI agent
nirium SDK, CLI or MCP"] + APP["Your app, backend or AI agent
nirium package, CLI or MCP"] KEY["Your key or wallet
(Stellar keypair, SEP-43, Pollar)"] - VAULT["Your Treasury vault
client-owned, DeFindex"] end subgraph NIRIUM["Nirium: no client funds"] API["Agent API on Fly
mainnet box is receive-only,
holds no signing key"] WEB["nirium.xyz
/verify, /stats"] end FAC["x402 facilitator
independent: OpenZeppelin"] - STELLAR[("Stellar
USDC payments, Soroban")] + STELLAR[("Stellar
USDC payments")] IPFS[("IPFS
receipt hashes")] KEY -- "signs every payment" --> APP APP -- "x402 payment" --> FAC @@ -70,25 +66,20 @@ flowchart TB APP -- "anchor a receipt hash" --> API API -- "pins" --> IPFS WEB -- "anyone verifies a CID" --> IPFS - KEY -- "deposits and withdraws, you sign" --> VAULT - API -. "proposes a rebalance,
you sign (mainnet: invite-only)" .-> VAULT - VAULT --- STELLAR ``` - ### Status at a glance | Product | Status | |---|---| | x402 | Live on mainnet ([last settled payment 24 Nov 2026, our own test](https://stellar.expert/explorer/public/account/GCLBBPON256CV7ATEHM5B54BOKNC7GX53MBINJ42MHVXGDMMZ3ZWKBHP)) | -| Audit Trail | Live on mainnet (last anchor 24 Nov 2026) | +| Audit Trail | Live on mainnet (44 anchors, the last on 25 Nov 2026, our own notice) | | Reporting | Live on mainnet | -| Treasury Rebalance | Mainnet, invite-only (4 self-funded rebalances, last 6 Aug 2026) | -| Payouts | Mainnet, invite-only (no mainnet runs yet) | -| Policy hook (pre-sign `ALLOW`/`DENY`) | Experimental (TypeScript SDK; Python SDK since 0.12.9) | -| MPP Charge | Testnet only | +| Policy hook (pre-sign `ALLOW`/`DENY`) | Experimental (TypeScript package; Python since 0.12.9) | +| MPP Charge | Testnet only (the client fails on `nirium` 0.20.0 and 0.21.0; use 0.19.8) | +| Treasury and Payouts | Tested only with the team's own funds and discontinued on 30 Nov 2026 | -The detailed tables below back each row with a transaction hash or a live endpoint - this one is just the summary. Statuses checked against Horizon and the live API on 22 Nov 2026. +The tables below back each row with a transaction hash or a live endpoint. Statuses checked against Horizon and the live API on 28 Nov 2026; Treasury, Payouts and the closed endpoints re-checked on 2 Dec 2026. ### Mainnet (real value) @@ -100,30 +91,21 @@ The detailed tables below back each row with a transaction hash or a live endpoi | x402: paid from a social login (Pollar) | Settled 5 Aug 2026, holding **zero XLM** end to end | [`e4fa3df9…16ed9`](https://stellar.expert/explorer/public/tx/e4fa3df9cb225a4d7f64dd0082eb38218ada4b4af3378f288989a5d4b1116ed9) | | `nirium-pollar-adapter`: end-to-end from a clean npm install | Settled 27 Jul 2026, standard Stellar keypair signer (the pluggable-signer test, not Pollar-specific) | [`48136451…3795e`](https://stellar.expert/explorer/public/tx/4813645165d15af1e503d66ef84d826e83fff235d4f98c3f6eba8a4e7c83795e) · receipt [`QmRzgTtVPg…`](https://gateway.pinata.cloud/ipfs/QmRzgTtVPg5a5pipi8npfpXt81xiGG5Ue5Rygd6Fye1aon) · **Update, 2026-10-07:** the receipt above no longer resolves on the Pinata gateway (404 on two checks). The original bytes are not kept in this repo, so it was not re-pinned under the same CID. The payment itself is verifiable on Stellar Expert. **Update, 2026-11-10:** the receipt resolves again - 200 on both the Pinata gateway and `nirium.myfilebase.com`. | | MPP Charge | **Experimental**: implemented, `charge.enabled: true` on both networks; **testnet verified 2026-10-15** with settled payments in pull and push mode ([`b8c4ed56…`](https://stellar.expert/explorer/testnet/tx/b8c4ed568f6eb41321b97d251d7f3727c57570a226d187e3675a9df03496e3ed), [`96d43d6f…`](https://stellar.expert/explorer/testnet/tx/96d43d6f4cf38fbd3a4df2c2bb6625e650c0d0509184d86c1e42c7e6ebdf242c)); mainnet unverified, no confirmed mainnet settlement (**Update, 2026-10-07, checked live against Horizon and `/api/v1/mpp/info`:** this row previously read "Live: `market` charges and delivers" without a transaction hash, unlike every other row in this table. A 2026-10-01 end-to-end test found the testnet box rejecting real payment proofs with `verification-failed`, including a push flow where the payment settled on-chain but the content was never delivered; the root cause was not determined. No MPP Charge-tagged credit appears anywhere in the mainnet recipient's payment history, past or since. **Update, 2026-10-15:** re-tested with `nirium@0.16.1` against the testnet box: `pull` and `push` both settled and delivered, so the 1 Oct failure no longer reproduces. Mainnet is still untested.) | [`/api/v1/mpp/info`](https://nirium-agent-mainnet.fly.dev/api/v1/mpp/info) | -| Treasury: vault deployed | 6 Aug 2026, **client signs** | [`93ff6284…78416`](https://stellar.expert/explorer/public/tx/93ff6284cdf03706624c88434a79fba1b213ee547f58e09a9248f75373178416) | -| Treasury: autonomous invest | 6 Aug 2026, **the agent signs** | [`82d73f53…6b3d4`](https://stellar.expert/explorer/public/tx/82d73f537e907140367f9343f63a36704c74a5286aced7a938cee8fffb56b3d4) | -| Treasury: the vault itself | Client-owned, roles readable on-chain | [`CAMDXG6L…K57MH`](https://stellar.expert/explorer/public/contract/CAMDXG6L4LXLXXV675KZSHM3BMSETZ4NVMC7JYIQCZ2JTG54OMSK57MH) | -| Payouts | Live, **invite-only** (tier-gated + terms acceptance); no mainnet payout runs yet | [`/api/payroll/info`](https://nirium-agent-mainnet.fly.dev/api/payroll/info) | -| Trustless Work escrow: deploy path timing, 3 Sep 2026 | Real deploys, self-owned wallets only - **not** the milestone fast-signer below, which stays testnet-only | [`65568e79…f2f3d6e`](https://stellar.expert/explorer/public/tx/65568e79ef61f78e153156158983ab4cdb5325d0813fc1e8bf9f28b74f2f3d6e) (Horizon direct) · [`7d5690cf…02e4b9e6`](https://stellar.expert/explorer/public/tx/7d5690cf431cd32ac4e28780f57c9291ac0a10d670186b9f6ccf495602e4b9e6) (via Trustless Work's own relay) | -| Trustless Work escrow: full cycle, 3 Sep 2026 | deploy → fund → approve → release, real 0.50 USDC, **self-directed** (one key, every role, no third-party client). Proves the mechanism - not a decision to open this flow to Payouts production, which waits on a written legal opinion | [`4110dd16…12aefe84`](https://stellar.expert/explorer/public/tx/4110dd16df6c7cdaf50d89f7402e3e51de0ac4f63255f6601e800e3912aefe84) → [`7b181a13…451c09c`](https://stellar.expert/explorer/public/tx/7b181a13160d6d7170f78ba9a4e15309cc0a8f6e20a1db01adfcdb667451c09c) → [`a3aa35a2…4096ca5`](https://stellar.expert/explorer/public/tx/a3aa35a272774547d3ca4ce5a32e361641daac6cf829ecf8951b83a194096ca5) → [`0c533088…a8192b`](https://stellar.expert/explorer/public/tx/0c533088ab6326a78b9f79c197b7636ca4662a0d72562968ddea37f370a8192b) - receiver balance moved by exactly 0.4985 USDC, 0.50 minus Trustless Work's fixed 0.3% fee | | Audit + Reporting | Live | [`/api/audit/info`](https://nirium-agent-mainnet.fly.dev/api/audit/info) · [`/api/reporting/info`](https://nirium-agent-mainnet.fly.dev/api/reporting/info) | -| Autonomous rebalancing | **Invite-only** until we have a written legal opinion | enabling a vault takes a commit to this repo, with author and date | -| **NiriumVault (our own contract)** | ❌ **Not on mainnet**: audit-gated | n/a | | **MPP Channel mode** | ❌ **Not on mainnet**: deposit contract = temporary custody, same audit gate | [`channel.enabled: false`](https://nirium-agent-mainnet.fly.dev/api/v1/mpp/info) | | **LCP legal layer** | ❌ Off: terms pending a written legal opinion | n/a | -### Testnet (no real value, where the loop and the key live) +The transactions from the Treasury tests stay public in [EVIDENCE.md section 7](https://github.com/nirium-protocol/nirium/blob/main/EVIDENCE.md). + +### Testnet (no real value) | What | Status | Verify | |---|---|---| -| API box | Live, full autonomous loop, agent holds a key | [`/health`](https://nirium-agent.fly.dev/health) · [`/api/loop/status`](https://nirium-agent.fly.dev/api/loop/status) | +| API box | Live | [`/health`](https://nirium-agent.fly.dev/health) · [`/api/nodes`](https://nirium-agent.fly.dev/api/nodes) | | NiriumVault | Live, source-verified on Stellar Expert (9 Nov 2026): treasury, delegation, flash loans, emergency pause (2-of-3 once cosigners are registered; none yet) | [`CDMFURE6…QOI2S2`](https://stellar.expert/explorer/testnet/contract/CDMFURE6MYROTA2A6DLD4TN2S4QTN64L2FZ2I2RY2AREONX6DUQOI2S2) | | NiriumProtocol | Testnet, deployed 25 Oct 2026: no agents or strategies registered yet (checked 17 Nov 2026) | [`CBKCTMTC…CNSXX`](https://stellar.expert/explorer/testnet/contract/CBKCTMTCCZQIPEESLHHEZKXYSPWNO24NEG33T2XSAAAHPISBND5CNSXX) | | Policy Account | Live: one `CallContract` rule, **no** `Default` rule | [`CCZW2WIF…B5LML`](https://stellar.expert/explorer/testnet/contract/CCZW2WIFAD7OQX35U5AILTNF32TCHQUYVPNB32GGKEKKPII2HF7B5LML) | -| Treasury: full cycle, 5 Aug 2026 | deploy → deposit → autonomous invest | [`a96eec81…a2662`](https://stellar.expert/explorer/testnet/tx/a96eec81347731ced1505cd20be7bbc92d66fbc88c8e12e5376d685ff82a2662) → [`2c4df5a8…2c3b7`](https://stellar.expert/explorer/testnet/tx/2c4df5a85de8357c1f4868ddbb88aa123db04fc80967291fe3f06e9a9332c3b7) → [`c53d4746…52ed3`](https://stellar.expert/explorer/testnet/tx/c53d474658898af7ebbb84d17845902572147cfe1fb72965833e3d4cf7552ed3) | -| Trustless Work escrow: full cycle, 2 Sep 2026 | deploy (human) → allowlist gate confirmed blocking, then permitting → approve + release milestone, both **agent-signed** | [`8c89ede2…5921f13`](https://stellar.expert/explorer/testnet/tx/8c89ede21a7b2246c2d0bef3d7ee0a4e7218f7ec7a07b2b3d3cc150d05921f13) | -| Autonomous rebalancing | Live and open: this is the demonstration | [`/api/loop/status`](https://nirium-agent.fly.dev/api/loop/status) | -| x402 `signals` / `execute` | Live and paid: the loop and the key exist here | [`/api/v1/premium/signals`](https://nirium-agent.fly.dev/api/v1/premium/signals) → `402` | +| x402 `market` | Live and paid | [`/api/v1/premium/market`](https://nirium-agent.fly.dev/api/v1/premium/market) → `402` | ### Signed audit evidence (anyone can verify with only the CID) @@ -134,42 +116,6 @@ Each document carries an ed25519 signature over `nirium-audit-v1: **The two networks are not two copies of the same thing.** Testnet is where the agent holds a key and rebalances on demand. That is the demonstration. Mainnet is where real value moves, and there the API box holds **no key at all**: a separate process with no HTTP surface signs the rebalances, and every fund movement a client makes is signed by the client. Never quote a testnet figure as if it were mainnet: deploying a vault costs ~0.038 XLM on testnet and ~1.4 XLM on mainnet, 47× more. - ---- - -## The Treasury Node: how an agent moves someone else's money without being able to take it - -This is the part that took the longest to get right, and it is worth stating precisely because the safety does not come from our promises. - -The client deploys a **DeFindex vault** (a third-party Soroban contract) with their own signature. That vault has four roles: - -| Role | Held by | Can do | -|---|---|---| -| Manager | **the client** | everything: pause, rescue, change roles | -| Emergency Manager | **the client** | emergency stop | -| Fee Receiver | **the client** | collect the vault fee (we set it to 0) | -| **RebalanceManager** | **Nirium** | `rebalance()` and nothing else | - -`rebalance()` accepts four instructions: `Invest`, `Unwind`, `SwapExactIn`, `SwapExactOut`. **None of them takes a destination address**: `to` is hardcoded to the vault itself in every branch. Withdrawal is not *forbidden*, it is **inexpressible**. This was verified by reading DeFindex's source (not its docs) and confirmed by submitting real transactions: Soroban's simulator *records* `require_auth()` without verifying signatures, so simulating gives a false pass. - -The client can call `set_rebalance_manager` and remove us unilaterally, without notice, and we cannot stop them. - -**Verified on mainnet, with real funds:** - -| Step | Who signs | Transaction | -|---|---|---| -| Deploy vault | the client | [`93ff6284…78416`](https://stellar.expert/explorer/public/tx/93ff6284cdf03706624c88434a79fba1b213ee547f58e09a9248f75373178416) | -| Invest into strategy | **the agent** | [`82d73f53…6b3d4`](https://stellar.expert/explorer/public/tx/82d73f537e907140367f9343f63a36704c74a5286aced7a938cee8fffb56b3d4) | - -That second transaction is the whole argument turned into evidence: the agent moved someone else's funds, and the contract gave it no way to take them out. - -**Audit scope, stated honestly:** the vault is DeFindex, audited by OtterSec (March 2025, 16 findings total - 13 of them vulnerabilities, all resolved; the other 3 were non-vulnerability suggestions), running a Blend V2 strategy (3 independent audits). The deployed WASM matches the public 1.0.0 release. What is *not* covered is the Etherfuse pool as an external dependency and each instance's configuration. **Fees:** Nirium takes no percentage of your capital; DeFindex, the protocol behind the vault, takes 20% of the yield it generates. - -**Update, 2026-10-24 (checked against the live SCF Integration List and on-chain contract data that day):** the CETES strategy above runs on a Blend lending pool (`CDMAVJPFXPADND3YRL4BSM3AKZWCTFMX27GLLXCML3PD62HEQS5FPVAI`, read directly from the strategy's own on-chain config). Blend currently carries **"Note: Blend temporarily removed from list"** on SCF's own Integration List (`stellar/scf-handbook`), its entire row struck through, while under review. Two real 2026 incidents hit Blend: YieldBlox/Blend V2 (~22-Feb-2026, ~$10.2-10.8M, an oracle misconfiguration via thin USTRY liquidity) and the Comet BLND-USDC backstop pool (~25-Aug-2026, ~$717K, a same-asset swap-accounting bug that paused Blend's backstop). Neither incident's affected pool is this one - YieldBlox's exploit drained a different pool entirely (`CCCCIQSDILITHMM7PBSLVDT5MISSY7R26MNZXCX4H7J5JQ5FPIYOGYFS`), and the Comet incident hit a separate backstop AMM pool (`CAS3FL6TLZKDGGSISDBWGGPXT3NRR4DYTZD7YOD3HMYO6LTJUVGRVEAM`), not any lending pool; Blend itself stated lending-pool depositors were not at risk in the August incident, only backstop depositors. This is not a claim that the Etherfuse/CETES pool is risk-free - only that it was not the pool involved in either known 2026 incident. - -The mainnet signer is a **separate process with its own key and no HTTP surface**: the mainnet API box holds no signing key at all, by design, and enforces it at startup. - --- ## Why now @@ -177,19 +123,18 @@ The mainnet signer is a **separate process with its own key and no HTTP surface* Market context, high-confidence sources only - this is not traction (see the next section for that), and none of it implies any relationship with Nirium unless stated. - **Mastercard published Verifiable Intent** ([mastercard.com](https://www.mastercard.com/us/en/news-and-trends/stories/2026/verifiable-intent.html)), an open standard for proving what a user actually authorized in an agent payment. Its own spec repo has two open issues asking the exact question Audit Trail already answers: [#37](https://github.com/agent-intent/verifiable-intent/issues/37) ("does VI check that a purchase matches what the user asked for, not only that it was authorized?") and [#42](https://github.com/agent-intent/verifiable-intent/issues/42) (what evidence anchors a decision after the fact). Verifying the payment is not the same problem as verifying the decision - that gap is Audit Trail's whole premise. -- **Tokenized RWA on Stellar grew 360%+ in 2026**, nearing $4B, with roughly $490M of it non-U.S. sovereign debt - CETES included - per Cointelegraph ([cointelegraph.com](https://cointelegraph.com/news/stellar-tokenized-rwa-market-nears-4b-after-fourfold-2026-growth)). This is the asset class the Treasury Node rebalances into. - **MPP shipped on a production mainnet**: Stripe and Tempo launched the Machine Payments Protocol on Tempo's mainnet in March 2026 ([theblock.co](https://www.theblock.co/post/394131/tempo-mainnet-goes-live-with-machine-payments-protocol-for-agents)). Nirium's own MPP Charge mode is testnet-only (see the status table above) - cited here as evidence the protocol itself is moving toward production elsewhere, not as our own traction. - **Institutional auto-renewal infrastructure went live on Stellar**: Ascend and M1X Global completed the first institutional repo on Stellar using a sovereign-bond-backed stablecoin, with 72 automated hourly rolls over three days, announced 23-oct-2026 ([businesswire.com](https://www.businesswire.com/news/home/20261023351098/en/)). Unrelated to Nirium - cited only as a market signal that institutional-grade automation is landing on this chain. + --- ## Market Traction: Developer Adoption & Verifiable On-Chain Activity Traction is **self-generated and independently verifiable**. It does not depend on third-party announcements: -- **Published SDKs** on npm and PyPI (`nirium`) with recorded downloads across multiple versions. -- **Live autonomous agent** running 24/7 on Stellar Testnet, every rebalance verifiable on Stellar Expert. -- **Real mainnet activity**: x402 micropayments settling in production, and a full treasury cycle executed with real funds (hashes above). +- **Published packages** on npm and PyPI (`nirium`) with recorded downloads across multiple versions. +- **Real mainnet activity**: x402 micropayments settling in production (hashes above). - **Open API + free sandbox keys**, so any developer can integrate and exercise the contracts directly. - **Real upstream engagement** - issues we filed and fixes we shipped against the Stellar and x402 ecosystems, most recent first. Every row links to the public thread; @@ -226,104 +171,75 @@ We provide the middleware; independent operators (e.g. Etherfuse) execute settle ## Architecture ``` -Fintech / Institution (B2B / A2A) +Fintech, developer or AI agent | v - [Next.js 15 Dashboard: nirium.xyz] - [i18n: EN / ES] + [Next.js 15 site: nirium.xyz, EN / ES] | v - [Agent API: dual network, 102 endpoints] - |-- nirium-agent.fly.dev (testnet, full autonomous loop, agent holds a key) + [Agent API: dual network] + |-- nirium-agent.fly.dev (testnet) |-- nirium-agent-mainnet.fly.dev (mainnet, receive-only, NO signing key by design) |-- Auth (JWT / API key / sandbox tiers) - |-- legalShield middleware (SCF CoC compliance) |-- x402 + MPP payment middleware - |-- Sliding-window rate limiting (300 rpm institutional) - |-- domainLock + obfuscation code exists but is not mounted on any route - | (Update, 2026-10-07: this line previously also listed "AML screening" as part - | of the Agent API. That middleware was never imported or mounted anywhere in - | the codebase since it was written - dead code, not a live control - and has - | been removed. domainLock and obfuscation remain in the repo, equally unmounted.) + |-- Sliding-window rate limiting | v - [Autonomous Execution Layer] - |-- Autonomous node: LLM proposes, deterministic fallback decides if it stalls - |-- Mainnet rebalancer: separate process, own key, no HTTP surface, - | deterministic rule with no model in the signing path - |-- Composable framework: up to 10 Execution Nodes per vault + [Soroban Contracts, testnet] + |-- NiriumVault (source-verified build, see Deployed Contracts) + |-- NiriumProtocol (reputation, strategy registry, scoring, skill gate) + |-- Policy Account (scopes an agent key to ONE vault: one CallContract + | rule, no Default rule; that absence IS the mechanism) | v - [Soroban Contracts] - |-- Testnet: NiriumVault (treasury, flash loans, delegation, emergency pause; - | source-verified build, see Deployed Contracts) - |-- Testnet: NiriumProtocol (ELO reputation, strategy registry, scoring, skill gate) - |-- Testnet: Policy Account (scopes the agent key to ONE vault: one CallContract - | rule, no Default rule; that absence IS the mechanism) - |-- Mainnet: DeFindex vault (third-party, OtterSec-audited, owned by the client; - | Nirium holds RebalanceManager only) - | - v - [Supabase] ← logs, auth_keys, webhooks, payroll_runs, treasury_vaults, subscriptions - [IPFS / Pinata] ← tamper-evident receipts; daily digest of confirmed executions + [Supabase] ← logs, auth_keys, webhooks, subscriptions + [IPFS / Pinata] ← tamper-evident receipts ``` --- ## Core Features -### Institutional API (102 endpoints: 101 HTTP + 1 WebSocket) +### API -Multi-tier authentication with sandbox accounts, self-service API keys (`/keys`, wallet-signed via SEP-53), tiers (free/sandbox/institutional/enterprise), and JWT for WebSocket. Full RBAC, sliding-window rate limiting. **Update, 2026-10-07:** this previously also said "AML checks, and domain lock" as live controls. Neither was ever mounted on any route - the AML middleware has been removed as dead code, and the domainLock/obfuscation modules remain in the repo, unused. +Multi-tier authentication with sandbox accounts, self-service API keys (`/keys`, wallet-signed via SEP-53), tiers (free/sandbox/institutional/enterprise), and JWT for WebSocket. Sliding-window rate limiting. | Access level | Endpoints | |---|---| -| Public (no key) | health, loop/status, execute-demo, signals/recent, skills, nodes, netdiag | -| Protected (API key) | execute, market, tickers, stats, loop control, webhooks, subscriptions, skills/install, payroll/\*, treasury/\* | -| Paid (x402 / MPP) | premium/\*, mpp/\* | +| Public (no key) | health, loop/status, skills, nodes, netdiag, audit/info, reporting/info | +| Protected (API key) | market, tickers, stats, webhooks, subscriptions, skills/install | +| Paid (x402 / MPP) | `premium/market`, `mpp/market` ($0.05 USDC, both networks) | | WebSocket (JWT) | `/ws/signals`, signal stream (the hosted endpoint did not accept connections when checked on 21 Nov 2026) | | Admin only | system/health, config/llm | -**Endpoints charge where the capability exists, not where it reads better.** The mainnet box holds no signing key and runs no autonomous loop, so `premium/signals` and `premium/execute` return `501` there instead of charging for an empty answer. `premium/market` charges and delivers on both networks. - -Full specification: [API_DOCUMENTATION_OPENAPI.yaml](API_DOCUMENTATION_OPENAPI.yaml) - -### Autonomous On-Chain Execution (Soroban) - -Strategies dispatched to the NiriumVault contract on testnet, all verifiable on Stellar Expert: +Closed: `premium/signals`, `premium/execute`, `mpp/signals` and `signals/recent` since 1 Dec 2026; `execute-demo`, the Payouts runs and the Treasury write routes since 30 Nov 2026. They answer `410` without charging. -- `flash-loan-arb` / `flash-loan` → `flash_loan_execute`: atomic flash loans with automatic revert on non-repayment -- `path-arbitrage` / `path-vector` → `execute_path_arbitrage`: path payment discovery for XLM-USDC corridors -- `cross-dex` → `execute_cross_dex`: cross-venue routing -- `blend-yield` → `execute_blend_yield`: non-custodial allocation on Blend Protocol -- `soroswap-swap` → `execute_soroswap_swap`: multi-hop execution with minimum-slippage enforcement - -The mainnet treasury path does **not** go through this router. It goes through the client-owned DeFindex vault described above. +Full specification: [API_DOCUMENTATION_OPENAPI.yaml](API_DOCUMENTATION_OPENAPI.yaml) (it still lists the closed routes). ### x402 + MPP + MCP -Any AI agent (Claude, GPT, custom) can access Nirium's premium data **per request** by paying USDC on Stellar: no account, no subscription. Adopted on launch day alongside emerging industry standards: +Any AI agent (Claude, GPT, custom) can pay for Nirium's market data **per request** by paying USDC on Stellar: no account, no subscription. Adopted on launch day alongside emerging industry standards: - x402 integrated April 2, 2026: same day as the Linux Foundation x402 Foundation launch - MPP integrated April 3, 2026: a few weeks after Stripe and Tempo launched it (March 2026) -**Both directions are supported.** `initX402()` pays for someone else's API, live today. `x402Serve()` charges for yours. **Update, 2026-10-07:** this previously said third-party facilitator use was invite-only, same gate as Treasury and Payouts - there is no such gate. `x402Serve()` is a general-purpose library that runs on the integrator's own server; Nirium does not operate or gate it. Third-party use is an open legal question, with no written legal opinion yet - compliance is the integrator's own responsibility: +**Both directions are supported.** `initX402()` pays for someone else's API, live today. `x402Serve()` charges for yours. `x402Serve()` is a general-purpose library that runs on the integrator's own server; Nirium does not operate or gate it. Third-party use is an open legal question, with no written legal opinion yet - compliance is the integrator's own responsibility: ```typescript import { x402Serve } from 'nirium'; app.use('/premium', x402Serve({ payTo: 'G...', - routes: { 'GET /signals': '$0.02' }, + routes: { 'GET /data': '$0.02' }, facilitatorApiKey: process.env.X402_FACILITATOR_API_KEY, // OpenZeppelin Channels, per network })); ``` Replay protection and a per-IP rate limit are available since nirium 0.15.0 through the optional `guard`; without it, `x402Serve()` verifies and settles the payment and nothing else. On the paying side, both SDKs refuse more than $1 of USDC per payment by default unless the integrator raises the cap (Python since 0.12.0, which also refuses a 402 offered on another network). -**MPP Charge is experimental**: implemented and verified on testnet (settled payments in pull and push mode, 15 Oct 2026); mainnet is unverified. Its design: the client signs a complete USDC transfer inside the request, the server validates it by simulation and broadcasts it, with no external facilitator. MPP's Channel mode is implemented but **disabled**, because its setup phase deploys a channel contract holding a deposit, which is temporary custody and falls under the same audit gate as our own vault. +**MPP Charge is experimental**: implemented and verified on testnet (settled payments in pull and push mode, 15 Oct 2026); mainnet is unverified. The client signs a complete USDC transfer inside the request, and the server validates it by simulation and broadcasts it, with no external facilitator. MPP's Channel mode is implemented but **disabled**, because its setup deploys a channel contract holding a deposit, which would be temporary custody. -The MCP server exposes Nirium as **25 tools** for Claude Desktop, Cursor, and any MCP-compatible IDE: 10 free, 9 authenticated, 1 informational, 3 paid over x402, 2 MPP tools (experimental). +The MCP server exposes Nirium to Claude Desktop, Cursor and any MCP-compatible IDE: 14 tools by default (see the [nirium-mcp README](https://github.com/nirium-protocol/nirium/tree/main/packages/mcp)). ### Audit Trail Engine @@ -339,63 +255,28 @@ Agent action or third-party event An invalid signature returns **400 and nothing is anchored**: nobody can guarantee deletion from IPFS (anyone with the CID may have kept a copy), so a false attestation could outlive any correction. Third-party apps anchor through `POST /api/audit/log`. Anchor **hashes, not raw personal data**. -### Live Market Ticker (Reference Data) - -> *Public protocol information. Not investment advice and not a return projection.* - -| Ticker | Source | Description | -|---|---|---| -| **XLM/USDC** | Reflector → CoinGecko → Stellar Expert | Multi-tier oracle price feed | -| **SDEX spread** | Stellar Horizon orderbook | Live XLM/USDC spread in basis points | -| **Blend rate** | Blend Protocol on-chain | Liquidity reference rate | -| **CETES rate** | Etherfuse (fixed reference) | **Fixed** reference value 5.57%, read 2026-06 from app.etherfuse.com/b/cetes; not updated live | -| **Base fee** | Stellar Horizon | Live network base fee | - -### Published SDKs (npm + PyPI) +### Published packages (npm + PyPI) -| SDK | Package | Version | Install | +| Package | Registry | Version | Install | |---|---|---|---| -| TypeScript | [nirium (npm)](https://www.npmjs.com/package/nirium) | 0.20.0 | `npm install nirium` | +| TypeScript | [nirium (npm)](https://www.npmjs.com/package/nirium) | 0.21.0 | `npm install nirium` | | Python | [nirium (PyPI)](https://pypi.org/project/nirium/) | 0.13.0 | `pip install nirium` | -| MCP server | [nirium-mcp (npm)](https://www.npmjs.com/package/nirium-mcp) | 0.6.13 | `npx nirium-mcp` | -| Pollar adapter | [nirium-pollar-adapter (npm)](https://www.npmjs.com/package/nirium-pollar-adapter) | 0.6.6 | `npm install nirium-pollar-adapter` | -| CLI | [nirium-cli (npm)](https://www.npmjs.com/package/nirium-cli) | 3.2.8 | `npm install -g nirium-cli` | +| MCP server | [nirium-mcp (npm)](https://www.npmjs.com/package/nirium-mcp) | 0.8.0 | `npx nirium-mcp` | +| CLI | [nirium-cli (npm)](https://www.npmjs.com/package/nirium-cli) | 4.0.0 | `npm install -g nirium-cli` | +| Pollar adapter | [nirium-pollar-adapter (npm)](https://www.npmjs.com/package/nirium-pollar-adapter) | 0.7.0 | `npm install nirium-pollar-adapter` | +| Solana | [nirium-solana (npm)](https://www.npmjs.com/package/nirium-solana) | 0.3.0 | `npm install nirium-solana` | +| Avalanche | [nirium-avalanche (npm)](https://www.npmjs.com/package/nirium-avalanche) | 0.3.0 | `npm install nirium-avalanche` | -Versions checked against the npm and PyPI registries on 23 Nov 2026. These packages are released from [nirium-protocol/nirium](https://github.com/nirium-protocol/nirium). - -> The two SDKs share full Treasury parity (12 methods, `proposeTreasuryRebalance()`/`propose_treasury_rebalance()` included) since 10-sep-2026. `x402Serve()` stays TypeScript-only - it's Express middleware, server-side Node, with no meaningful equivalent in an async Python client. Both SDKs include a resilient, auto-reconnecting WebSocket client (backoff, jitter, dedup; `ResilientSignalClient` in TypeScript), though the hosted stream at `/ws/signals` did not accept connections when checked on 18 Nov 2026. Python also ships a LangChain `BaseTool` (`pip install nirium[langchain]`) that TypeScript doesn't have. +Versions checked against the npm and PyPI registries on 2 Dec 2026. Full docs: the package READMEs in [nirium-protocol/nirium](https://github.com/nirium-protocol/nirium). ```typescript import { Agent } from 'nirium'; const agent = new Agent({ apiKey: 'sk_inst_...', baseUrl: 'https://nirium-agent.fly.dev' }); -const market = await agent.getMarket(); const nodes = await agent.getNodes(); await agent.anchorAuditRecord({ hash: '...' }); -agent.subscribe(signal => console.log(signal)); // hosted stream not accepting connections as of 18 Nov 2026 -``` - -```python -import asyncio -from nirium import Agent - -async def main(): - agent = Agent(api_url="https://nirium-agent.fly.dev", api_key="sk_inst_...") - - market = await agent.get_market() - await agent.anchor_audit_record(hash="...") - - @agent.on("signal") - async def on_signal(data): - print(data) - - await agent.subscribe() - -asyncio.run(main()) ``` -Full SDK documentation: the package READMEs in nirium-protocol/nirium, [TypeScript](https://github.com/nirium-protocol/nirium/tree/main/packages/sdk) and [Python](https://github.com/nirium-protocol/nirium/tree/main/packages/sdk-python). - --- ## Deployed Contracts @@ -405,25 +286,15 @@ Full SDK documentation: the package READMEs in nirium-protocol/nirium, [TypeScri | **NiriumVault** (source-verified, 9 Nov 2026) | Testnet | `CDMFURE6MYROTA2A6DLD4TN2S4QTN64L2FZ2I2RY2AREONX6DUQOI2S2` | Core treasury: vaults, agent delegation, strategy execution, flash loans, emergency pause (2-of-3 once cosigners are registered; none yet). Built by GitHub from [nirium-core@8489481](https://github.com/nirium-protocol/nirium-core/releases/tag/nirium-vault-v0.1.0_nirium-contracts_pkg0.1.0_cli28.1.0). Earlier, unverified deployments: `CBTWMZCG3P72EHFAQ4ZLSEBIOFYJC244H5J6DHZIJ56FHFWJ2CFAWSZU` (May 2026, used by nirium.xyz until 9 Nov, 180 vaults) and `CARTJIASVFHS4JJ24GVRO3XFQD37JCJEAXVPS7SPIWB3HLBXAYQ5SICV` (25 Oct 2026, never connected to the site) | | **NiriumProtocol** | Testnet | `CBKCTMTCCZQIPEESLHHEZKXYSPWNO24NEG33T2XSAAAHPISBND5CNSXX` | Unified registry: ELO reputation, strategy marketplace, agent scoring, skill gate (x402). No agents or strategies registered yet (checked 17 Nov 2026) | | **Policy Account** | Testnet | `CCZW2WIFAD7OQX35U5AILTNF32TCHQUYVPNB32GGKEKKPII2HF7B5LML` | Scopes an agent key to a single vault: one `CallContract` rule, **no** `Default` rule | -| **DeFindex vault** (reference) | Mainnet | `CAMDXG6L4LXLXXV675KZSHM3BMSETZ4NVMC7JYIQCZ2JTG54OMSK57MH` | Third-party, OtterSec-audited, owned by its deployer; Nirium holds RebalanceManager only | - -Verifiable at [Stellar Expert](https://stellar.expert/explorer/public). - ---- - -## Side Projects - -### /build: Startup Ideas Hub -Interactive dashboard with 12 startup ideas buildable on the Nirium API and SDKs, with code examples in TypeScript, Python, cURL, and MCP. -Live: [nirium.xyz/build](https://nirium.xyz/build) +Verifiable at [Stellar Expert](https://stellar.expert/explorer/testnet). --- ## Quick Start ### Requirements -- Node.js >=22.12.0, pnpm 9+ (`@stellar/stellar-sdk` 17.x requires 22.12.0+; an older Node resolves an older, incompatible SDK silently) +- Node.js >=22.12.0, pnpm 9+ (`@stellar/stellar-sdk` 17.x requires 22.12.0+; an older Node resolves an older, incompatible version silently) - [Freighter Wallet](https://freighter.app/) for dashboard interactions ### Run locally @@ -434,10 +305,11 @@ pnpm --filter nirium-web dev # web app on port 3000 The agent API (`packages/agent`) is private; this repo carries only its types, so `pnpm dev` (web + agent) only works in the private source. The web app talks to the hosted API boxes listed under Contact. -### SDK quick start +### Try it ```bash -npm install nirium # TypeScript SDK -pip install nirium # Python SDK +# Testnet: no real funds required +curl https://nirium-agent.fly.dev/health +curl https://nirium-agent.fly.dev/api/nodes ``` --- @@ -446,16 +318,16 @@ pip install nirium # Python SDK ``` nirium-core/ (public repo) -├── apps/web/ → Next.js 15 dashboard (nirium.xyz), i18n (EN/ES) -├── packages/sdk/ → copy of the TypeScript SDK (npm: nirium; released from nirium-protocol/nirium) -├── packages/sdk-python/ → copy of the Python SDK (PyPI: nirium; released from nirium-protocol/nirium) -├── nirium-soroban-contracts/ → Soroban contracts (Rust): NiriumVault + NiriumProtocol, both deployed on testnet, 5 fuzz targets +├── apps/web/ → Next.js 15 site (nirium.xyz), i18n (EN/ES) +├── packages/sdk/ → copy of the TypeScript package (npm: nirium; released from nirium-protocol/nirium) +├── packages/sdk-python/ → copy of the Python package (PyPI: nirium; released from nirium-protocol/nirium) +├── packages/mcp/ → MCP server (npm: nirium-mcp) +├── packages/cli/ → CLI (npm: nirium-cli) +├── nirium-soroban-contracts/ → Soroban contracts (Rust): NiriumVault + NiriumProtocol, both on testnet, 5 fuzz targets ├── packages/policy-account/ → Soroban policy account (Rust), scopes a key to one vault -├── .github/workflows/ → CI, release, security-gate, desktop release, NiriumVault verified release +├── .github/workflows/ → CI, release, security-gate, NiriumVault verified release │ -├── packages/agent/ → [private] Express 5 API, 102 endpoints (101 HTTP + 1 WebSocket); only its types are published here -├── packages/mcp/ → [public] MCP server, 25 tools (npm: nirium-mcp) -├── packages/cli/ → [public] CLI (npm: nirium-cli) +├── packages/agent/ → [private] Express 5 API; only its types are published here ├── packages/desktop/ → [private] Tauri desktop wrapper ``` @@ -464,10 +336,9 @@ nirium-core/ (public repo) ## Security - **Internal self-review only. No external audit and no penetration test has been done.** The report lists method, findings, fixes and what was left out; it carries no score and no certification. -- Methodology: static analysis (`cargo clippy`, grep), runtime checks on testnet, `cargo audit` + `pnpm audit` in CI, fuzz smoke runs (5 cargo-fuzz targets), manual code review -- **Update, 2026-10-12 (checked against `INTERNAL_SECURITY_AUDIT.md` and CI that day):** this section previously stated "83/83 vectors checked" and named the method "full-spectrum pentesting". The score and that label were removed: no pentest was performed and a pass count over our own checklist is not evidence an outside reader can check. -- A formal independent audit is planned before any mainnet deployment of **NiriumVault**. The mainnet nodes running today do not depend on it: they either never touch funds (x402, audit, reporting), or the client signs every fund movement themselves (Payouts), or they operate a **third-party contract already audited by OtterSec** in a role that cannot withdraw (Treasury). -- The mainnet API box holds **no signing key**, enforced at startup. The autonomous mainnet signer is a separate process with no HTTP surface. +- Methodology: static analysis (`cargo clippy`, grep), runtime checks on testnet, `cargo audit` + `pnpm audit` in CI, fuzz smoke runs (5 cargo-fuzz targets), manual code review. +- A formal independent audit is planned before any mainnet deployment of **NiriumVault**. The mainnet nodes running today never touch client funds: x402 is signed by the client and settled by an independent facilitator, and Audit Trail and Reporting only store and read hashes. +- The mainnet API box holds **no signing key**, enforced at startup. - See [SECURITY.md](SECURITY.md) for responsible disclosure, and [INTERNAL_SECURITY_AUDIT.md](INTERNAL_SECURITY_AUDIT.md) for the full report. --- @@ -478,11 +349,11 @@ Nirium operates in alignment with the [Stellar Code of Conduct](https://stellar. | Principle | Nirium status | |---|---| -| Stellar must be **core and valuable**, not auxiliary | ✅ Soroban contracts, SDEX, Blend, DeFindex, x402; MPP experimental; Stellar is the execution layer | +| Stellar must be **core and valuable**, not auxiliary | ✅ Soroban contracts, x402 and Audit Trail anchoring on Stellar; MPP experimental | | No speculation, wash trading, or insider trading with grant funds | ✅ Grant funds allocated to development, not trading | | No investment advice or yield promises | ✅ Prominent disclaimer; rates displayed as protocol reference data only | | No marketing promising interest, dividends, or appreciation | ✅ Language focuses on workflow automation, not guaranteed returns | -| Open source, contracts and SDKs publicly available | ✅ Soroban contracts + TypeScript SDK + Python SDK in the public repo | +| Open source, contracts and packages publicly available | ✅ Soroban contracts + TypeScript and Python packages in the public repo | | Transparency | ✅ Every protocol action auditable on-chain via Stellar Expert | | Integrity | ✅ No front-running or predatory extraction | | Safety | ✅ Non-custodial by design; the user is the sole custodian of their keys | @@ -502,22 +373,20 @@ Nirium received two Stellar Community Fund Instawards, through the Stellar Ambas | Milestone | Status | |---|---| | Core infrastructure + x402 on testnet | ✅ Complete · MPP experimental | -| Institutional API (102 endpoints) + published SDKs | ✅ Complete | +| API + published TypeScript and Python packages | ✅ Complete | | Internal security self-review (no external audit; see report) | ✅ Complete | -| MCP server, 25 tools | ✅ Complete | -| Etherfuse CETES integration (testnet + SPEI sandbox) | ✅ Complete | +| MCP server | ✅ Complete | | Self-service API keys console (`/keys`, wallet-signed via SEP-53) | ✅ Live | -| Mainnet receive-only nodes (x402, Audit Trail, Reporting) | ✅ Live, early access | -| MPP Charge, mainnet receive-only node | 🟡 Implemented, experimental - no confirmed mainnet settlement yet, see the evidence table above | -| Payouts node, non-custodial batch disbursements | ✅ Live, mainnet invite-only | -| `x402Serve()`, charge for your own API in one call | ✅ Shipped in SDK. **Update, 2026-10-07:** previously said third-party use was invite-only during legal review - there is no such gate. It's a general-purpose library the integrator runs on their own server; Nirium does not operate or gate it; compliance is theirs | +| Mainnet receive-only nodes (x402, Audit Trail, Reporting) | ✅ Live | +| MPP Charge, mainnet receive-only node | 🟡 Implemented, experimental - no confirmed mainnet settlement yet | +| `x402Serve()`, charge for your own API in one call | ✅ Shipped. A library the integrator runs on their own server; Nirium does not operate or gate it | | Agent attestation in the audit trail (signed evidence) | ✅ Shipped | -| Treasury node on mainnet over a client-owned DeFindex vault | ✅ Live, invite-only until a written legal opinion | -| Legal opinion on the treasury node (MX + cross-border) | ⏳ Pending: no lawyer engaged yet; a written opinion gates opening it beyond invite-only | -| Etherfuse, enterprise KYB onboarding | **Update, 2026-10-14:** this row previously read "In progress". Etherfuse told us they cannot commit to a partnership or KYB track at this time, only co-marketing. Closed, not in progress. | -| Stellar Community Fund Build Award | 🔄 Submitted for SCF #46 on 9 Nov 2026, in review | +| Pre-sign policy hook | ✅ Shipped, experimental | +| Solana and Avalanche (x402, pre-sign policy, payment-bound receipts) | ✅ Public repos, packages on npm | +| Base and Arbitrum | 🟡 First versions | +| Treasury and Payouts | Tested only with the team's own funds; discontinued 30 Nov 2026 | +| Legal opinion (MX + cross-border) | ⏳ Pending a written legal opinion; no lawyer engaged yet | | Formal independent audit of NiriumVault | Planned, ahead of any NiriumVault mainnet deployment | -| NiriumVault mainnet deployment (real treasury funds) | Post formal audit | | **KineGuard** (tentative name) - remote key-custody policy gate: the auditor endpoint would hold or gate access to the signing key itself, not just opine before the same process signs | 💭 Idea only. Not designed, not scoped, no date. Distinct from Policy Gate above (#6), which already covers "ask a policy engine before signing" - this would only be worth building if it closes that control's one real gap: code in the same process as the key can bypass a same-process hook. | --- @@ -526,7 +395,6 @@ Nirium received two Stellar Community Fund Instawards, through the Stellar Ambas - **Stellar Community Fund Instawards (2)**, via the Stellar Ambassador Program; full KYC complete (Airtable + Persona + W-8BEN). Payments on mainnet: [#1, 11 May 2026](https://stellar.expert/explorer/public/tx/fd0f7469ae78b76ca5c4186cd7e1b24c081c407758a92cff3a56f376d01e91d1) and [#2, 31 Jul 2026](https://stellar.expert/explorer/public/tx/7784ad6eb2b27ace75ce2fe4b7290fb1b8241da425331bfbda2e939b47759b7e) - **Update, 2026-10-12 (checked against this repository):** this list previously included "Stellar Scale / Kickstart: 83/100 Bootcamp Impact; active graduate with ongoing SDF mentorship". The line was removed because it could not be verified (no source for the 83/100 figure or for an SDF mentorship), not reworded. -- **Update, 2026-10-14 (confirmed directly with Etherfuse):** this line previously read "active technical integration (CETES on testnet + SPEI sandbox); enterprise KYB onboarding in progress". We used Etherfuse's CETES vault via DeFindex (4 mainnet rebalances, 6-Aug-2026); no partnership or KYB is in progress. --- @@ -536,7 +404,7 @@ Nirium received two Stellar Community Fund Instawards, through the Stellar Ambas |---|---| | [SDKs.md](SDKs.md) | Historical SDK notes (SDK 0.5.0); the maintained docs are the package READMEs in nirium-protocol/nirium | | [API_DOCUMENTATION_OPENAPI.yaml](API_DOCUMENTATION_OPENAPI.yaml) | OpenAPI specification | -| [MCP_INTEGRATION_GUIDE.md](MCP_INTEGRATION_GUIDE.md) | Historical MCP guide (v0.4.0); the maintained one is the [nirium-mcp README](https://github.com/nirium-protocol/nirium/tree/main/packages/mcp) (25 tools) | +| [MCP_INTEGRATION_GUIDE.md](MCP_INTEGRATION_GUIDE.md) | Historical MCP guide (v0.4.0); the maintained one is the [nirium-mcp README](https://github.com/nirium-protocol/nirium/tree/main/packages/mcp) (14 tools by default) | | [INTERNAL_SECURITY_AUDIT.md](INTERNAL_SECURITY_AUDIT.md) | Internal security self-review: method, findings, fixes, out of scope | | [NIRIUM_TECHNICAL_PAPER.md](NIRIUM_TECHNICAL_PAPER.md) | Technical whitepaper | | [SECURITY.md](SECURITY.md) | Responsible vulnerability disclosure policy | @@ -544,25 +412,6 @@ Nirium received two Stellar Community Fund Instawards, through the Stellar Ambas --- -## Developer Quick Start - -```bash -# Testnet: no real funds required -curl https://nirium-agent.fly.dev/health - -# The node catalog: no key needed -curl https://nirium-agent.fly.dev/api/nodes - -# Sandbox API key (free) -curl https://nirium-agent.fly.dev/api/sandbox/status \ - -H "x-api-key: YOUR_SANDBOX_KEY" - -# WebSocket signal stream (hosted endpoint not accepting connections as of 21 Nov 2026; -# run your own agent and use ws://localhost:3001/ws/signals?token=YOUR_JWT) -``` - ---- - ## Contact | Channel | Link | @@ -570,9 +419,8 @@ curl https://nirium-agent.fly.dev/api/sandbox/status \ | **Website** | [nirium.xyz](https://nirium.xyz) | | **API (testnet)** | [nirium-agent.fly.dev](https://nirium-agent.fly.dev) | | **API (mainnet)** | [nirium-agent-mainnet.fly.dev](https://nirium-agent-mainnet.fly.dev) | -| **Build Hub** | [nirium.xyz/build](https://nirium.xyz/build) | +| **Every network** | [nirium.xyz/chains](https://nirium.xyz/chains) | | **X / Twitter** | [@Niriumstellar](https://x.com/Niriumstellar) | -| **SCF / Community** | [communityfund.stellar.org](https://communityfund.stellar.org) | | **Security** | niriumprotocol@gmail.com | --- @@ -587,4 +435,4 @@ This project operates under the [Stellar Community Fund](https://stellar.gitbook --- -*Nirium Protocol: experimental software. Not financial advice. NiriumVault is testnet-only and audit-gated; the mainnet treasury node runs over a client-owned, third-party audited DeFindex vault in a role that cannot withdraw. Updated November 22, 2026.* +*Nirium Protocol: experimental software. Not financial advice. NiriumVault is testnet-only and audit-gated. Treasury and Payouts were tested only with the team's own funds and discontinued on 30 Nov 2026. Updated 2 December 2026.* diff --git a/apps/web/app/(app)/agents/layout.tsx b/apps/web/app/(app)/agents/layout.tsx index ed64e947..ae065132 100644 --- a/apps/web/app/(app)/agents/layout.tsx +++ b/apps/web/app/(app)/agents/layout.tsx @@ -2,8 +2,8 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/agents", - title: "Execution Nodes", - description: "Nirium's execution nodes on Stellar: what each one does, what it is allowed to sign, and on which network it runs.", + title: "How it works", + description: "Nirium's 3 nodes: what each one does, what it is allowed to sign, and on which network it runs.", }); export default function AgentsLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/agents/page.tsx b/apps/web/app/(app)/agents/page.tsx index 01d8778d..023c97d1 100644 --- a/apps/web/app/(app)/agents/page.tsx +++ b/apps/web/app/(app)/agents/page.tsx @@ -33,79 +33,9 @@ export default function AgentsPage() { return () => { cancelled = true; }; }, []); + // 30-nov-2026: los nodos de Tesorería, Payouts y bóveda se archivaron (ver /treasury). + const NODE_ORDER = ['audit-node', 'settlement-hub', 'policy-gate']; const nodes = [ - { - id: "rebalance-node", - statusLabel: lang("MAINNET · INVITE-ONLY", "MAINNET · POR INVITACIÓN"), - statusColor: "bg-emerald-400/10 text-emerald-400 border-emerald-400/20", - dotColor: "bg-stellar-teal", - accentBorder: "border-stellar-teal/20", - icon: Activity, - iconColor: "text-stellar-teal", - name: lang( - "Rebalance Node", - "Nodo de Rebalanceo"), - role: lang( - "Autonomous rebalancing of a vault's idle funds (USDC or CETES, one asset per vault) into the vault's own strategy and back, based on thresholds the vault owner sets, no human approval per call. Designed to run continuously; to date, 4 real rebalances, self-funded, all on 6 Aug 2026, none since.", - "Rebalanceo autónomo del saldo ocioso de una bóveda (USDC o CETES, un activo por bóveda) hacia la estrategia de esa misma bóveda y de regreso, según umbrales que fija el dueño de la bóveda, sin aprobación humana por llamada. Diseñado para correr de forma continua; a la fecha, 4 rebalanceos reales, autofinanciados, todos el 6-ago-2026, ninguno desde entonces."), - // Revisado contra rebalanceDecision.ts / scripts/rebalancer.ts (8-nov-2026): - // no es un spread. Es la tasa de CETES de la bóveda (medida desde su - // propia posición, o la de referencia declarada si aún no hay historia) - // contra dos umbrales del dueño, con banda muerta entre ellos. - cycle: lang("Checks every 10 minutes by default", "Revisa cada 10 minutos por defecto"), - trigger: lang( - "The vault's measured yield (or the CETES reference rate, until there is history) reaches the owner's entry threshold (invest idle cash) or drops to the exit threshold (unwind); between the two, it does nothing", - "El rendimiento medido de la bóveda (o la tasa de referencia de CETES, mientras no hay historial) llega al umbral de entrada del dueño (invierte el efectivo ocioso) o baja al de salida (recoge lo invertido); entre los dos, no hace nada"), - authorized: lang( - "Invest and Unwind between the vault's own strategies - no swaps, no destination address", - "Invest y Unwind entre las estrategias de la propia bóveda - sin swaps y sin dirección de destino"), - audit: lang( - "SHA-256 + IPFS anchor when a run is recorded (opt-in)", - "SHA-256 + anclaje IPFS cuando se registra una corrida (opcional)"), - // 21-nov-2026 (G2): era una ruta relativa, que en nirium.xyz da 404. - metric: ( - <> - {lang("Health is public - see ", "Salud pública - ver ")} - nirium-agent-mainnet.fly.dev/api/public/rebalancer-health - {lang( - "; a non-zero problem count there is expected when a dependency hiccups, not a silent failure", - "; un conteo de problemas distinto de cero ahí es esperado cuando falla una dependencia, no una falla silenciosa")} - - ), - locked: false, - }, - { - id: "payroll-node", - statusLabel: lang("MAINNET · EARLY ACCESS · INVITE-ONLY", "MAINNET · ACCESO ANTICIPADO · POR INVITACIÓN"), - statusColor: "bg-emerald-400/10 text-emerald-400 border-emerald-400/20", - dotColor: "bg-stellar-teal", - accentBorder: "border-stellar-teal/20", - icon: Send, - iconColor: "text-stellar-teal", - name: lang( - "Disbursement Node (Bulk Payouts)", - "Nodo de Dispersión (Pagos Masivos)"), - role: lang( - "Disburse funds from one company wallet to up to 100 recipients per batch (99 if the batch carries a fee) - contractors, freelancers, B2B partners - in a single signed batch payment. Non-custodial - the company signs in its own wallet, Nirium never holds funds.", - "Dispersa fondos desde una wallet de la empresa a hasta 100 destinatarios por lote (99 si el lote lleva comisión) - contratistas, freelancers, socios B2B - en un solo lote de pago firmado. Non-custodial - la empresa firma en su propia wallet, Nirium nunca custodia fondos."), - cycle: lang("On-demand / per run", "Bajo demanda / por corrida"), - trigger: lang( - "Company builds and signs a payout run", - "La empresa arma y firma una corrida de pago"), - authorized: lang( - // No es "sponsored": executePayroll.ts (onboardEmployee) arma un - // changeTrust que firma el propio destinatario y su cuenta paga la - // reserva. Verificado el 8-nov-2026. - "Batch USDC/XLM payment (up to 100 recipients per batch, 99 if the batch carries a fee) + USDC trustline the recipient adds and signs itself", - "Pago batch USDC/XLM (hasta 100 destinatarios por lote, 99 si el lote lleva comisión) + trustline USDC que el propio destinatario agrega y firma"), - audit: lang( - "Tamper-evident IPFS receipt per run (optional LCP legal layer - pending a legal opinion)", - "Recibo IPFS por corrida donde cualquier cambio se nota (capa legal LCP opcional - pendiente de opinión legal)"), - metric: lang( - "Mainnet early access · independent service payments only · Freighter-signed", - "Mainnet early access · solo pagos de servicios independientes · firmado con Freighter"), - locked: false, - }, { id: "policy-gate", // Reemplaza a "Compliance Sentinel" (2026-11-03): esa tarjeta @@ -117,8 +47,8 @@ export default function AgentsPage() { // esta es la mitad real. Texto igual al de // packages/agent/src/services/nodeRegistry.ts (la fuente real) - // si se actualiza uno, actualizar el otro. - // Sin "SDK" en lo público (regla de AGENTS.md: ese enrutamiento ya - // costó un prescreen de SCF). Es el paquete `nirium` en npm. + // Sin "SDK" en lo público: se nombra la capacidad, no la + // categoría técnica. Es el paquete `nirium` en npm. statusLabel: lang("SHIPPED · NPM PACKAGE", "PUBLICADO · PAQUETE NPM"), statusColor: "bg-emerald-400/10 text-emerald-400 border-emerald-400/20", dotColor: "bg-green-400", @@ -156,8 +86,8 @@ export default function AgentsPage() { "Settlement Hub", "Hub de Liquidación"), role: lang( - "On mainnet, Nirium's own x402 test endpoint (/premium/market, $0.05) settles on-chain; signals and execute answer 501 there without charging. x402Serve() lets you charge for your own API the same way. Third-party use on mainnet is not something we promote until we have a written legal opinion, and compliance is the integrator's own responsibility.", - "En mainnet, el endpoint x402 de prueba de Nirium (/premium/market, $0.05) liquida en cadena; signals y execute responden 501 ahí sin cobrar. x402Serve() te deja cobrar por tu propia API de la misma forma. No promovemos su uso por terceros en mainnet hasta tener una opinión legal por escrito, y el cumplimiento es responsabilidad de quien integra."), + "On mainnet, Nirium's own x402 test endpoint (/premium/market, $0.05) settles on-chain; signals answers 501 there without charging. x402Serve() lets you charge for your own API the same way. Third-party use on mainnet is not something we promote until we have a written legal opinion, and compliance is the integrator's own responsibility.", + "En mainnet, el endpoint x402 de prueba de Nirium (/premium/market, $0.05) liquida en cadena; signals responde 501 ahí sin cobrar. x402Serve() te deja cobrar por tu propia API de la misma forma. No promovemos su uso por terceros en mainnet hasta tener una opinión legal por escrito, y el cumplimiento es responsabilidad de quien integra."), cycle: lang("On-demand", "Bajo demanda"), trigger: lang("Paid HTTP requests (x402)", "Requests HTTP pagados (x402)"), authorized: lang( @@ -203,44 +133,6 @@ export default function AgentsPage() { "Anclajes en mainnet - conteo en vivo en /stats"), locked: false, }, - { - // Revisado contra packages/contracts/src/nirium_vault.rs (8-nov-2026). - // Antes decía que pausa, cambio de cosignatarios y cierre de bóveda - // requerían multisig 2-de-3. En el contrato: solo pause/unpause usan - // admin + 1 cosignatario, y solo si hay cosignatarios registrados (si no, - // el admin solo); set_cosigners es solo del admin; close_vault lo firma - // el dueño de la bóveda. - id: "vault-operations", - statusLabel: lang("TESTNET · CONTRACT ADMIN", "TESTNET · ADMIN DEL CONTRATO"), - statusColor: "bg-red-500/10 text-red-400 border-red-500/20", - dotColor: "bg-red-400", - accentBorder: "border-red-500/20", - icon: Lock, - iconColor: "text-red-400", - name: lang( - "Vault Operations Node", - "Nodo de Operaciones de Vault"), - // Confirmado en la cadena el 8-nov-2026 (instance storage de - // CARTJI…Q5SICV vía Soroban RPC): solo AdminAddress, Treasury y - // contadores; ningún Cosigner1/Cosigner2. O sea, hoy pausa el admin solo. - role: lang( - "Emergency controls of the NiriumVault contract. The contract supports a 2-of-3 pause (admin plus one cosigner), but the testnet deployment (contract CDMFURE6…) has no cosigners registered yet (checked on-chain, 21 Nov 2026), so today pausing or resuming takes the admin's signature alone. Each owner closes their own vault with their own signature. Never runs autonomously.", - "Controles de emergencia del contrato NiriumVault. El contrato admite una pausa 2-de-3 (admin más un cosignatario), pero el despliegue de testnet (contrato CDMFURE6…) todavía no tiene cosignatarios registrados (revisado en la cadena, 21 nov 2026), así que hoy pausarlo o reanudarlo requiere solo la firma del admin. Cada dueño cierra su propia bóveda con su propia firma. Nunca corre de forma autónoma."), - cycle: lang("Manual only", "Solo manual"), - trigger: lang( - "Admin request (no cosigners registered yet)", - "Solicitud del admin (aún sin cosignatarios registrados)"), - authorized: lang( - "Contract pause/unpause · cosigner changes (admin only)", - "Pausa/reanudación del contrato · cambio de cosignatarios (solo el admin)"), - audit: lang( - "Pause and unpause emit on-chain events", - "La pausa y la reanudación emiten eventos en la cadena"), - metric: lang( - "Human signatures only - no autonomous action", - "Solo firmas humanas - ninguna acción autónoma"), - locked: false, - }, ]; return ( @@ -267,8 +159,8 @@ export default function AgentsPage() { {/* Antes prometía "rastro de auditoría criptográfico" para los 6; Policy Gate y Vault Operations no lo tienen (ver su campo Audit). */} {lang( - "6 nodes: what each one does, what it is allowed to sign, and on which network it runs.", - "6 nodos: qué hace cada uno, qué puede firmar y en qué red corre.")} + "3 nodes: what each one does, what it is allowed to sign, and on which network it runs.", + "3 nodos: qué hace cada uno, qué puede firmar y en qué red corre.")}

@@ -310,9 +202,11 @@ export default function AgentsPage() { {/* ── NODE CARDS ─────────────────────────────────────────── */}
- {nodes.map((node, i) => ( + {/* 27-nov-2026: los nodos de Audit Trail, x402 y la política primero; los de + Tesorería y Payouts después, bajo "en pausa". */} + {[...nodes].sort((a, b) => NODE_ORDER.indexOf(a.id) - NODE_ORDER.indexOf(b.id)).map((node, i) => ( +
+
))}
diff --git a/apps/web/app/(app)/analytics/layout.tsx b/apps/web/app/(app)/analytics/layout.tsx index ad6f9aad..b9f49255 100644 --- a/apps/web/app/(app)/analytics/layout.tsx +++ b/apps/web/app/(app)/analytics/layout.tsx @@ -2,8 +2,8 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/analytics", - title: "Network Telemetry", - description: "Receipts, settlements and node activity on Stellar, with links to the transactions behind them. Panels with sample data are labeled.", + title: "Reporting", + description: "Payments, receipts and what you can download: public data from mainnet and testnet as CSV or JSON, with links to the transactions behind them.", }); export default function AnalyticsLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/analytics/page.tsx b/apps/web/app/(app)/analytics/page.tsx index ac0911c3..53ce079f 100644 --- a/apps/web/app/(app)/analytics/page.tsx +++ b/apps/web/app/(app)/analytics/page.tsx @@ -16,8 +16,6 @@ import NodeActivity from "@/components/analytics/NodeActivity"; import ReceiptsSettlements from "@/components/analytics/ReceiptsSettlements"; import NetworkScopeNote from "@/components/shared/NetworkScopeNote"; import { ComplianceBanner, AtomicProofBadge } from "@/components/ui/ComplianceBanner"; -import { getCETESBalance, vaultGetVaultCount, vaultGetTotalFees } from "@/lib/sorobanContracts"; -import { CETES_REFERENCE_RATE_PCT, CETES_REFERENCE_DATE_LABEL_EN } from "@/lib/cetesReference"; // ── StatCard ────────────────────────────────────────────────────────────── const StatCard = ({ title, value, change, icon: Icon, color, status }: any) => ( @@ -60,14 +58,10 @@ const StatCard = ({ title, value, change, icon: Icon, color, status }: any) => ( type AnalyticsLog = { time: string; source: string; type: string; msg: string; tx?: string }; const ANALYTICS_LOGS: AnalyticsLog[] = [ - { time: '00:25:44', source: 'REBALANCE_NODE', type: 'info', msg: `Scan - CETES ${CETES_REFERENCE_RATE_PCT}% (Etherfuse fixed reference, ${CETES_REFERENCE_DATE_LABEL_EN}) vs idle USDC | base fee 100 stroops.` }, - { time: '00:25:46', source: 'REBALANCE_NODE', type: 'success', msg: `CETES reference ${CETES_REFERENCE_RATE_PCT}% (fixed, Etherfuse, ${CETES_REFERENCE_DATE_LABEL_EN}, not live) is above the 2.5% rule threshold. Rule condition only, not a recommendation. The agent calls rebalance() on the owner's DeFindex vault: Invest into its own strategy - no swap, no destination address.` }, - { time: '00:25:48', source: 'AUDIT_NODE', type: 'audit', msg: 'Transaction confirmed on-chain before it is logged. Anchoring a receipt of it is opt-in, per call.' }, - { time: '00:30:12', source: 'PAYOUTS_NODE', type: 'payment', msg: 'Batch prepared: unsigned XDR built server-side. The client signs it with their own wallet - Nirium never holds the key.' }, - { time: '00:30:15', source: 'PAYOUTS_NODE', type: 'success', msg: 'Batch submitted. One signature, every transfer in a single Stellar transaction.' }, - { time: '00:35:00', source: 'SETTLEMENT', type: 'info', msg: 'x402 challenge issued - 0.02 USDC for /signals.' }, - { time: '00:35:02', source: 'SETTLEMENT', type: 'success', msg: 'Payment verified and settled on-chain before the response was returned.' }, - { time: '00:35:04', source: 'AUDIT_NODE', type: 'success', msg: 'Receipt anchored to IPFS on request - the caller gets a CID anyone can check at /verify.' }, + { time: '00:25:44', source: 'SETTLEMENT', type: 'info', msg: 'x402 challenge issued - 0.02 USDC for /signals.' }, + { time: '00:25:46', source: 'SETTLEMENT', type: 'success', msg: 'Payment verified and settled on-chain before the response was returned.' }, + { time: '00:25:48', source: 'AUDIT_NODE', type: 'success', msg: 'Receipt anchored to IPFS on request - the caller gets a CID anyone can check at /verify.' }, + { time: '00:30:16', source: 'AUDIT_NODE', type: 'audit', msg: 'Transaction confirmed on-chain before it is logged. Anchoring a receipt of it is opt-in, per call.' }, ]; export default function AnalyticsPage() { @@ -145,27 +139,6 @@ export default function AnalyticsPage() { return () => { cancelled = true; clearInterval(id); }; }, []); - // ── Live on-chain stats ────────────────────────────────────────────────── - const [vaultCount, setVaultCount] = useState('-'); - const [feesCollected, setFeesCollected] = useState('-'); - const [cetesBalance, setCetesBalance] = useState('-'); - const [cetesRate, setCetesRate] = useState(`${CETES_REFERENCE_RATE_PCT}%`); - - useEffect(() => { - // Fetch on-chain metrics - vaultGetVaultCount().then(n => setVaultCount(String(n))).catch(() => {}); - vaultGetTotalFees().then(f => setFeesCollected(`${(Number(f) / 10_000_000).toFixed(2)} XLM`)).catch(() => {}); - - if (accountStr) { - getCETESBalance(accountStr).then(b => setCetesBalance(`${Number(b).toFixed(2)} CETES`)).catch(() => {}); - } - - // CETES reference rate from the agent API: a fixed value (12 Nov 2026), not a live reading - fetch('https://nirium-agent.fly.dev/api/tickers') - .then(r => r.json()) - .then(d => { if (d.cetesRate) setCetesRate(`${d.cetesRate.toFixed(2)}%`); }) - .catch(() => {}); - }, [accountStr]); return (
@@ -190,19 +163,20 @@ export default function AnalyticsPage() {

{/* 16-nov-2026: decía "Treasury Telemetry"; la página ahora abre con recibos y cobros. */} - {language === 'es' ? 'TELEMETRÍA DE LA RED' : 'NETWORK TELEMETRY'} + {/* 27-nov-2026: el home manda aquí como la página de Reporting. */} + {language === 'es' ? 'REPORTING' : 'REPORTING'} - v0.20.0 + v0.21.0

- {language === 'es' ? 'Recibos, cobros y actividad por nodo' : 'Receipts, settlements and node activity'} + {language === 'es' ? 'Pagos, recibos y lo que puedes descargar' : 'Payments, receipts and what you can download'}

- {language === 'es' ? 'Lecturas on-chain de mainnet y testnet · NiriumVault solo en testnet' : 'On-chain reads from mainnet and testnet · NiriumVault on testnet only'} + {language === 'es' ? 'Datos públicos de mainnet y testnet · CSV o JSON' : 'Public data from mainnet and testnet · CSV or JSON'}
@@ -214,117 +188,6 @@ export default function AnalyticsPage() { {/* 16-nov-2026: recibos, cobros y reporting antes que Treasury. */} - {/* KPI Grid - Treasury, live on-chain data. Plegado por defecto (16-nov-2026). */} -
- -
-

- {language === 'es' ? 'Treasury · tu wallet y testnet' : 'Treasury · your wallet and testnet'} -

-

- {language === 'es' ? 'Saldos de tu wallet y del contrato NiriumVault en testnet, sin valor real.' : 'Your wallet balances and the NiriumVault contract on testnet, no real value.'} -

-

- {language === 'es' ? 'En mainnet, Treasury es solo por invitación hasta tener una opinión legal por escrito.' : 'On mainnet, Treasury is invite-only until we have a written legal opinion.'} -

-
- -
- -
- - - - -
- - {/* Charts & Side Area */} -
-
-
-
- -

TREASURY DEPLOYMENT HISTORY

-
-
- {/* Aquí había una gráfica hecha con Math.random(): etiquetada "Datos de - muestra", pero con horas reales en el eje y una curva que cambiaba en - cada clic de 24H/7D/30D. En una página llamada "telemetría" eso se lee - como historial real. Hasta tener una serie real, se dice que no la hay. */} -
-

- {language === 'es' ? 'Sin historial que graficar todavía' : 'No history to chart yet'} -

-

- {language === 'es' - ? 'El rebalanceo en mainnet solo ha corrido con fondos del equipo (4 rebalanceos, 6-ago-2026). Las ejecuciones reales, con su transacción, están en la evidencia on-chain verificada y en el feed del dashboard.' - : "Mainnet rebalancing has only run with the team's own funds (4 rebalances, 6 Aug 2026). Real executions, each with its transaction, are under Verified On-chain Evidence and in the dashboard feed."} -

-
-
- -
-

CAPITAL DEPLOYMENT MATRIX

-
- {[ - { asset: 'CETES', name: 'Etherfuse Stablebond', rate: `${CETES_REFERENCE_RATE_PCT}% fixed ref. (${CETES_REFERENCE_DATE_LABEL_EN})`, type: 'TOKENIZED CETES' }, - { asset: 'USDC', name: 'Operational Liquidity', rate: '0.00%', type: 'STABLE' }, - { asset: 'XLM', name: 'Gas Reserve', rate: 'Min.', type: 'UTILITY' }, - // AUDIT y PAYOUTS salieron de aquí el 9-nov-2026: no son activos de la - // tesorería. Ahora tienen su propia tarjeta en "Actividad por nodo". - ].map((item, i) => ( -
-
- {item.asset} - {item.name} -
-
-
{item.rate}
-
{item.type}
-
-
- ))} -
-
-
- -
{/* Agent Activity Feed */} @@ -343,9 +206,6 @@ export default function AnalyticsPage() { esto es una muestra de la forma que tienen las entradas. */}
{language === 'es' ? 'Ejemplo' : 'Example'} - - {language === 'es' ? 'Feed en vivo en el dashboard' : 'Live feed in the dashboard'} -
@@ -420,18 +280,6 @@ export default function AnalyticsPage() { {[ { net: 'mainnet' as const, date: '2026-07-09', tx: '3134a51c66091fd7fbd85b38a4a6ec6cd432bb92c2450eac84ea7855cb7558bc', msg: 'x402 settlement - 0.02 USDC to our x402 account (Nirium-funded test wallet)' }, { net: 'mainnet' as const, date: '2026-08-05', tx: 'e4fa3df9cb225a4d7f64dd0082eb38218ada4b4af3378f288989a5d4b1116ed9', msg: 'x402 settlement - 0.02 USDC, signed via Pollar social login (Nirium self-test, reserve funded by us)' }, - // Se retiró la tx del 19-abr etiquetada 'NiriumVault - revoke_agent(1218)'. - // El hash era real y la cuenta fue nuestra, pero el contrato invocado era - // CAU2XBJT… - el vault VIEJO, retirado en la consolidación a 2 contratos de - // mayo. O sea: la etiqueta nombraba un contrato que no es el que publicamos, - // y quien hiciera clic para verificar encontraría una dirección que no cuadra. - // En su lugar va la evidencia más fuerte que tenemos, y es de agosto: - // el agente invirtiendo fondos ajenos dentro de una bóveda de la que no - // puede sacarlos. - { net: 'testnet' as const, date: '2026-08-05', tx: 'c53d474658898af7ebbb84d17845902572147cfe1fb72965833e3d4cf7552ed3', msg: 'DeFindex vault - Invest signed by the agent, not the owner' }, - // 12-nov-2026: el texto de arriba remite aquí para "ejecuciones reales" de mainnet y no había - // ninguna. rebalance() en Horizon, SUCCESS, 2026-08-06T00:56:39Z. - { net: 'mainnet' as const, date: '2026-08-06', tx: '82d73f537e907140367f9343f63a36704c74a5286aced7a938cee8fffb56b3d4', msg: 'DeFindex rebalance() on mainnet - team funds, our own vault' }, // 16-nov-2026: el Policy Gate no publica contadores; su única evidencia es esta corrida // de testnet (Horizon: SUCCESS, 2026-10-01T01:20:42Z). Los casos DENY y stale no firmaron nada. { net: 'testnet' as const, date: '2026-10-01', tx: 'eefd57995733c29fd1ba8244b783419015af642073e9c918a0d732a6bb81a6b3', msg: 'Policy Gate - ALLOW signed and settled (0.02 USDC); the DENY and stale cases in the same run signed nothing' }, @@ -463,9 +311,9 @@ export default function AnalyticsPage() { ))} -

- {language === 'es' ? 'El registro completo está en el dashboard' : 'Full audit trail in the dashboard'} -

+ + {language === 'es' ? 'Toda la evidencia en EVIDENCE.md' : 'All the evidence in EVIDENCE.md'} + @@ -518,6 +366,8 @@ export default function AnalyticsPage() { + +
); diff --git a/apps/web/app/(app)/blog/bbva-open-deal-room/layout.tsx b/apps/web/app/(app)/blog/bbva-open-deal-room/layout.tsx index 437bce49..7feff8bb 100644 --- a/apps/web/app/(app)/blog/bbva-open-deal-room/layout.tsx +++ b/apps/web/app/(app)/blog/bbva-open-deal-room/layout.tsx @@ -4,7 +4,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/blog/bbva-open-deal-room", title: "Nirium at The Open Deal Room by Stellar", - description: "We were one of six Stellar startups featured at La Arena inside BBVA Tower CDMX. Here is what we showed, who was in the room, and why an autonomous treasury agent belongs in front of institutional investors.", + description: "We were one of six Stellar startups featured at La Arena inside BBVA Tower CDMX. Here is what we showed and who was in the room.", }); export default function BbvaOpenDealRoomLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/layout.tsx b/apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/layout.tsx deleted file mode 100644 index a48c2118..00000000 --- a/apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/layout.tsx +++ /dev/null @@ -1,12 +0,0 @@ -import { pageMetadata } from "@/lib/pageMetadata"; - -// page.tsx es "use client": sin este layout el post salía con el título de la home. -export const metadata = pageMetadata({ - path: "/blog/codigo-402-agentes-que-pagan", - title: "Código 402: Agentes que pagan - free Stellar x402 bootcamp", - description: "Your code has never charged you a dime. A free, 5-session bootcamp (BAF x Stellar x Nirium) where you build an API that charges per call and an agent that pays on its own, on Stellar testnet.", -}); - -export default function Codigo402Layout({ children }: { children: React.ReactNode }) { - return children; -} diff --git a/apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/page.tsx b/apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/page.tsx deleted file mode 100644 index 4f16856a..00000000 --- a/apps/web/app/(app)/blog/codigo-402-agentes-que-pagan/page.tsx +++ /dev/null @@ -1,261 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { - ArrowLeft, - Calendar, - Clock, - Gift, - MonitorSmartphone, - Code2, - Bot, - FileCheck2, - GraduationCap, - UserCheck, - Sparkles, - Server, - ShoppingCart, - Network, - Receipt, -} from "lucide-react"; -import { motion } from "framer-motion"; -import { useLanguage } from "../../../../context/LanguageContext"; -import { posts } from "../posts"; - -const SLUG = "codigo-402-agentes-que-pagan"; -const STEPS = [ - { key: "step1", Icon: Code2 }, - { key: "step2", Icon: Bot }, - { key: "step3", Icon: FileCheck2 }, -] as const; - -const FACTS = [ - { key: "fact_date", Icon: Calendar }, - { key: "fact_time", Icon: Clock }, - { key: "fact_mode", Icon: MonitorSmartphone }, - { key: "fact_cost", Icon: Gift }, -] as const; - -const LEARN_ITEMS = ["learn1", "learn2", "learn3", "learn4", "learn5"] as const; - -const BUILD_CARDS = [ - { key: "build1", Icon: Server }, - { key: "build2", Icon: ShoppingCart }, - { key: "build3", Icon: Network }, - { key: "build4", Icon: Receipt }, -] as const; - -export default function Codigo402Post() { - const { t } = useLanguage(); - const meta = (t.blog.posts as Record)[SLUG]; - const postMeta = posts.find((p) => p.slug === SLUG)!; - const readLabel = `${postMeta.readMinutes} ${t.blog.min_read}`; - - return ( -
-
-
- - - - - {t.blog.back_to_blog} - - -
- - {meta.tag} - - {readLabel} -
- -

- {meta.h1} -

- -

- {meta.hook} -

- - {/* Facts strip */} -
- {FACTS.map(({ key, Icon }) => ( - - {meta[key]} - - ))} -
-
- - -

{meta.p_curiosity}

- -

{meta.h_why}

-

{meta.p_why1}

-

{meta.p_why2}

- -

{meta.h_who}

-
-
-
- -
-

{meta.who_dev_title}

-

{meta.who_dev_body}

-
-
-
- -
-

{meta.who_nondev_title}

-

{meta.who_nondev_body}

-
-
- -

{meta.h_steps}

- - {/* 3-step diagram */} -
- {STEPS.map(({ key, Icon }, i) => ( -
-
- - {`0${i + 1}`} -
-

- {meta[`${key}_title`]} -

-

- {meta[`${key}_body`]} -

-
- ))} -
- -

{meta.p_risk}

-

{meta.p_identity}

- -

- - {meta.h_learn} -

-
    - {LEARN_ITEMS.map((key) => ( -
  • - - {meta[key]} -
  • - ))} -
- -

{meta.h_sessions}

-

{meta.p_sessions}

- -

{meta.h_build}

-
- {BUILD_CARDS.map(({ key, Icon }) => ( -
-
- -
-

- {meta[`${key}_title`]} -

-

- {meta[`${key}_body`]} -

-
- ))} -
- -
- - - {meta.build_cta_label} - -
- -
-
- - {meta.where_label} -
-

{meta.where_body}

-
- - {/* Roadmap note: honest "not built yet" disclosure */} -
-
- - {meta.roadmap_label} -
-

{meta.roadmap_body}

-
- - {/* Verify CTA + Luma registration, both as plain buttons (the embedded iframe broke under ad-blockers) */} -
-

{meta.verify_body}

- - - {meta.verify_cta_label} - -

{meta.cta_urgency}

- - {meta.cta_label} - -
-
- - - - - {t.blog.all_articles} - - - {t.blog.see_product} - - -
-
- ); -} diff --git a/apps/web/app/(app)/blog/page.tsx b/apps/web/app/(app)/blog/page.tsx index fbc1b234..92621e6b 100644 --- a/apps/web/app/(app)/blog/page.tsx +++ b/apps/web/app/(app)/blog/page.tsx @@ -48,7 +48,7 @@ export default function BlogPage() {
- {posts.map((post, i) => { + {posts.filter((p) => !p.hidden).map((post, i) => { const meta = (t.blog.posts as Record)[post.slug]; if (!meta) return null; return ( diff --git a/apps/web/app/(app)/blog/posts.ts b/apps/web/app/(app)/blog/posts.ts index 36063e52..bb9bedbf 100644 --- a/apps/web/app/(app)/blog/posts.ts +++ b/apps/web/app/(app)/blog/posts.ts @@ -10,14 +10,11 @@ export interface BlogPostMeta { readMinutes: number; /** Entries that live outside /blog/ (21-nov-2026, NAV2: the workshop recap). */ href?: string; + /** Kept for its own page (reachable by URL) but left out of the blog list and the sitemap. */ + hidden?: boolean; } export const posts: BlogPostMeta[] = [ - { - slug: "codigo-402-agentes-que-pagan", - date: "2026-11-06", - readMinutes: 4, - }, { slug: "workshop-audit-trail-recap", date: "2026-10-30", @@ -34,11 +31,6 @@ export const posts: BlogPostMeta[] = [ date: "2026-09-14", readMinutes: 6, }, - { - slug: "treasury-node-verify-it-yourself", - date: "2026-08-31", - readMinutes: 7, - }, { slug: "bbva-open-deal-room", date: "2026-05-21", diff --git a/apps/web/app/(app)/blog/treasury-node-verify-it-yourself/layout.tsx b/apps/web/app/(app)/blog/treasury-node-verify-it-yourself/layout.tsx deleted file mode 100644 index 542b056a..00000000 --- a/apps/web/app/(app)/blog/treasury-node-verify-it-yourself/layout.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import { pageMetadata } from "@/lib/pageMetadata"; - -// page.tsx es "use client": la metadata va en este layout. pageMetadata pone -// canonical, og:url y la tarjeta propia de lib/og/sections.ts. -export const metadata = pageMetadata({ - path: "/blog/treasury-node-verify-it-yourself", - title: "The Treasury Node on Mainnet: Don't Trust Us, Verify the Contract", - description: - "Nirium's agent holds the RebalanceManager role on a real DeFindex vault on Stellar mainnet, and the vault's own contract code makes withdrawal structurally impossible for that role, not just against our policy. Here is the transaction, the exact line of source code that proves it, and what it means for everyone involved.", - absoluteTitle: true, -}); - -export default function TreasuryNodeVerifyItYourselfLayout({ children }: { children: React.ReactNode }) { - return children; -} diff --git a/apps/web/app/(app)/blog/treasury-node-verify-it-yourself/page.tsx b/apps/web/app/(app)/blog/treasury-node-verify-it-yourself/page.tsx deleted file mode 100644 index cf38e46f..00000000 --- a/apps/web/app/(app)/blog/treasury-node-verify-it-yourself/page.tsx +++ /dev/null @@ -1,226 +0,0 @@ -"use client"; - -import Link from "next/link"; -import { - ArrowLeft, - Calendar, - Link2, - ShieldCheck, - ExternalLink, - Layers, - Landmark, - Globe, - Users, - Award, -} from "lucide-react"; -import { motion } from "framer-motion"; -import { useLanguage } from "../../../../context/LanguageContext"; -import { posts } from "../posts"; - -const SLUG = "treasury-node-verify-it-yourself"; - -const EVIDENCE_LINKS = [ - { - key: "evidence_tx_label", - href: "https://stellar.expert/explorer/public/tx/82d73f537e907140367f9343f63a36704c74a5286aced7a938cee8fffb56b3d4", - mono: "82d73f53…6b3d4", - }, - { - key: "evidence_vault_label", - href: "https://stellar.expert/explorer/public/contract/CAMDXG6L4LXLXXV675KZSHM3BMSETZ4NVMC7JYIQCZ2JTG54OMSK57MH", - mono: "CAMDXG6L…57MH", - }, - { - key: "evidence_strategy_label", - href: "https://stellar.expert/explorer/public/contract/CAZ3LLLKPWEOVK6K4G5NCQ2VXWABLFIPKKNMN5GLKMZKEN7JSKTEMIKN", - mono: "CAZ3LLLK…MIKN", - }, - { - key: "evidence_source_label", - href: "https://github.com/paltalabs/defindex/blob/a0fcabfae38f1c7b0c9c2f10ff51d225f8edc2f1/apps/contracts/vault/src/lib.rs#L846-L903", - mono: "vault/src/lib.rs#L846", - }, - { - key: "evidence_roles_label", - href: "https://docs.defindex.io/getting-started/vault-roles", - mono: "docs.defindex.io", - }, - { - key: "evidence_audit_label", - href: "https://github.com/paltalabs/defindex/blob/main/audits/2025_03_18_ottersec_defindex_audit.pdf", - mono: "OtterSec, Mar 2025", - }, -]; - -const IMPACT_CARDS = [ - { key: "defindex", Icon: Layers }, - { key: "etherfuse", Icon: Landmark }, - { key: "ottersec", Icon: ShieldCheck }, - { key: "stellar", Icon: Globe }, - { key: "clients", Icon: Users }, - { key: "nirium", Icon: Award }, -] as const; - -export default function TreasuryNodeVerifyItYourselfPost() { - const { t, language } = useLanguage(); - const meta = (t.blog.posts as Record)[SLUG]; - const postMeta = posts.find((p) => p.slug === SLUG)!; - const readLabel = `${postMeta.readMinutes} ${t.blog.min_read}`; - - return ( -
-
-
- - - - - {t.blog.back_to_blog} - - -
- - {meta.tag} - - {readLabel} -
- -

- {meta.h1} -

- -
- - {meta.fact_date} - - - {meta.fact_network} - - - {meta.fact_role} - -
-
- - -

{meta.p1}

-

{meta.p2}

- -

{meta.h_fact}

-

{meta.fact_p1}

- - {/* Evidence box */} -
-
- {meta.evidence_label} -
- -
- -

{meta.fact_p2}

-

{meta.fact_p3}

- -

{meta.h_why}

-

{meta.why_p1}

-

- {meta.why_p2} -

- -

{meta.h_impact}

-

{meta.impact_intro}

- - {/* Impact grid */} -
- {IMPACT_CARDS.map(({ key, Icon }) => ( -
-
- -

- {meta[`impact_${key}_h`]} -

-
-
- {(meta[`impact_${key}_p`] as string) - .split("\n\n") - .map((para, i) => ( -

- {para} -

- ))} -
-
- ))} -
- -

{meta.regulatory_map_p}

- -

{meta.h_close}

-

{meta.close_p1}

- -
-
- - {meta.where_label} -
-

{meta.where_body}

-
-
- - - - - {t.blog.all_articles} - - - {t.blog.see_product} - - -
-
- ); -} diff --git a/apps/web/app/(app)/build/layout.tsx b/apps/web/app/(app)/build/layout.tsx index e2cb9996..5feeecc8 100644 --- a/apps/web/app/(app)/build/layout.tsx +++ b/apps/web/app/(app)/build/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/build", title: "What You Can Build", - description: "Product ideas you can prototype on Nirium's payment, audit and execution rails, most of them live on Stellar testnet today.", + description: "Product ideas you can prototype on Nirium's receipts, Reporting and x402, most of them live on Stellar testnet today.", }); export default function BuildLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/build/page.tsx b/apps/web/app/(app)/build/page.tsx index 2baf35db..3b8368a0 100644 --- a/apps/web/app/(app)/build/page.tsx +++ b/apps/web/app/(app)/build/page.tsx @@ -5,9 +5,9 @@ import { motion } from "framer-motion"; import { Rocket, Bot, Wallet, Gift, Wand2, ScrollText, PlayCircle, Clock, Code2, ArrowRight, Globe, Zap, Layers, Webhook, - KeyRound, Send, Coins, Radio, LineChart, Brain, Trophy, + KeyRound, Send, Coins, Radio, Brain, Trophy, Terminal as TerminalIcon, Package, Github, Shield, - Landmark, ShieldCheck, Image, Database, Handshake, Cpu + Landmark, Image, Database, Cpu } from "lucide-react"; import { useLanguage } from "@/context/LanguageContext"; @@ -19,46 +19,35 @@ const fadeUp = (delay = 0) => ({ }); const STARTUP_CARDS = [ - { id: "global_payroll", icon: Globe, accent: "#2DEBE8" }, + // 27-nov-2026: primero las ideas sobre Audit Trail y x402; las de Tesorería y Payouts al final + // (por invitación). Fuera "Router de Capital Autónomo": era una app para consumidores que mueve su + // capital, y Nirium es B2B (su texto sigue en los diccionarios, sin usarse). { id: "m2m_exchange", icon: Zap, accent: "#FFD700" }, - { id: "forensic_treasury", icon: Shield, accent: "#34D399" }, - { id: "savings_neobank", icon: LineChart, accent: "#EC4899" }, - { id: "grant_distributor", icon: Trophy, accent: "#A78BFA" }, { id: "logistics_settle", icon: Send, accent: "#F97316" }, - { id: "energy_grid", icon: Cpu, accent: "#10B981" }, - { id: "rwa_market", icon: Landmark, accent: "#FBBF24" }, - { id: "defi_insurance", icon: ShieldCheck, accent: "#EF4444" }, { id: "content_license", icon: Image, accent: "#8B5CF6" }, { id: "oracle_bridge", icon: Database, accent: "#3B82F6" }, - { id: "escrow_fleet", icon: Handshake, accent: "#6366F1" }, + { id: "energy_grid", icon: Cpu, accent: "#10B981" }, + { id: "grant_distributor", icon: Trophy, accent: "#A78BFA" }, ] as const; // 21-nov-2026 (B1): rutas comprobadas en main ese día (#373, #412, #389, #411, #422 mergeados). // Grants Autónomos entra cuando #419 se mergee. const COMMUNITY_EXAMPLES: Record = { - global_payroll: { dir: 'payouts-batch-testnet' }, oracle_bridge: { dir: 'build-oracle-x402' }, - defi_insurance: { dir: 'build-risk-signals' }, logistics_settle: { dir: 'build-smart-settlement' }, grant_distributor: { dir: 'build-autonomous-grants' }, m2m_exchange: { dir: 'openai-agents-x402', related: { en: 'an agent that pays x402 with a cap', es: 'un agente que paga x402 con tope' } }, }; const API_ENDPOINTS = [ - // 21-nov-2026 (B2): `auth` marca las rutas que piden key, igual que /developers (probado ese día: - // /api/webhooks, /api/auth/keys y /api/payroll/run dan 401 sin key). - { id: "auth", icon: KeyRound, path: "/api/auth/keys", method: "POST", auth: "key" }, - { id: "market", icon: LineChart, path: "/api/market", method: "GET", auth: "key" }, - { id: "exec", icon: TerminalIcon, path: "/api/execute", method: "POST", auth: "signer" }, - { id: "skills", icon: Brain, path: "/api/skills", method: "GET" }, - // market es el único endpoint x402 que cobra en mainnet; signals es solo testnet. + // 27-nov-2026: Audit Trail y x402 primero. 30-nov-2026: Tesorería y Payouts archivados, fuera. + // 1-dic-2026: fuera también market, execute (410) y webhooks (sus eventos eran del loop y la ejecución). + // `auth` marca las rutas que piden key (probado el 21-nov-2026: webhooks, auth/keys y payroll/run dan 401 sin key). + { id: "audit", icon: ScrollText, path: "/api/audit/log", method: "POST" }, { id: "billing", icon: Coins, path: "/api/v1/premium/market", method: "GET" }, { id: "settle", icon: Send, path: "/api/v1/mpp/signals", method: "GET" }, - { id: "vault", icon: Landmark, path: "/api/treasury/vaults", method: "GET" }, - { id: "audit", icon: ScrollText, path: "/api/audit/log", method: "POST" }, - { id: "payroll", icon: Wallet, path: "/api/payroll/run", method: "POST", auth: "key" }, - { id: "webhooks", icon: Webhook, path: "/api/webhooks", method: "POST", auth: "key" }, - // Las 10 rutas comprobadas contra packages/agent/src el 9-nov-2026. + { id: "auth", icon: KeyRound, path: "/api/auth/keys", method: "POST", auth: "key" }, + { id: "skills", icon: Brain, path: "/api/skills", method: "GET" }, ]; const SDK_ICONS: Record = { @@ -69,7 +58,6 @@ const SDK_HREFS: Record = { ts: 'https://www.npmjs.com/package/nirium', py: 'https://pypi.org/project/nirium/', mcp: 'https://www.npmjs.com/package/nirium-mcp', - studio: '/treasury/builder', }; export default function BuildPage() { @@ -407,26 +395,22 @@ export default function BuildPage() { {" "}apiKey: 'sk_free_...',{"\n"} {" "}baseUrl: 'https://nirium-agent.fly.dev', // testnet node{"\n"} {"}"});{"\n\n"} -// 1. Deploy a treasury vault. This returns an UNSIGNED xdr.{"\n"} -// You sign it with YOUR OWN key; Nirium never holds it.{"\n"} -const vault = await nirium.deployTreasuryVault({"{"}{"\n"} -{" "}caller: 'G...', manager: 'G...',{"\n"} -{"}"});{"\n"} -// vault.xdr: sign with `caller`, then submitTreasuryTx(signedXdr){"\n\n"} +// 1. Anchor the hash of a record only you hold (Audit Trail){"\n"} +const receipt = await nirium.anchorAuditRecord({"{"} hash: '<sha-256 of your record>', tag: 'my-app' {"}"});{"\n"} +// receipt.cid: anyone can check it at nirium.xyz/verify{"\n\n"} // 2. Pay for an x402-protected API from your own wallet{"\n"} // (to charge for YOUR API, see x402Serve() in the docs){"\n"} nirium.initX402({"{"} secretKey: process.env.STELLAR_SECRET_KEY {"}"});{"\n"} const res = await nirium.x402Fetch('https://your-api.com/paid-endpoint');{"\n\n"} -// 3. Anchor the hash of a record only you hold (Audit Trail){"\n"} -const receipt = await nirium.anchorAuditRecord({"{"} hash: '<sha-256 of your record>', tag: 'my-app' {"}"});{"\n"} -// receipt.cid: anyone can check it at nirium.xyz/verify +// 3. Reporting: payments and receipts for a network{"\n"} +const summary = await nirium.getReportingSummary({"{"} network: 'testnet' {"}"}); {/* SDK cards */} - {(Object.keys(ah.sdks) as Array).map((key) => { + {(Object.keys(ah.sdks) as Array).filter((key) => key !== 'studio').map((key) => { const sdk = ah.sdks[key]; const IconComp = SDK_ICONS[key as string] || Package; const href = SDK_HREFS[key as string]; diff --git a/apps/web/app/(app)/chains/layout.tsx b/apps/web/app/(app)/chains/layout.tsx new file mode 100644 index 00000000..f82ea621 --- /dev/null +++ b/apps/web/app/(app)/chains/layout.tsx @@ -0,0 +1,11 @@ +import { pageMetadata } from "@/lib/pageMetadata"; + +export const metadata = pageMetadata({ + path: "/chains", + title: "Chains", + description: "What works on Stellar, Solana, Avalanche, Base and Arbitrum, feature by feature: receipts, verification, x402, the pre-sign policy, Reporting and the markets.", +}); + +export default function ChainsLayout({ children }: { children: React.ReactNode }) { + return children; +} diff --git a/apps/web/app/(app)/chains/page.tsx b/apps/web/app/(app)/chains/page.tsx new file mode 100755 index 00000000..c9435a54 --- /dev/null +++ b/apps/web/app/(app)/chains/page.tsx @@ -0,0 +1,395 @@ +/** Nirium - Chains: what works on Stellar, Solana, Avalanche, Base and Arbitrum, feature by feature. One page, so a + * visitor does not have to visit three sites to learn where each thing runs. Every "Mainnet" here was + * checked live on 27-nov-2026 (markets' /v1/market/info, the node's /api/reporting/summary per chain, + * npm exports). Keep it that way: a row changes only when the thing itself changes. **/ +'use client'; + +import { Check, Minus, Clock, ExternalLink, ArrowRight } from "lucide-react"; +import { useEffect, useState } from "react"; +import { useLanguage } from "@/context/LanguageContext"; + +type State = "yes" | "no" | "soon"; +type Cell = { state: State; en: string; es: string; href?: string }; +type Row = { en: string; es: string; cells: [Cell, Cell, Cell, Cell, Cell] }; + +const CHAINS = [ + { id: "stellar", name: "Stellar", color: "#D4AF37", home: "/verify" }, + { id: "solana", name: "Solana", color: "#9945FF", home: "/solana" }, + { id: "avalanche", name: "Avalanche", color: "#E84142", home: "/avalanche" }, + { id: "base", name: "Base", color: "#0052FF", home: "/base" }, + { id: "arbitrum", name: "Arbitrum", color: "#28A0F0", home: "/arbitrum" }, +] as const; + +const y = (en: string, es: string, href?: string): Cell => ({ state: "yes", en, es, href }); +const n = (en = "Not on this chain", es = "No en esta red"): Cell => ({ state: "no", en, es }); + +const ROWS: Row[] = [ + { + en: "Payer-signed receipts, anchored to IPFS by Audit Trail", es: "Recibos firmados por quien paga, anclados en IPFS por Audit Trail", + cells: [ + y("Mainnet", "Mainnet"), + y("Mainnet", "Mainnet"), + y("Mainnet", "Mainnet"), + y("Mainnet", "Mainnet"), + y("Mainnet", "Mainnet"), + ], + }, + { + en: "Receipt checked against the exact payment on-chain (amount, payer, receiver, asset)", es: "Recibo comprobado contra el pago exacto en la cadena (monto, quién paga, quién cobra, activo)", + cells: [ + n("Not yet: a receipt can name the transaction hash, but nothing checks it against the payment", "Todavía no: un recibo puede nombrar el hash de la transacción, pero nada lo compara con el pago"), + y("Mainnet, against the SPL transfer and its Memo", "Mainnet, contra la transferencia SPL y su Memo"), + y("Mainnet, against the USDC Transfer log and the EIP-3009 nonce", "Mainnet, contra el log Transfer de USDC y el nonce EIP-3009"), + y("Mainnet, against the USDC Transfer log and the EIP-3009 nonce", "Mainnet, contra el log Transfer de USDC y el nonce EIP-3009"), + y("Mainnet, against the USDC Transfer log and the EIP-3009 nonce", "Mainnet, contra el log Transfer de USDC y el nonce EIP-3009"), + ], + }, + { + en: "Order reference written on-chain with the payment", es: "Referencia del pedido escrita en la cadena junto al pago", + cells: [ + n("Not yet: an x402 payment carries no memo", "Todavía no: un pago x402 no lleva memo"), + y("Memo, from the X-Nirium-Ref header", "Memo, desde el header X-Nirium-Ref"), + n("No memo on EVM; the reference goes in the receipt", "En EVM no hay memo; la referencia va en el recibo"), + n("No memo on EVM; the reference goes in the receipt", "En EVM no hay memo; la referencia va en el recibo"), + n("No memo on EVM; the reference goes in the receipt", "En EVM no hay memo; la referencia va en el recibo"), + ], + }, + { + en: "Check a receipt in the browser", es: "Comprobar un recibo en el navegador", + cells: [ + y("nirium.xyz/verify", "nirium.xyz/verify", "/verify"), + y("nirium.xyz/solana; mainnet chain checks need your own RPC", "nirium.xyz/solana; en mainnet la parte de la cadena pide tu propio RPC", "/solana/explorer"), + y("nirium.xyz/avalanche, every check in the browser", "nirium.xyz/avalanche, todas las comprobaciones en el navegador", "/avalanche/explorer"), + y("nirium.xyz/base, every check in the browser", "nirium.xyz/base, todas las comprobaciones en el navegador", "/base/explorer"), + y("nirium.xyz/arbitrum, every check in the browser", "nirium.xyz/arbitrum, todas las comprobaciones en el navegador", "/arbitrum/explorer"), + ], + }, + { + en: "Check a receipt from a terminal", es: "Comprobar un recibo desde la terminal", + cells: [ + y("npx nirium-cli verify ", "npx nirium-cli verify "), + y("npx -p nirium-solana nirium-verify-svm receipt.json", "npx -p nirium-solana nirium-verify-svm receipt.json"), + y("npx -p nirium-avalanche nirium-verify-evm receipt.json", "npx -p nirium-avalanche nirium-verify-evm receipt.json"), + n("Not yet: the library is not on npm", "Todavía no: la librería no está en npm"), + n("Not yet: the library is not on npm", "Todavía no: la librería no está en npm"), + ], + }, + { + en: "Pay and charge per request with x402", es: "Pagar y cobrar por consulta con x402", + cells: [ + y("Mainnet on Nirium's own endpoint; for your API, testnet", "Mainnet en el endpoint propio de Nirium; para tu API, testnet"), + y("Mainnet on Nirium's own market, settled by an independent facilitator (PayAI); for your API, devnet", "Mainnet en el market propio de Nirium, liquidado por un facilitador independiente (PayAI); para tu API, devnet"), + y("Mainnet on Nirium's own market, settled by an independent facilitator (PayAI); for your API, Fuji", "Mainnet en el market propio de Nirium, liquidado por un facilitador independiente (PayAI); para tu API, Fuji"), + y("Mainnet on Nirium's own market, settled by an independent facilitator (PayAI); the library for your API is not on npm yet", "Mainnet en el market propio de Nirium, liquidado por un facilitador independiente (PayAI); la librería para tu API todavía no está en npm"), + y("Mainnet on Nirium's own market, settled by an independent facilitator (PayAI); the library for your API is not on npm yet", "Mainnet en el market propio de Nirium, liquidado por un facilitador independiente (PayAI); la librería para tu API todavía no está en npm"), + ], + }, + { + en: "Refuse a payment before it is signed (pre-sign policy)", es: "Rechazar un pago antes de firmarlo (política antes de firmar)", + cells: [y("In the library", "En la librería"), y("In the library", "En la librería"), y("In the library", "En la librería"), n("In the library, not on npm yet", "En la librería, todavía no en npm"), n("In the library, not on npm yet", "En la librería, todavía no en npm")], + }, + { + en: "Receipts for refused payments (DENY, WAIT)", es: "Recibos de pagos rechazados (DENY, WAIT)", + cells: [ + y("As Audit Trail receipts", "Como recibos de Audit Trail"), + y("Devnet, in nirium-solana 0.3.0", "Devnet, en nirium-solana 0.3.0"), + y("Fuji, in nirium-avalanche 0.3.0", "Fuji, en nirium-avalanche 0.3.0"), + n("Not yet", "Todavía no"), + n("Not yet", "Todavía no"), + ], + }, + { + en: "Reporting: receipts, payers and USDC declared, per chain", es: "Reporting: recibos, pagadores y USDC declarados, por red", + cells: [y("Mainnet", "Mainnet"), y("Mainnet", "Mainnet"), y("Mainnet", "Mainnet"), y("Mainnet", "Mainnet"), y("Mainnet", "Mainnet")], + }, + { + en: "An x402 market selling network data at $0.01", es: "Un market x402 que vende datos de la red a $0.01", + cells: [ + y("Paid endpoints on the Nirium node", "Endpoints de pago en el nodo de Nirium"), + y("Mainnet", "Mainnet", "https://nirium-market-solana.fly.dev/v1/market/info"), + y("C-Chain mainnet", "C-Chain mainnet", "https://nirium-market-avalanche.fly.dev/v1/market/info"), + y("Base mainnet", "Base mainnet", "https://nirium-market-base.fly.dev/v1/market/info"), + y("Arbitrum One", "Arbitrum One", "https://nirium-market-arbitrum.fly.dev/v1/market/info"), + ], + }, + { + en: "ERC-8004: a validation request that points to a receipt", es: "ERC-8004: una solicitud de validación que apunta a un recibo", + cells: [n(), n(), y("Fuji", "Fuji"), n(), n()], + }, + { + en: "MCP server for agents", es: "Servidor MCP para agentes", + cells: [y("nirium-mcp", "nirium-mcp"), n("Not yet", "Todavía no"), n("Not yet", "Todavía no"), n("Not yet", "Todavía no"), n("Not yet", "Todavía no")], + }, + { + en: "Package", es: "Paquete", + cells: [ + y("nirium (npm, PyPI)", "nirium (npm, PyPI)", "https://www.npmjs.com/package/nirium"), + y("nirium-solana", "nirium-solana", "https://www.npmjs.com/package/nirium-solana"), + y("nirium-avalanche", "nirium-avalanche", "https://www.npmjs.com/package/nirium-avalanche"), + n("nirium-base, not published yet", "nirium-base, todavía sin publicar"), + n("nirium-arbitrum, not published yet", "nirium-arbitrum, todavía sin publicar"), + ], + }, +]; + +function Mark({ state }: { state: State }) { + if (state === "yes") return
@@ -76,6 +76,12 @@ export default function CocPage() { <>La comunidad, los desarrolladores y el ecosistema de Nirium Protocol siguen el Código de Conducta de Stellar. Queremos un ambiente acogedor, profesional y transparente para todos. )}

+

+ {t( + "Nirium also runs on Solana, Avalanche, Base and Arbitrum. In each ecosystem's own spaces (its Discord, forums and events) we follow that ecosystem's rules too; in Nirium's own spaces, the five principles below apply on every chain.", + "Nirium también corre en Solana, Avalanche, Base y Arbitrum. En los espacios de cada ecosistema (su Discord, sus foros y eventos) seguimos además sus propias reglas; en los espacios de Nirium aplican los cinco principios de abajo, en todas las redes." + )} +

{t( - <>When taking part in our Discord, our GitHub repositories, our events (such as Código 402) or our social channels, everyone is expected to:, - <>Al participar en nuestro Discord, en nuestros repositorios de GitHub, en nuestros eventos (como Código 402) o en nuestras redes, se espera que cada persona: + <>When taking part in our Discord, our GitHub repositories, our events or our social channels, everyone is expected to:, + <>Al participar en nuestro Discord, en nuestros repositorios de GitHub, en nuestros eventos o en nuestras redes, se espera que cada persona: )}

  • {t("Use welcoming and inclusive language.", "Use un lenguaje acogedor e inclusivo.")}
  • diff --git a/apps/web/app/(app)/compliance/page.tsx b/apps/web/app/(app)/compliance/page.tsx index 97ef43e2..0b8dc1e1 100644 --- a/apps/web/app/(app)/compliance/page.tsx +++ b/apps/web/app/(app)/compliance/page.tsx @@ -254,6 +254,10 @@ export default function CompliancePage() {

    {t.compliance_page.preview.note}

    +

    + {language === 'es' ? 'Sin terminal: descárgalo en CSV o JSON desde ' : 'No terminal: download it as CSV or JSON from '} + Reporting. +

@@ -267,7 +271,7 @@ export default function CompliancePage() {

- {language === 'es' ? 'Última actualización: 21 de noviembre de 2026' : 'Last updated: November 21, 2026'} + {language === 'es' ? 'Última actualización: 1 de diciembre de 2026' : 'Last updated: December 1, 2026'}

diff --git a/apps/web/app/(app)/dashboard/layout.tsx b/apps/web/app/(app)/dashboard/layout.tsx index 49b5801a..34dd0949 100644 --- a/apps/web/app/(app)/dashboard/layout.tsx +++ b/apps/web/app/(app)/dashboard/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/dashboard", title: "Dashboard", - description: "The Nirium operator dashboard: the agent's execution feed, vault state and Audit Trail receipts (anchored on IPFS).", + description: "The Nirium dashboard: activity per node, Audit Trail receipts (anchored on IPFS) and x402 settlements.", }); export default function DashboardLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/dashboard/page.tsx b/apps/web/app/(app)/dashboard/page.tsx index fe9f44a2..c46a64e5 100644 --- a/apps/web/app/(app)/dashboard/page.tsx +++ b/apps/web/app/(app)/dashboard/page.tsx @@ -1,3354 +1,50 @@ -// @ts-nocheck 'use client'; -import { SectionBrandLogo } from "@/components/ui/SectionBrandLogo"; +/** /dashboard - 30-nov-2026: Tesorería y Payouts archivados. Antes esta página era casi + * entera herramientas de NiriumVault (crear, fondear, delegar al agente) y su feed; eso + * salió con el archivo. Quedan la actividad por nodo y los recibos y cobros. **/ -import { Suspense, useState, useEffect, useMemo, useRef } from "react"; -import { motion, AnimatePresence } from "framer-motion"; -import { Canvas } from "@react-three/fiber"; -import { Float, Sphere, MeshTransmissionMaterial } from "@react-three/drei"; -import { CanvasErrorBoundary } from "@/components/3d/CanvasErrorBoundary"; -import Link from 'next/link'; -import { useFreighter } from "@/hooks/useFreighter"; -import { TransactionBuilder, Networks, Asset, Operation, Keypair } from "@stellar/stellar-sdk"; -import { toast } from "sonner"; -import { useRouter, useSearchParams } from "next/navigation"; -import { ExternalLink, Shield, X, AlertTriangle, Trash2, Info, ChevronRight, RefreshCw, Zap, Plus, Code, Cpu, Filter, Download, Activity, StopCircle, Database, Globe } from "lucide-react"; -import ProtocolRevenue from "@/components/dashboard/ProtocolRevenue"; -import PaymentStreams from "@/components/dashboard/PaymentStreams"; -import TelemetryFeed from "@/components/dashboard/TelemetryFeed"; -import { writeLog } from "@/lib/logger"; -import { stellarClient } from "@/lib/stellarClient"; -import { useVault } from "@/hooks/useNiriumContracts"; -import { getWebSocketUrl } from "@/lib/constants"; -import { simulateSorobanTx } from "@/lib/stellarSim"; -import { handleWalletError } from "@/components/wallet/WalletErrorHandler"; -import { NATIVE_ASSET_ID, USDC_ASSET_ID, CETES_ASSET_ID, vaultDeposit, vaultWithdraw, vaultCreate, vaultClose, vaultRevokeAgent, vaultDelegateAgent, vaultGetVaultCount, CETES_ASSET, getCETESBalance, hasCETESTrustline } from "@/lib/sorobanContracts"; -import { generateOnboardingUrl, getOrCreateCustomerIds } from "@/lib/etherfuseApi"; -import MarketTicker from "@/components/dashboard/MarketTicker"; +import { SectionBrandLogo } from "@/components/ui/SectionBrandLogo"; +import { ComplianceBanner } from "@/components/ui/ComplianceBanner"; import AuditTrailViewer from "@/components/dashboard/AuditTrailViewer"; -import ProtocolKernel from "@/components/dashboard/ProtocolKernel"; -import StatusBadge from "@/components/ui/StatusBadge"; -import { useLanguage } from "@/context/LanguageContext"; import NodeActivity from "@/components/analytics/NodeActivity"; import ReceiptsSettlements from "@/components/analytics/ReceiptsSettlements"; +import { useLanguage } from "@/context/LanguageContext"; import { useNetwork } from "@/context/NetworkContext"; -import NetworkScopeNote from "@/components/shared/NetworkScopeNote"; - -import { ComplianceBanner } from "@/components/ui/ComplianceBanner"; - -// WebSocket hook removed as it was unused and redundant - -function ProtocolKernelSmall() { - return ( - - { - gl.domElement.addEventListener('webglcontextlost', (e: Event) => { - e.preventDefault(); - }, false); - }} - > - - - - - - - - - - - - ); -} -function DashboardContent() { +export default function Dashboard() { const { t, language } = useLanguage(); - // Textos fijos del panel en el idioma elegido. - const L = (en: string, es: string) => (language === 'es' ? es : en); - const router = useRouter(); - const searchParams = useSearchParams(); - const { address: accountStr, isConnected, connect, disconnect } = useFreighter(); - const account = useMemo(() => isConnected && accountStr ? { address: accountStr, chains: ['stellar:testnet'] } : null, [isConnected, accountStr]); - // Helper: Sign transaction with Freighter and submit to Horizon. - const signAndSubmitTransaction = async ({ transaction }: { transaction: any }): Promise<{ hash: string }> => { - const { signTransaction } = await import("@stellar/freighter-api"); - const { Horizon, Networks, TransactionBuilder } = await import("@stellar/stellar-sdk"); - - console.log("Signing XDR via Freighter..."); - const txXdr = transaction.toXDR(); - - // Let Freighter sign the Transaction - const response = await signTransaction(txXdr, { - networkPassphrase: Networks.TESTNET, - address: transaction.source, // Ensure Freighter signs with the transaction's source account - } as any); - - if (response.error) { - throw new Error(response.error as string); - } - - // Submit the signed transaction via Horizon - const server = new Horizon.Server("https://horizon-testnet.stellar.org"); - const signedTx = TransactionBuilder.fromXDR(response.signedTxXdr, Networks.TESTNET); - - try { - const result = await server.submitTransaction(signedTx as any); - - if (!result.successful) { - throw new Error('Stellar Transaction failed on-chain'); - } - - return { hash: result.hash }; - } catch (e: any) { - console.error("Horizon Submission Error:", e.response?.data || e); - if (e.response?.data?.extras?.result_codes) { - const codes = e.response.data.extras.result_codes; - throw new Error(`Horizon rejected Tx: ${codes.transaction} - Operations: ${codes.operations?.join(', ')}`); - } - throw e; - } - }; - - // Helper: fetch current sequence number and build transaction - const buildStellarTransaction = async (accountId: string) => { - const { TransactionBuilder, Networks, Horizon } = await import("@stellar/stellar-sdk"); - const server = new Horizon.Server("https://horizon-testnet.stellar.org"); - const sourceAccount = await server.loadAccount(accountId); - return new TransactionBuilder(sourceAccount, { fee: "100", networkPassphrase: Networks.TESTNET }).setTimeout(300); - }; - - // Helper: fetch account or contract state from Horizon/Soroban - const getLiveAccountData = async (accountId: string) => { - const obj = await stellarClient.getObject({ id: accountId }); - if (!obj.data) throw new Error(`Account ${accountId} not found on Stellar network`); - return obj.data; - }; - const [showAutoStartModal, setShowAutoStartModal] = useState(false); - const [baseAsset, setBaseAsset] = useState<"XLM" | "USDC" | "CETES">("USDC"); - const getCoinType = () => baseAsset === "XLM" - ? "XLM" - : baseAsset === "CETES" - ? "CETES" - : "USDC"; - - const [selectedStrategy, setSelectedStrategy] = useState(null); // State for Details Modal - const [expandConsole, setExpandConsole] = useState(false); - - const [blendData, setBlendData] = useState<{ supplyApy: number, borrowApy: number } | null>(null); - const [phoenixData, setPhoenixData] = useState<{ supplyApy: number, borrowApy: number } | null>(null); - const [currentMarketState, setCurrentMarketState] = useState<{ etherfuseApy: number; baseFee: number; pathPaymentRoutes: any[] } | null>(null); - const [walletBalance, setWalletBalance] = useState(0); - const [cetesBalance, setCetesBalance] = useState('0'); - const [hasCetesTrust, setHasCetesTrust] = useState(false); - const [onChainVaultCount, setOnChainVaultCount] = useState(null); - const [onChainTotalFees, setOnChainTotalFees] = useState(null); - const [globalActiveAgents, setGlobalActiveAgents] = useState(null); - // Empieza vacío: antes traía tres mensajes de demo ("Strategic execution - // network online...") que se veían igual que logs reales y se quedaban si - // /api/logs fallaba. TelemetryFeed ya tiene su propio estado vacío. - const [thoughts, setThoughts] = useState([]); - const vault = useVault(); - - // Fetch live on-chain data from Soroban RPC - useEffect(() => { - const fetchOnChainData = async () => { - try { - const [count, fees] = await Promise.all([ - vault.getVaultCount(), - vault.getTotalFees(), - ]); - setOnChainVaultCount(count); - setOnChainTotalFees(fees / 10_000_000); - } catch (e) { - console.warn('[Dashboard] On-chain data fetch failed:', e); - } - }; - fetchOnChainData(); - }, [accountStr]); - - // Fetch global active agents count from Supabase - useEffect(() => { - const fetchGlobalAgents = async () => { - try { - const { supabase } = await import('@/lib/supabase'); - const { count } = await supabase - .from('nirium_protocol_records') - .select('*', { count: 'exact', head: true }) - .eq('record_type', 'STRATEGY') - .eq('status', 'RUNNING'); - setGlobalActiveAgents(count ?? 0); - } catch { - setGlobalActiveAgents(null); - } - }; - fetchGlobalAgents(); - }, []); - - // Fetch telemetry from /api/logs (combines agent_logs + activity + Horizon), polling every 8s - useEffect(() => { - const fetchThoughts = async () => { - try { - const res = await fetch('/api/logs'); - const data = await res.json(); - if (!Array.isArray(data) || data.length === 0) return; - setThoughts(data.slice(0, 20).map((d: any) => ({ - id: d.id, - agent: d.agent_id ?? 'CORE', - content: d.message ?? '', - timestamp: d.created_at ?? new Date().toISOString(), - type: (d.level === 'error' || d.level === 'warn') ? 'security' : 'execution', - }))); - } catch { - // silently ignore - empty state handles it - } - }; - fetchThoughts(); - // Nothing while the tab is in the background: each poll is a server function run on Vercel. - const interval = setInterval(() => { if (document.visibilityState === 'visible') fetchThoughts(); }, 8000); - return () => clearInterval(interval); - }, []); - - const [vaultBalance, setVaultBalance] = useState(0); - const [vaultId, setVaultId] = useState(null); - // 16-nov-2026: Treasury (bóveda de testnet) va plegado debajo de recibos y cobros. - // Se abre solo si ya tienes bóveda o si llegas desde el builder con una estrategia. const { network: uiNet } = useNetwork(); - const [treasuryOpen, setTreasuryOpen] = useState(false); - const [autoRebalance, setAutoRebalance] = useState(false); - const [autoRebalanceLoading, setAutoRebalanceLoading] = useState(false); - const [delegationId, setDelegationId] = useState(null); - const [autoExit, setAutoExit] = useState(false); - const [autoExitLoading, setAutoExitLoading] = useState(false); - const [delegationTxHash, setDelegationTxHash] = useState(null); - const [rebalanceThreshold, setRebalanceThreshold] = useState(2.5); - const [reverseThreshold, setReverseThreshold] = useState(2.0); - const [ownerCapId, setOwnerCapId] = useState(null); - const [amountInput, setAmountInput] = useState("0.1"); - const [installedSkills, setInstalledSkills] = useState([]); - - const tradingSkills = installedSkills.filter(s => s.category === 'trading' || s.category === 'defi'); - const activePlugins = installedSkills.filter(s => s.category !== 'trading' && s.category !== 'defi'); - const [isSkillsLoading, setIsSkillsLoading] = useState(false); - - const [confirmConfig, setConfirmConfig] = useState<{ - isOpen: boolean; - title: string; - description: React.ReactNode; - icon: React.ReactNode; - confirmText: string; - onConfirm: () => void; - type: 'danger' | 'info'; - }>({ - isOpen: false, - title: '', - description: '', - icon: null, - confirmText: '', - onConfirm: () => { }, - type: 'info' - }); - - // Fetch User Real Balance - useEffect(() => { - if (!account?.address) return; - - const fetchBalance = async () => { - try { - const { stellarClient } = await import("@/lib/stellarClient"); - const decimals = 10_000_000; // All Stellar / Soroban SAC assets use 7 decimals - const coinType = baseAsset === "XLM" - ? "XLM" - : "USDC"; - const balance = await stellarClient.getBalance({ owner: account.address, coinType }); - const total = Number(BigInt(balance.totalBalance)) / decimals; - setWalletBalance(total); - } catch (e) { - console.warn("Soft Error: Wallet Fetch Failed", e); - } - }; - - fetchBalance(); - const interval = setInterval(fetchBalance, 10000); // Poll every 10s - return () => clearInterval(interval); - }, [account, baseAsset]); - - // Fetch CETES Balance and Trustline Status - useEffect(() => { - if (!account?.address) return; - - const fetchCETESData = async () => { - try { - const [balance, trustlineStatus] = await Promise.all([ - getCETESBalance(account.address), - hasCETESTrustline(account.address) - ]); - setCetesBalance(balance); - setHasCetesTrust(trustlineStatus); - } catch (e) { - console.warn("CETES fetch failed:", e); - } - }; - - fetchCETESData(); - const interval = setInterval(fetchCETESData, 10000); // Poll every 10s - return () => clearInterval(interval); - }, [account]); - - // Fetch Vault Balance specifically - useEffect(() => { - if (!vaultId) { - setVaultBalance(0); - return; - } - - const fetchVaultBalance = async () => { - try { - if (vaultId) { - const vData = await vault.getVault(Number(vaultId)); - if (vData && vData.balance !== undefined) { - const realBalance = Number(BigInt(vData.balance)) / 10_000_000; - setVaultBalance(realBalance); - return; - } - } - - // Fallback: Read from local storage to keep demo state across refreshes if contract not ready - const storedBalance = localStorage.getItem(`nirium-vault-balance-${vaultId}-${baseAsset}`); - if (storedBalance) { - setVaultBalance(parseFloat(storedBalance)); - } else { - setVaultBalance(0); - } - } catch (e) { - console.warn("Soft Error: Vault Balance Scan Failed", e); - } - }; - - fetchVaultBalance(); - const interval = setInterval(fetchVaultBalance, 10000); - return () => clearInterval(interval); - }, [vaultId, baseAsset]); - - // Fetch Real Protocol Data - useEffect(() => { - const fetchProtocols = async () => { - try { - // Direct fetch to Protocol SDKs (Simulated for Demo Stability) - console.log("Connecting to Liquidity Protocols..."); - - // Simulation of network call latency - await new Promise(r => setTimeout(r, 1000)); - - // In a full production app we would use: - // const blend = new BlendSDK({ networkType: 'testnet' }); - // const market = await blend.queryMarket(); - // setBlendData(market.stellar.apy); - - // Blend/Phoenix rates not used in main stats - CETES rate from Etherfuse is the reference - // These remain available for the Strategy Builder internal calculations - setBlendData({ supplyApy: 0, borrowApy: 0 }); - setPhoenixData({ supplyApy: 0, borrowApy: 0 }); - - } catch (e) { - console.error("Protocol data fetch error", e); - } - }; - fetchProtocols(); - }, []); - - // Fetch Installed Skills - const fetchInstalledSkills = async (agentId?: string) => { - if (!agentId) return; - - setIsSkillsLoading(true); - try { - // Skills/Plugins catalog (now fetched from protocol-meta) - const SKILL_CATALOG = protocolMeta.skills || {}; - - // Read from localStorage PER-AGENT (where Marketplace + Plugins pages persist installs) - const localSkills = JSON.parse(localStorage.getItem(`nirium-skills-${agentId}`) || '{}'); - const localPlugins = JSON.parse(localStorage.getItem(`nirium-plugins-${agentId}`) || '{}'); - const allLocalInstalled = { ...localSkills, ...localPlugins }; - - // Build full skill objects from the catalog - const resolved: any[] = []; - for (const key of Object.keys(allLocalInstalled)) { - if (allLocalInstalled[key] && SKILL_CATALOG[key]) { - resolved.push(SKILL_CATALOG[key]); - } - } - - // Also try the API (merge if available) - try { - const response = await fetch(`/api/marketplace/installed?agentId=${agentId}`); - const data = await response.json(); - if (data.success && data.skills?.length > 0) { - const existingSlugs = new Set(resolved.map(s => s.slug)); - for (const s of data.skills) { - if (!existingSlugs.has(s.slug)) { - resolved.push(s); - } - } - } - } catch { - // API unavailable, localStorage data is sufficient - } - - setInstalledSkills(resolved); - } catch (error) { - console.error("Failed to fetch skills", error); - } finally { - setIsSkillsLoading(false); - } - }; - - useEffect(() => { - if (selectedStrategy?.id) { - fetchInstalledSkills(selectedStrategy.id); - } - }, [selectedStrategy]); - - const handleUninstallSkill = async (slug: string) => { - if (!selectedStrategy?.id) return; - - const toastId = toast.loading(L(`Uninstalling ${slug}...`, `Desinstalando ${slug}...`)); - try { - // Remove from localStorage (per-agent) - const agentId = selectedStrategy.id; - const localSkills = JSON.parse(localStorage.getItem(`nirium-skills-${agentId}`) || '{}'); - const localPlugins = JSON.parse(localStorage.getItem(`nirium-plugins-${agentId}`) || '{}'); - - delete localSkills[slug]; - delete localPlugins[slug]; - - localStorage.setItem(`nirium-skills-${agentId}`, JSON.stringify(localSkills)); - localStorage.setItem(`nirium-plugins-${agentId}`, JSON.stringify(localPlugins)); - - // Update state - setInstalledSkills(prev => prev.filter(s => s.slug !== slug)); - toast.success(L("Skill uninstalled", "Skill desinstalada"), { id: toastId }); - - // Log to Ops Console - const skillName = installedSkills.find(s => s.slug === slug)?.name || slug; - writeLog(`PLUGIN REMOVED: ${skillName} - uninstalled from agent ${agentId}`, 'warn', account?.address); - } catch (error) { - toast.error(L(`Failed to uninstall: ${String(error)}`, `No se pudo desinstalar: ${String(error)}`), { id: toastId }); - } - }; - - // --- 1. STATE DECLARATIONS (Must correspond to logic below) --- - // Active Strategies Fleet (Persisted via Supabase/Local) - const [activeStrategies, setActiveStrategies] = useState>([]); - const [isLoadingFleet, setIsLoadingFleet] = useState(false); - const [isInitialized, setIsInitialized] = useState(false); - - // Modals (showAutoStartModal already declared above) - - // --- 2. CONSTANTS & MEMOS --- - // Protocol Metadata state (fetched from API) - const [protocolMeta, setProtocolMeta] = useState({ strategies: {}, skills: {}, bootLogs: {} }); - - // Fetch Protocol Metadata on mount - useEffect(() => { - const fetchMeta = async () => { - try { - const res = await fetch(`${process.env.NEXT_PUBLIC_API_URL || 'https://nirium-agent.fly.dev'}/api/public/protocol-meta`); - const data = await res.json(); - if (data.success) { - setProtocolMeta(data); - } - } catch (e) { - console.warn("[Dashboard] Protocol metadata fetch failed, using fallback empty state."); - } - }; - fetchMeta(); - }, []); - - // Fetch live market state (CETES rate, base fee, corridors) - useEffect(() => { - const fetchMarket = async () => { - try { - const res = await fetch('/api/market'); - const data = await res.json(); - setCurrentMarketState({ - etherfuseApy: data.cetesRate ?? 0, - baseFee: data.baseFee ?? 100, - pathPaymentRoutes: data.pathPaymentRoutes ?? [], - }); - } catch { /* use fallback */ } - }; - fetchMarket(); - const interval = setInterval(fetchMarket, 30_000); - return () => clearInterval(interval); - }, []); - - const STRATEGIES = protocolMeta.strategies || {}; - - const strategyId = searchParams.get('strategy') || "nirium-usdc-loop"; - const strategyNameParam = searchParams.get('name'); // From Builder redirect - - // Dynamically resolve strategy metadata (Default -> Active Fleet -> URL Param -> Custom Fallback) - const currentStrategy = useMemo(() => { - // 1. Known Hardcoded Strategy - if (STRATEGIES[strategyId]) return STRATEGIES[strategyId]; - - // 2. Look in Active Fleet (Loaded from DB/Local) - const found = activeStrategies.find(s => s.id === strategyId || s.strategy_id === strategyId); - if (found) return { name: found.name, logPrefix: "CUSTOM", emoji: found.emoji }; - - // 3. Try direct LocalStorage peek (for immediate post-builder redirect) - if (typeof window !== 'undefined' && account?.address) { - try { - const localKey = `nirium-fleet-${account.address}`; - const local = JSON.parse(localStorage.getItem(localKey) || "[]"); - const localFound = local.find((s: any) => s.id === strategyId); - if (localFound) return { name: localFound.name, logPrefix: "CUSTOM", emoji: localFound.emoji || "🛠️" }; - } catch { } - } - - // 4. Use URL name param if provided (for immediate display before data loads) - if (strategyNameParam) { - return { name: strategyNameParam, logPrefix: "CUSTOM", emoji: "🛠️" }; - } - - // 5. Smart Fallback - if (strategyId.startsWith('custom-')) { - return { name: "Custom Agent Strategy", logPrefix: "BUILDER", emoji: "🛠️" }; - } - - return STRATEGIES["nirium-usdc-loop"] || { name: "Nirium Loop", logPrefix: "CORE", emoji: "🧬" }; - }, [strategyId, activeStrategies, account, strategyNameParam, STRATEGIES]); - - // Treasury plegado: se abre con bóveda propia o al llegar con una estrategia/activo en la URL. - useEffect(() => { - if (vaultId !== null || searchParams.get('strategy') || searchParams.get('asset') || strategyNameParam) { - setTreasuryOpen(true); - } - }, [vaultId, searchParams, strategyNameParam]); - - // Auto-deploy logic for Navbar CTA - useEffect(() => { - const assetParam = searchParams.get('asset'); - if (assetParam === 'XLM' || assetParam === 'USDC') { - setBaseAsset(assetParam); - } - - if (searchParams.get('autostart') === 'true' && account) { - setTreasuryOpen(true); - // Preserve name param if it exists - const nameParam = strategyNameParam ? `&name=${encodeURIComponent(strategyNameParam)}` : ''; - router.replace(`/dashboard?strategy=${strategyId}${nameParam}`); - setShowAutoStartModal(true); - } - }, [searchParams, account, router, strategyId, strategyNameParam]); - - useEffect(() => { - if (account?.address) { - const loadFleet = async () => { - setIsLoadingFleet(true); - setIsInitialized(false); - try { - // Dynamic import to avoid server-side issues - const { StrategyService } = await import("@/lib/strategyService"); - const fleet = await StrategyService.getStrategies(account.address); - - // Merge with LocalStorage to capture offline-created custom builds - const localKey = `nirium-fleet-${account.address}`; - const localRaw = localStorage.getItem(localKey); - let merged = [...fleet]; - - if (localRaw) { - const local = JSON.parse(localRaw) as any[]; - - // 1. Deduplicate LocalStorage internally (keep latest) - const localMap = new Map(); - local.forEach(item => { - if (item.id) localMap.set(item.id, item); - }); - const distinctLocal = Array.from(localMap.values()); - - // 2. Filter out items that are already in DB - const uniqueLocals = distinctLocal.filter((l: any) => - !fleet.some(dbS => - (dbS.strategy_id && dbS.strategy_id === l.id) || - (dbS.name === l.name) - ) - ); - merged = [...merged, ...uniqueLocals]; - } - - if (merged.length === 0) { - // Clean state - setActiveStrategies([]); - } else { - // FINAL AGGRESSIVE DEDUP: Prioritize NAME to avoid same-name duplicates - const finalMap = new Map(); - merged.forEach(item => { - // For custom strategies, use name as key (prevents "StellarL" appearing 3 times) - // For DB strategies, use id - const isCustom = item.id?.startsWith('custom-') || item.strategy_id?.startsWith('custom-'); - const key = isCustom ? (item.name || item.id) : (item.id || item.name); - - if (key && !finalMap.has(key)) { - finalMap.set(key, item); - } - }); - const finalDeduped = Array.from(finalMap.values()); - - // Filter out DRAFT strategies - show any RUNNING/active status - const activeOnly = finalDeduped.filter(s => { - const st = (s.status || '').toUpperCase(); - return st !== 'DRAFT' && st !== ''; - }); - - // Also clean up LocalStorage to prevent future issues - if (finalDeduped.length < merged.length) { - const localKey = `nirium-fleet-${account.address}`; - localStorage.setItem(localKey, JSON.stringify(finalDeduped)); - console.log('[Dashboard] Cleaned duplicate strategies from LocalStorage'); - } - - setActiveStrategies(activeOnly); - } - } catch (e) { - console.error("Supabase sync failed, using local", e); - } finally { - setIsLoadingFleet(false); - setIsInitialized(true); - } - }; - loadFleet(); - } else { - setActiveStrategies([]); - setIsInitialized(false); - } - }, [account]); - - // Persist activeStrategies to LocalStorage whenever they change (after initial load) - useEffect(() => { - if (!isInitialized || !account?.address) return; - - const localKey = `nirium-fleet-${account.address}`; - try { - // Merge with existing to preserve DRAFT strategies from Builder - const existing = JSON.parse(localStorage.getItem(localKey) || "[]"); - const drafts = existing.filter((s: any) => s.status === 'DRAFT'); - - // activeStrategies only contains RUNNING strategies - // Combine DRAFTs (from builder) + RUNNING (from dashboard) - const combined = [...drafts, ...activeStrategies]; - - // Deduplicate by ID - const deduped = Array.from(new Map(combined.map(s => [s.id, s])).values()); - - localStorage.setItem(localKey, JSON.stringify(deduped)); - console.log('[Dashboard] Synced fleet to LocalStorage:', deduped.length, 'strategies'); - } catch (e) { - console.warn('[Dashboard] Failed to sync LocalStorage:', e); - } - }, [activeStrategies, isInitialized, account]); - - const handleDeploy = () => { - if (!account) { - toast.error(L("Please connect your Stellar wallet first", "Primero conecta tu wallet de Stellar")); - return; - } - - // Check duplicates - if (activeStrategies.find(s => s.strategy_id === strategyId)) { - toast.warning(L(`${currentStrategy.emoji} ${currentStrategy.name} is already active`, `${currentStrategy.emoji} ${currentStrategy.name} ya está activa`)); - return; - } - - setShowAutoStartModal(true); - }; - - const executeDeploy = async () => { - if (!account) return; - - const toastId = toast.loading(L(`Starting ${currentStrategy.name}...`, `Iniciando ${currentStrategy.name}...`)); - - // determine Mode: V2 (AgentCap) or V1 (Script) - const useAgentCap = !!(vaultId && ownerCapId); - // Updated License fee: 12.5 XLM (approx. 100 MXN / 5 USD) - const REQUIRED_FEE_LO: string = "125000000"; // 12.5 XLM in stroops - - // Network Check (Strict) - if (account.chains?.[0] && account.chains[0] !== 'stellar:testnet') { - toast.error(L("Wrong network", "Red equivocada"), { - description: L("This dashboard runs on Stellar testnet. Switch your wallet's network.", "Este panel corre en Stellar testnet. Cambia la red de tu wallet.") - }); - return; - } - const REQUIRED_BALANCE = 15.0; // 12.5 Fee + Gas Buffer - - try { - // 0. Check Balance - // Check Native XLM Balance for Transaction Gas + Fee Requirements - let requiredStellarAmount = REQUIRED_BALANCE; - const { stellarClient } = await import("@/lib/stellarClient"); - const nativeBalance = await stellarClient.getBalance({ owner: account.address, coinType: 'XLM' }).then(b => Number(BigInt(b.totalBalance)) / 10_000_000); - - if (nativeBalance < REQUIRED_BALANCE) { - toast.error(t.dashboard.toasts.insufficient_balance.replace('{amount}', REQUIRED_BALANCE.toString()), { - description: L(`Detected: ${nativeBalance.toFixed(4)} XLM.`, `Detectado: ${nativeBalance.toFixed(4)} XLM.`) - }); - return; - } - - // REAL INSTITUTIONAL SOROBAN CALL - toast.loading(t.dashboard.toasts.deploying_vault, { id: toastId }); - const result = await vault.createVault(account.address, NATIVE_ASSET_ID, currentStrategy.name); - - if (!result.success || !result.txHash) { - toast.dismiss(toastId); - toast.error(t.dashboard.toasts.deployment_failed, { - description: result.error || t.dashboard.toasts.check_freighter - }); - return; - } - - const txHash = result.txHash; - - // Extract vault ID and store so stop flow can call close_vault - const newVaultData = result.result as any; - const newVaultId = newVaultData - ? Number(newVaultData.vault_id ?? newVaultData.vaultId ?? newVaultData[0] ?? NaN) - : NaN; - if (!isNaN(newVaultId)) { - const storageData = { - vaultId: newVaultId, - ownerCapId: `cap_${newVaultId}_${Date.now()}`, - createdAt: Date.now(), - txHash, - }; - localStorage.setItem(`nirium-vault-v2-XLM-${account.address}`, JSON.stringify(storageData)); - setVaultId(newVaultId); - } - - toast.dismiss(toastId); - toast.success(L(`${currentStrategy.emoji} ${currentStrategy.name} active`, `${currentStrategy.emoji} ${currentStrategy.name} activa`), { - description: L("Vault created on Soroban.", "Bóveda creada en Soroban."), - action: { - label: "Verify on Explorer", - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${txHash}`, "_blank") - } - }); - - // Save to Supabase & State (vault_id in config so stop works after page reload) - const { StrategyService } = await import("@/lib/strategyService"); - StrategyService.deployStrategy(account.address, { - strategy_id: strategyId, - name: currentStrategy.name, - emoji: currentStrategy.emoji, - status: "RUNNING", - yield: "~6.5%", - tx_digest: txHash, - config: !isNaN(newVaultId) ? { vault_id: newVaultId } : {} - }).then((newStrategy: any) => { - const strategyToAdd = { - id: newStrategy?.id || strategyId, - strategy_id: strategyId, - name: currentStrategy.name, - emoji: currentStrategy.emoji, - status: "RUNNING", - yield: "~6.5%", - tx_digest: txHash, - }; - setActiveStrategies(prev => { - const filtered = prev.filter(s => s.id !== strategyId && s.strategy_id !== strategyId); - return [strategyToAdd, ...filtered]; - }); - }); - - writeLog(`Agent Activity: ${currentStrategy.name} initialization confirmed.`, 'info', account?.address); - - writeLog( - `${currentStrategy.emoji} AGENT DEPLOYED: ${currentStrategy.name} | tx: ${txHash.slice(0, 12)}...`, - 'success', - account?.address - ); - - // Strategy-specific boot logs (now fetched from protocol-meta) - const STRATEGY_BOOT_LOGS = protocolMeta.bootLogs || {}; - - const bootLogs = STRATEGY_BOOT_LOGS[strategyId]; - if (bootLogs) { - bootLogs.forEach((entry, i) => { - setTimeout(() => { - writeLog(entry.msg, entry.level, account?.address); - }, (i + 1) * 2000); - }); - } - - } catch (err: any) { - console.error("Deploy Error:", err); - toast.dismiss(toastId); - handleWalletError(err); - } - }; - - const stopStrategy = (dbId: string) => { - if (!account) { - toast.error(L("Please connect your Stellar wallet first", "Primero conecta tu wallet de Stellar")); - return; - } - const foundStrategy = activeStrategies.find(s => s.id === dbId || s.strategy_id === dbId); - if (!foundStrategy) return; - - setConfirmConfig({ - isOpen: true, - title: L("Stop this agent?", "¿Detener este agente?"), - description: ( -
-

{L('You are about to stop the agent for ', 'Vas a detener el agente de ')}{foundStrategy.name}.

-
-
- - {L('What happens', 'Qué pasa')} -
-

- {L('• The agent stops acting on this strategy', '• El agente deja de actuar en esta estrategia')}
- {L('• If it has a vault, it is closed on-chain (balance must be 0)', '• Si tiene bóveda, se cierra en la cadena (el saldo debe ser 0)')}
- {L('• Needs your signature in Freighter', '• Requiere tu firma en Freighter')} -

-
-
- ), - icon:
- - -
, - confirmText: L("STOP AGENT", "DETENER AGENTE"), - type: 'danger', - onConfirm: () => { - setConfirmConfig(prev => ({ ...prev, isOpen: false })); - executeStopStrategy(dbId); - } - }); - }; - - const executeStopStrategy = async (dbId: string) => { - if (!account) return; - - // Network Check (Strict) - if (account.chains?.[0] && account.chains[0] !== 'stellar:testnet') { - toast.error(L("Wrong network", "Red equivocada"), { - description: L("This dashboard runs on Stellar testnet. Switch your wallet's network.", "Este panel corre en Stellar testnet. Cambia la red de tu wallet.") - }); - return; - } - - const toastId = toast.loading(L("Stopping the agent...", "Deteniendo el agente...")); - - try { - // Resolve vaultId: state → localStorage → Supabase config - let resolvedVaultId = vaultId; - if (resolvedVaultId === null && account?.address) { - for (const asset of ['USDC', 'XLM', 'CETES']) { - try { - const saved = localStorage.getItem(`nirium-vault-v2-${asset}-${account.address}`); - if (saved) { - const parsed = JSON.parse(saved); - if (parsed?.vaultId != null && !isNaN(Number(parsed.vaultId))) { - resolvedVaultId = Number(parsed.vaultId); - break; - } - } - } catch { /* skip */ } - } - } - // Last resort: read vault_id from the strategy's config in Supabase/localStorage - if (resolvedVaultId === null) { - const found = activeStrategies.find(s => s.id === dbId || s.strategy_id === dbId); - const configVaultId = found?.config?.vault_id; - if (configVaultId != null && !isNaN(Number(configVaultId))) { - resolvedVaultId = Number(configVaultId); - } - } - - // Close vault on-chain - proper Soroban invocation, 1 Freighter signature - const localVaultId = resolvedVaultId; - const closeResult = localVaultId !== null - ? await vaultClose(account.address, localVaultId) - : null; - - toast.dismiss(toastId); - if (closeResult?.success && closeResult?.txHash) { - toast.success(L("Vault closed", "Bóveda cerrada"), { - description: L(`Vault #${localVaultId} closed on Stellar testnet.`, `Bóveda #${localVaultId} cerrada en Stellar testnet.`), - action: { - label: "View Tx", - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${closeResult.txHash}`, "_blank") - } - }); - writeLog(`VAULT CLOSED: #${localVaultId} | tx: ${closeResult.txHash.slice(0, 12)}...`, 'warn', account?.address); - } else { - // Fallback: signed memo tx so Freighter still prompts - const { Operation, Asset, Memo } = await import("@stellar/stellar-sdk"); - const stratName = activeStrategies.find(s => s.id === dbId)?.name || dbId; - const tx = await buildStellarTransaction(account.address); - tx.addOperation(Operation.payment({ - destination: account.address, - asset: Asset.native(), - amount: "0.0001" - })).addMemo(Memo.text(`NIRIUM:STOP:${stratName.slice(0, 16)}`)); - const builtTx = tx.build(); - const result = await signAndSubmitTransaction({ transaction: builtTx }); - toast.success(L("Agent stopped", "Agente detenido"), { - description: L("Stop recorded on Stellar testnet.", "Detención registrada en Stellar testnet."), - action: { - label: "View Tx", - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${result.hash}`, "_blank") - } - }); - writeLog(`AGENT TERMINATED: ${stratName} | tx: ${result.hash.slice(0, 12)}...`, 'warn', account?.address); - } - - // Step 2: Clean up locally - setActiveStrategies(prev => prev.filter(s => s.id !== dbId)); - - // Server-side stop (DB update) - const isUUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-5][0-9a-f]{3}-[089ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(dbId); - if (isUUID) { - import("@/lib/strategyService").then(({ StrategyService }) => { - StrategyService.stopStrategy(dbId).catch(console.warn); - }); - } - - // Persist removal to LocalStorage - if (account?.address) { - const localKey = `nirium-fleet-${account.address}`; - try { - const existing = JSON.parse(localStorage.getItem(localKey) || "[]"); - const filtered = existing.filter((s: any) => s.id !== dbId && s.strategy_id !== dbId); - localStorage.setItem(localKey, JSON.stringify(filtered)); - } catch (e) { } - } - - } catch (e: any) { - toast.dismiss(toastId); - console.warn("Agent stop error:", e); - const msg = e.message || String(e); - - if (msg.includes("Rejected")) return; - - // If it's a network error (502) or the object doesn't exist, offer "Force Remove" - toast.error(L("Sync failed", "Falló la sincronización"), { - description: L(`Code: ${msg.slice(0, 30)}...`, `Código: ${msg.slice(0, 30)}...`), - action: { - label: "FORCE REMOVE", - onClick: () => { - // 1. Force clean up local state - setActiveStrategies(prev => prev.filter(s => s.id !== dbId)); - - // 2. Force clean up database (Uplink) - import("@/lib/strategyService").then(({ StrategyService }) => { - StrategyService.stopStrategy(dbId).catch(err => console.error("DB Cleanup failed:", err)); - }); - - // 3. Force clean up local storage - if (account?.address) { - const localKey = `nirium-fleet-${account.address}`; - try { - const existing = JSON.parse(localStorage.getItem(localKey) || "[]"); - const filtered = existing.filter((s: any) => s.id !== dbId && s.strategy_id !== dbId); - localStorage.setItem(localKey, JSON.stringify(filtered)); - } catch (err) { } - } - toast.success(L("Agent removed from the list and its record cleared", "Agente quitado de la lista y su registro borrado")); - writeLog(`AGENT TERMINATED: Force cleaned from logic gates.`, 'error', account?.address); - } - } - }); - } - }; - - - - const confirmAutoStart = () => { - setShowAutoStartModal(false); - executeDeploy(); - }; - - // --- RESTORE AUTO-REBALANCE STATE FROM LOCALSTORAGE --- - useEffect(() => { - if (!account?.address) return; - try { - const saved = localStorage.getItem(`nirium-autorebalance-${account.address}`); - if (!saved) return; - - const { autoRebalance: ar, delegationId: di, autoExit: ae, txHash: th, rebalanceThreshold: rt, reverseThreshold: rv } = JSON.parse(saved); - if (ar) { setAutoRebalance(true); setDelegationId(di ?? null); if (th) setDelegationTxHash(th); } - if (ae) setAutoExit(true); - if (rt) setRebalanceThreshold(rt); - if (rv) setReverseThreshold(rv); - - // If the saved delegation ID is a fake demo-del-xxx (created when the agent was unreachable), - // re-register in Supabase now that CORS + service role key are configured. - // The Soroban delegation already exists on-chain - no Freighter signature needed. - if (ar && di && (di.startsWith('demo-del-') || !di.includes('-'))) { - const savedVaultId = (() => { - for (const asset of ['USDC', 'XLM', 'CETES']) { - try { - const v = localStorage.getItem(`nirium-vault-v2-${asset}-${account.address}`); - if (v) { const p = JSON.parse(v); if (p?.vaultId) return p.vaultId; } - } catch { /* skip */ } - } - return null; - })(); - - if (savedVaultId) { - const AGENT_API_URL = process.env.NEXT_PUBLIC_AGENT_URL || 'https://nirium-agent.fly.dev'; - const token = localStorage.getItem('nirium-token') || 'demo-token'; - fetch(`${AGENT_API_URL}/api/vault/delegate`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, - body: JSON.stringify({ - user_wallet: account.address, - vault_id: savedVaultId, - rebalance_threshold: rt ?? 4.0, - }), - }).then(async r => { - if (r.ok) { - const data = await r.json(); - const realId = data.delegation?.id; - if (realId) { - setDelegationId(realId); - const updated = JSON.parse(localStorage.getItem(`nirium-autorebalance-${account.address}`) ?? '{}'); - updated.delegationId = realId; - localStorage.setItem(`nirium-autorebalance-${account.address}`, JSON.stringify(updated)); - } - } - }).catch(() => { /* silent - agent may be starting up */ }); - } - } - } catch { /* ignore */ } - }, [account?.address]); - - // --- RECONCILE WITH SUPABASE (DB es la fuente de verdad por wallet) --- - // Poll cada 15s al endpoint de la wallet conectada para mantener el toggle - // sincronizado con DB, incluso si un STOP/activate no se propagó por timeouts de red. - useEffect(() => { - if (!account?.address) return; - const AGENT_API_URL = process.env.NEXT_PUBLIC_AGENT_URL || 'https://nirium-agent.fly.dev'; - const wallet = account.address; - - const sync = async () => { - const ctrl = new AbortController(); - const t = setTimeout(() => ctrl.abort(), 8000); - try { - const r = await fetch(`${AGENT_API_URL}/api/vault/delegate/${wallet}`, { signal: ctrl.signal }); - if (!r.ok) return; - const data = await r.json(); - const d = data?.delegation; - if (d && d.is_active) { - setAutoRebalance(true); - setDelegationId(d.id); - if (d.rebalance_threshold) setRebalanceThreshold(Number(d.rebalance_threshold)); - if (d.reverse_rebalance) { - setAutoExit(true); - if (d.reverse_threshold) setReverseThreshold(Number(d.reverse_threshold)); - } else { - setAutoExit(false); - } - const stored = JSON.parse(localStorage.getItem(`nirium-autorebalance-${wallet}`) ?? '{}'); - localStorage.setItem(`nirium-autorebalance-${wallet}`, JSON.stringify({ - ...stored, - autoRebalance: true, - delegationId: d.id, - rebalanceThreshold: Number(d.rebalance_threshold), - autoExit: !!d.reverse_rebalance, - reverseThreshold: Number(d.reverse_threshold), - })); - } else { - // No hay fila activa en Supabase. Antes de borrar el estado, verificamos - // si tenemos una delegación on-chain pendiente de sincronizar (placeholder - // demo-del-* con txHash real). Si la hay, re-intentamos el registro. - const stored = localStorage.getItem(`nirium-autorebalance-${wallet}`); - if (stored) { - try { - const parsed = JSON.parse(stored); - const isPending = parsed?.autoRebalance === true - && typeof parsed?.delegationId === 'string' - && parsed.delegationId.startsWith('demo-del-') - && parsed?.txHash; - if (isPending) { - const resolvedVaultId = (() => { - for (const asset of ['USDC', 'XLM', 'CETES']) { - try { - const v = localStorage.getItem(`nirium-vault-v2-${asset}-${wallet}`); - if (v) { const p = JSON.parse(v); if (p?.vaultId) return p.vaultId; } - } catch { /* skip */ } - } - return null; - })(); - if (resolvedVaultId) { - const token = localStorage.getItem('nirium-token') || 'demo-token'; - fetch(`${AGENT_API_URL}/api/vault/delegate`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, - body: JSON.stringify({ - user_wallet: wallet, - vault_id: resolvedVaultId, - rebalance_threshold: parsed.rebalanceThreshold ?? 4.0, - }), - }).then(async r2 => { - if (!r2.ok) return; - const data2 = await r2.json(); - const realId = data2?.delegation?.id; - if (realId) { - setDelegationId(realId); - const updated = { ...parsed, delegationId: realId }; - localStorage.setItem(`nirium-autorebalance-${wallet}`, JSON.stringify(updated)); - } - }).catch(() => { /* siguiente tick re-intenta */ }); - return; // No borramos el estado mientras retry está en curso - } - } - } catch { /* ignore parse error */ } - } - setAutoRebalance(false); - setAutoExit(false); - setDelegationId(null); - setDelegationTxHash(null); - localStorage.removeItem(`nirium-autorebalance-${wallet}`); - } - } catch { /* timeout o offline - conserva estado actual */ } - finally { clearTimeout(t); } - }; - - sync(); - const interval = setInterval(sync, 15000); - return () => clearInterval(interval); - }, [account?.address]); - - // --- REAL-TIME LOGS VIA WEBSOCKET --- - const wsRef = useRef(null); - const accountRef = useRef(account); - useEffect(() => { accountRef.current = account; }, [account]); - - useEffect(() => { - let isUnmounted = false; - let retryCount = 0; - let retryTimeout: NodeJS.Timeout; - - const connectWebSocket = () => { - if (isUnmounted) return; - // Prevent multiple simultaneous connections from the same component instance - if (wsRef.current && (wsRef.current.readyState === WebSocket.OPEN || wsRef.current.readyState === WebSocket.CONNECTING)) { - return; - } - - const wsUrl = getWebSocketUrl('/ws/signals'); - // Safety check for production mixed content - if (wsUrl.includes('localhost') && typeof window !== 'undefined' && window.location.protocol === 'https:') { - console.log('[Dashboard] Skipping WS localhost on HTTPS'); - return; - } - - try { - console.log('[Dashboard] Attempting WS connection to:', wsUrl); - const ws = new WebSocket(wsUrl); - wsRef.current = ws; - - ws.onopen = () => { - if (isUnmounted) return; - console.log('[Dashboard] WS Connected Successfully'); - - if (accountRef.current?.address) { - ws.send(JSON.stringify({ - type: 'subscribe', - userId: accountRef.current.address, - topics: ['execution', 'system'] - })); - } - }; - - ws.onmessage = (event) => { - if (isUnmounted) return; - try { - const data = JSON.parse(event.data); - if (data.type === 'log' || data.type === 'execution') { - const time = new Date().toLocaleTimeString(); - const message = data.message || JSON.stringify(data); - writeLog(`🤖 ${message}`, 'info', data.agent_id || 'UI_CLIENT'); - - if (data.status === 'success' && data.txHash) { - toast.success(L("Strategy executed", "Estrategia ejecutada"), { - description: `Tx: ${data.txHash.slice(0, 8)}...`, - action: { - label: "View", - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${data.txHash}`, "_blank") - } - }); - } - } - - // Tauri Tray Trigger - if (data.type === 'signal' && (window as any).__TAURI_INTERNALS__) { - const { invoke } = require('@tauri-apps/api/core'); - invoke('update_tray_status', { active: true }); - } - } catch (e) { } - }; - - ws.onclose = (event) => { - wsRef.current = null; - if (!isUnmounted) { - console.log('[Dashboard] WS Closed. Code:', event.code); - if (retryCount < 5) { // Limit retries to prevent storms - retryCount++; - const delay = 3000 * retryCount; // Exponential backoff - console.log(`[Dashboard] Retrying in ${delay}ms...`); - retryTimeout = setTimeout(connectWebSocket, delay); - } - } - }; - - ws.onerror = () => { - // Muted intentionally to prevent noisy UI console logs when backend is offline - wsRef.current = null; - }; - - } catch (e) { - console.error("[Dashboard] WS Setup Failed:", e); - } - }; - - connectWebSocket(); - - return () => { - isUnmounted = true; - if (retryTimeout) clearTimeout(retryTimeout); - if (wsRef.current) { - console.log('[Dashboard] Cleaning up WS connection'); - wsRef.current.close(); - wsRef.current = null; - } - }; - }, []); // Runs once per mount - - // 🧪 Production Diagnostics: Test Supabase link on first load - useEffect(() => { - const testConn = async () => { - const hasTested = sessionStorage.getItem('nirium_diag_v1'); - if (!hasTested) { - console.log('🧪 [Diag] Dashboard session initialized - keeping diagnostics off the public feed.'); - sessionStorage.setItem('nirium_diag_v1', 'true'); - } - }; - testConn(); - }, []); - - - - // SVG Chart Data Generator (Mock) - const chartPath = "M0,100 C20,90 40,110 60,80 C80,50 100,90 120,40 C140,20 160,60 180,30 C200,10 220,40 240,20 L240,150 L0,150 Z"; - const linePath = "M0,100 C20,90 40,110 60,80 C80,50 100,90 120,40 C140,20 160,60 180,30 C200,10 220,40 240,20"; - - // Load Vault & OwnerCap from LocalStorage on mount - useEffect(() => { - if (account?.address) { - const CURRENT_VAULT_CONTRACT = process.env.NEXT_PUBLIC_CONTRACT_VAULT || 'CDMFURE6MYROTA2A6DLD4TN2S4QTN64L2FZ2I2RY2AREONX6DUQOI2S2'; - const savedData = localStorage.getItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - if (savedData) { - try { - const vaultData = JSON.parse(savedData); - // If vault was created on a different contract, clear it - it's an orphaned vault - if (vaultData.contractId && vaultData.contractId !== CURRENT_VAULT_CONTRACT) { - console.warn('[Vault] Orphaned vault detected - contract changed. Clearing cache.'); - localStorage.removeItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - localStorage.removeItem(`nirium-autorebalance-${account.address}`); - setVaultId(null); - setOwnerCapId(null); - } else if (typeof vaultData === 'object' && vaultData.vaultId !== undefined) { - const numericId = typeof vaultData.vaultId === 'number' - ? vaultData.vaultId - : parseInt(String(vaultData.vaultId), 10); - if (!isNaN(numericId)) { - setVaultId(numericId); - if (vaultData.ownerCapId) setOwnerCapId(vaultData.ownerCapId); - } else { - localStorage.removeItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - setVaultId(null); - setOwnerCapId(null); - } - } else { - setVaultId(null); - setOwnerCapId(null); - } - } catch (e) { - console.error('Failed to parse vault data:', e); - setVaultId(null); - setOwnerCapId(null); - } - } else { - setVaultId(null); - setOwnerCapId(null); - } - } - }, [account, baseAsset]); - - const handleDeposit = () => { - if (!vaultId) return; - - setConfirmConfig({ - isOpen: true, - title: L("Deposit to your vault", "Depositar en tu bóveda"), - description: ( -
-

{L(`Move ${baseAsset} from your wallet to your vault.`, `Mueve ${baseAsset} de tu wallet a tu bóveda.`)}

-
- - {baseAsset} -
-
- ), - icon: , - confirmText: L("CONFIRM DEPOSIT", "CONFIRMAR DEPÓSITO"), - type: 'info', - onConfirm: () => { - const val = (document.getElementById('depositInput') as HTMLInputElement)?.value || "0"; - setAmountInput(val); - setConfirmConfig(p => ({ ...p, isOpen: false })); - executeDeposit(val); - } - }); - }; - - const executeDeposit = async (amount: string) => { - if (!account) { - toast.error(L("Please connect your wallet", "Conecta tu wallet")); - return; - } - - if (!vaultId || typeof vaultId !== 'number') { - toast.error(L("No vault found", "No se encontró la bóveda"), { - description: L("Create a vault before depositing", "Crea una bóveda antes de depositar") - }); - return; - } - - // Network Check (Strict) - if (account.chains?.[0] && account.chains[0] !== 'stellar:testnet') { - toast.error(L("Wrong network", "Red equivocada"), { - description: L("This dashboard runs on Stellar testnet. Switch your wallet's network.", "Este panel corre en Stellar testnet. Cambia la red de tu wallet.") - }); - return; - } - - // Validate balance before deposit - const depositAmount = parseFloat(amount); - const currentBalance = baseAsset === 'CETES' ? parseFloat(cetesBalance) : walletBalance; - - if (depositAmount > currentBalance) { - toast.error(L("Insufficient balance", "Saldo insuficiente"), { - description: L(`You only have ${currentBalance.toFixed(2)} ${baseAsset}. You can't deposit ${depositAmount} ${baseAsset}.`, `Solo tienes ${currentBalance.toFixed(2)} ${baseAsset}. No puedes depositar ${depositAmount} ${baseAsset}.`) - }); - return; - } - - const toastId = toast.loading(L(`Depositing ${amount} ${baseAsset}...`, `Depositando ${amount} ${baseAsset}...`)); - try { - // Convert amount to stroops (1 XLM/USDC/CETES = 10^7 stroops) - const amountInStroops = BigInt(Math.floor(parseFloat(amount) * 10_000_000)); - - // Call the actual Soroban vault contract deposit function - const result = await vaultDeposit(account.address, vaultId, amountInStroops); - - toast.dismiss(toastId); - - if (result.success) { - // Update vault balance optimistically - setVaultBalance(prev => prev + parseFloat(amount)); - - // Immediately update wallet balance (subtract deposited amount) - setWalletBalance(prev => Math.max(0, prev - parseFloat(amount))); - - toast.success(t.dashboard.toasts.deposit_success, { - description: t.dashboard.toasts.deposit_desc.replace('{amount}', amount).replace('{asset}', baseAsset), - action: result.txHash ? { - label: t.dashboard.toasts.view_tx, - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${result.txHash}`, "_blank") - } : undefined - }); - - // Log the successful deposit - writeLog(`VAULT DEPOSIT: ${amount} ${baseAsset} | Vault ID: ${vaultId} | Tx: ${result.txHash?.slice(0, 12)}...`, 'success'); - } else { - throw new Error(result.error || 'Deposit failed'); - } - } catch (e: any) { - console.error('Deposit error:', e); - toast.dismiss(toastId); - toast.error(L("Deposit failed", "Falló el depósito"), { - description: e.message || "Failed to deposit to vault contract" - }); - writeLog(`VAULT DEPOSIT FAILED: ${e.message}`, 'error'); - } - }; - - const handleWithdraw = () => { - if (!vaultId || !ownerCapId) { - toast.error(L("Only the vault owner can withdraw.", "Solo el dueño de la bóveda puede retirar.")); - return; - } - - setConfirmConfig({ - isOpen: true, - title: L("Withdraw from your vault", "Retirar de tu bóveda"), - description: ( -
-

{L(`Move ${baseAsset} from your vault back to your wallet.`, `Regresa ${baseAsset} de tu bóveda a tu wallet.`)}

-
- - {baseAsset} -
-
- ), - icon:
, - confirmText: L("CONFIRM WITHDRAWAL", "CONFIRMAR RETIRO"), - type: 'info', - onConfirm: () => { - const val = (document.getElementById('withdrawInput') as HTMLInputElement)?.value || "0"; - setAmountInput(val); - setConfirmConfig(p => ({ ...p, isOpen: false })); - executeWithdraw(val); - } - }); - }; - - const executeWithdraw = async (amount: string, retryCount = 0) => { - const MAX_RETRIES = 3; - - if (!account) { - toast.error(L("Please connect your wallet", "Conecta tu wallet")); - return; - } - - if (!vaultId || typeof vaultId !== 'number') { - toast.error(L("No vault found", "No se encontró la bóveda"), { - description: L("Create a vault first", "Primero crea una bóveda") - }); - return; - } - - if (!ownerCapId) { - toast.error(L("This wallet isn't the vault owner", "Esta wallet no es la dueña de la bóveda"), { - description: L("Only the vault owner can withdraw", "Solo el dueño de la bóveda puede retirar") - }); - return; - } - - // Network Check (Strict) - if (account.chains?.[0] && account.chains[0] !== 'stellar:testnet') { - toast.error(L("Wrong network", "Red equivocada"), { - description: L("This dashboard runs on Stellar testnet. Switch your wallet's network.", "Este panel corre en Stellar testnet. Cambia la red de tu wallet.") - }); - return; - } - - // Validate withdrawal amount - const withdrawAmount = parseFloat(amount); - if (isNaN(withdrawAmount) || withdrawAmount <= 0) { - toast.error(L("Invalid amount", "Monto inválido"), { - description: L("Enter a positive number to withdraw.", "Escribe un número positivo para retirar.") - }); - return; - } - - // Check vault has sufficient balance - if (withdrawAmount > vaultBalance) { - toast.error(L(`Not enough ${baseAsset} in the vault`, `No hay suficiente ${baseAsset} en la bóveda`), { - description: L(`Vault balance: ${vaultBalance.toFixed(7)} ${baseAsset}. You asked for ${withdrawAmount} ${baseAsset}.`, `Saldo de la bóveda: ${vaultBalance.toFixed(7)} ${baseAsset}. Pediste ${withdrawAmount} ${baseAsset}.`) - }); - return; - } - - // CETES trustline pre-check (Stellar requires trustline before receiving non-native assets) - // Reference: https://developers.stellar.org/docs/build/guides/basics/verify-trustlines - if (baseAsset === 'CETES' && !hasCetesTrust) { - toast.error(L("CETES trustline not found", "No se encontró la trustline de CETES"), { - description: L("Your wallet needs a CETES trustline to receive this asset. Add it in Freighter first.", "Tu wallet necesita una trustline de CETES para recibir este activo. Agrégala primero en Freighter."), - action: { - label: "Add via Etherfuse", - onClick: () => window.open('https://devnet.etherfuse.com', '_blank') - } - }); - return; - } - - // USDC trustline pre-check (SAC assets also need trustline on classic side for withdrawal) - if (baseAsset === 'USDC') { - try { - const { Horizon } = await import('@stellar/stellar-sdk'); - const horizonServer = new Horizon.Server(process.env.NEXT_PUBLIC_HORIZON_URL || 'https://horizon-testnet.stellar.org'); - const acct = await horizonServer.loadAccount(account.address); - const hasUSDC = acct.balances.some( - (b: any) => b.asset_type !== 'native' && b.asset_code === 'USDC' - ); - if (!hasUSDC) { - toast.error(L("USDC trustline not found", "No se encontró la trustline de USDC"), { - description: L("Your wallet needs a USDC trustline to receive this asset. Add it in Freighter's settings.", "Tu wallet necesita una trustline de USDC para recibir este activo. Agrégala en la configuración de Freighter.") - }); - return; - } - } catch { - // If Horizon is unreachable, proceed - the contract will catch it - } - } - - const isRetry = retryCount > 0; - const toastId = toast.loading( - isRetry - ? `Retrying withdrawal (${retryCount}/${MAX_RETRIES})...` - : `Withdrawing ${amount} ${baseAsset}...` - ); - - try { - // Convert amount to stroops (1 XLM/USDC/CETES = 10^7 stroops - Stellar 7-decimal precision) - const amountInStroops = BigInt(Math.floor(withdrawAmount * 10_000_000)); - - const result = await vaultWithdraw(account.address, vaultId, amountInStroops); - - toast.dismiss(toastId); - - if (result.success) { - setVaultBalance(prev => Math.max(0, prev - withdrawAmount)); - setWalletBalance(prev => prev + withdrawAmount); - - toast.success(t.dashboard.toasts.withdrawal_success, { - description: t.dashboard.toasts.withdrawal_desc - .replace('{amount}', amount) - .replace('{asset}', baseAsset), - action: result.txHash ? { - label: t.dashboard.toasts.view_tx, - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${result.txHash}`, "_blank") - } : undefined - }); - - writeLog(`VAULT WITHDRAW: ${amount} ${baseAsset} | Vault ID: ${vaultId} | Tx: ${result.txHash?.slice(0, 12)}...`, 'success'); - } else { - // Classify the error for actionable user feedback - const err = result.error || 'Withdrawal failed'; - - if (err.includes('insufficient vault balance') || err.includes('balance')) { - toast.error(L(`Not enough ${baseAsset} in the vault`, `No hay suficiente ${baseAsset} en la bóveda`), { - description: L(`The vault doesn't have enough ${baseAsset}. Current balance: ${vaultBalance.toFixed(7)} ${baseAsset}.`, `La bóveda no tiene suficiente ${baseAsset}. Saldo actual: ${vaultBalance.toFixed(7)} ${baseAsset}.`) - }); - } else if (err.includes('vault not found')) { - toast.error(L("Vault not found", "No se encontró la bóveda"), { - description: L("This vault may have been closed or the contract redeployed. Clear the cache and reconnect.", "Puede que la bóveda se haya cerrado o que el contrato se haya vuelto a desplegar. Borra la caché y vuelve a conectar.") - }); - } else if (err.includes('not_paused') || err.includes('paused')) { - toast.error(L("Contract paused", "Contrato en pausa"), { - description: L("The NiriumVault contract is paused for now.", "El contrato NiriumVault está en pausa por ahora.") - }); - } else if (result.isSimulationError) { - toast.error(L("Transaction simulation failed", "Falló la simulación de la transacción"), { - description: L("Soroban RPC rejected this transaction during simulation. It usually means the contract state changed. Try again.", "El RPC de Soroban rechazó la transacción al simularla. Suele significar que cambió el estado del contrato. Intenta de nuevo.") - }); - } else { - throw new Error(err); - } - - writeLog(`VAULT WITHDRAW FAILED: ${err}`, 'error'); - } - } catch (e: any) { - console.error('Withdrawal error:', e); - toast.dismiss(toastId); - - const errorMsg = e.message || 'Unknown error'; - - // Retry on transient network errors (exponential backoff: 2s, 4s, 8s) - const isTransient = errorMsg.includes('timeout') || - errorMsg.includes('fetch') || - errorMsg.includes('network') || - errorMsg.includes('ECONNREFUSED') || - errorMsg.includes('504') || - errorMsg.includes('503'); - - if (isTransient && retryCount < MAX_RETRIES) { - const delay = Math.pow(2, retryCount + 1) * 1000; // 2s, 4s, 8s - toast.info(L(`Network issue. Retrying in ${delay / 1000}s...`, `Problema de red. Reintentando en ${delay / 1000}s...`), { - description: L(`Attempt ${retryCount + 1} of ${MAX_RETRIES}`, `Intento ${retryCount + 1} de ${MAX_RETRIES}`) - }); - setTimeout(() => executeWithdraw(amount, retryCount + 1), delay); - return; - } - - if (isTransient) { - toast.error(L("Network unavailable", "Red no disponible"), { - description: L("Couldn't reach the Stellar network after 3 attempts. Check your connection and try again.", "No se pudo llegar a la red de Stellar tras 3 intentos. Revisa tu conexión e intenta de nuevo.") - }); - } else if (errorMsg.includes('User declined')) { - toast.error(L("Transaction cancelled", "Transacción cancelada"), { - description: L("You declined the transaction in Freighter.", "Rechazaste la transacción en Freighter.") - }); - } else { - toast.error(L("Withdrawal failed", "Falló el retiro"), { - description: errorMsg - }); - } - - writeLog(`VAULT WITHDRAW FAILED: ${errorMsg}`, 'error'); - } - }; - - // Nirium agent public key - receives delegation to execute on user vaults - const NIRIUM_AGENT_KEY = 'GAVU2GH5RZUIQKLHM4FTVGTUY2V4XNVGWNGO2T6LVU7U74IYJGGYZ667'; - const AGENT_API = process.env.NEXT_PUBLIC_AGENT_URL || 'https://nirium-agent.fly.dev'; - - const handleAutoRebalanceToggle = async () => { - if (!account || !vaultId) { - toast.error(L("Connect your wallet and create a vault first", "Conecta tu wallet y crea una bóveda primero")); - return; - } - setAutoRebalanceLoading(true); - try { - if (!autoRebalance) { - // Preflight: verifica que la wallet conectada sea el owner on-chain del vault. - // Sin esto, delegate_agent fallaría en vault.owner.require_auth() después de - // que el usuario firme con Freighter - y el auto-recovery dispararía 2 firmas - // adicionales que también fallan. - try { - const vData = await vault.getVault(Number(vaultId)); - const onChainOwner = (vData as any)?.owner; - if (onChainOwner && onChainOwner !== account.address) { - toast.error(L(`This vault belongs to another wallet (${String(onChainOwner).slice(0, 8)}…). Connect that wallet in Freighter or create a new vault.`, `Esta bóveda pertenece a otra wallet (${String(onChainOwner).slice(0, 8)}…). Conecta esa wallet en Freighter o crea una nueva bóveda.`)); - return; - } - } catch { /* si la lectura falla, dejamos que el flujo siga - peor caso, falla la tx */ } - - // 1. Delegate vault to Nirium's agent key on Soroban - capture TX hash - const delegateResult = await vaultDelegateAgent(account.address, vaultId, NIRIUM_AGENT_KEY); - const txHash = (delegateResult as any)?.txHash; - const txSuccess = (delegateResult as any)?.success; - const txError = (delegateResult as any)?.error; - - // Si el contrato rechazó la llamada, casi siempre es porque el agente ya está delegado - // para este vault (estado previo no revocado). Intentamos revoke + re-delegate. - if (txSuccess === false) { - if (typeof txError === 'string' && txError.includes('failed on-chain')) { - try { - await vaultRevokeAgent(account.address, vaultId, NIRIUM_AGENT_KEY, true); - const retry = await vaultDelegateAgent(account.address, vaultId, NIRIUM_AGENT_KEY); - if ((retry as any)?.success === false) { - toast.error(L(`Soroban rejected the delegation: ${(retry as any)?.error ?? 'unknown'}`, `Soroban rechazó la delegación: ${(retry as any)?.error ?? 'unknown'}`)); - return; - } - (delegateResult as any).txHash = (retry as any).txHash; - } catch (e: any) { - toast.error(L(`Couldn't delegate on-chain: ${e?.message ?? txError}`, `No se pudo delegar on-chain: ${e?.message ?? txError}`)); - return; - } - } else { - toast.error(L(`Soroban rejected the delegation: ${txError ?? 'unknown'}`, `Soroban rechazó la delegación: ${txError ?? 'unknown'}`)); - return; - } - } - const finalTxHash = (delegateResult as any).txHash ?? txHash; - - // Optimistic UI: la delegación on-chain ya quedó firmada. Marcamos el nodo - // activo *antes* del POST a Supabase para que (a) el usuario vea feedback - // inmediato (1/10) y (b) si vuelve a clickear, dispare el flujo de STOP - // (revoke) en vez de un nuevo delegate_agent on-chain. - const pendingDelegationId = `demo-del-${Date.now()}`; - setDelegationTxHash(finalTxHash ?? null); - setAutoRebalance(true); - setDelegationId(pendingDelegationId); - localStorage.setItem(`nirium-autorebalance-${account.address}`, JSON.stringify({ - autoRebalance: true, - delegationId: pendingDelegationId, - autoExit, - txHash: finalTxHash ?? null, - rebalanceThreshold, - reverseThreshold, - })); - - // 2. Register delegation in agent backend - reintenta hasta 3 veces si la red Fly→Supabase está degradada - const token = localStorage.getItem('nirium-token') || 'demo-token'; - let newDelegationId: string | null = null; - for (let attempt = 0; attempt < 3 && !newDelegationId; attempt++) { - try { - const res = await fetch(`${AGENT_API}/api/vault/delegate`, { - method: 'POST', - headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, - body: JSON.stringify({ user_wallet: account.address, vault_id: vaultId, rebalance_threshold: rebalanceThreshold }), - }); - if (res.ok) { - const data = await res.json(); - if (data.delegation?.id) newDelegationId = data.delegation.id; - } - } catch { /* siguiente intento */ } - if (!newDelegationId && attempt < 2) await new Promise(r => setTimeout(r, 1500)); - } - - if (!newDelegationId) { - // El registro en Supabase falló - el reconcile sync re-intentará en el próximo tick - // (usa el placeholder demo-del-* para detectar que la fila aún no está sincronizada). - toast.warning(L("On-chain delegation confirmed - syncing with the backend in the background…", "Delegación on-chain confirmada - sincronizando con backend en segundo plano…"), { - action: finalTxHash ? { - label: t.dashboard.toasts.view_tx, - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${finalTxHash}`, '_blank'), - } : undefined, - }); - return; - } - - setDelegationId(newDelegationId); - localStorage.setItem(`nirium-autorebalance-${account.address}`, JSON.stringify({ autoRebalance: true, delegationId: newDelegationId, autoExit, txHash: finalTxHash ?? null, rebalanceThreshold, reverseThreshold })); - - toast.success(t.dashboard.auto_rebalance.toast_enabled, { - action: finalTxHash ? { - label: t.dashboard.toasts.view_tx, - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${finalTxHash}`, '_blank'), - } : undefined, - }); - } else { - // 1. Mark inactive in backend FIRST - para detener el loop incluso si el usuario cancela la firma Freighter - { - const token = localStorage.getItem('nirium-token'); - await fetch(`${AGENT_API}/api/vault/delegate/${delegationId ?? 'none'}`, { - method: 'DELETE', - headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, - body: JSON.stringify({ user_wallet: account.address }), - }).catch(() => {}); - } - - // 2. Update UI state inmediatamente - el toggle/nodo desaparece sin esperar Freighter - setAutoRebalance(false); - setAutoExit(false); - setDelegationId(null); - setDelegationTxHash(null); - localStorage.removeItem(`nirium-autorebalance-${account.address}`); - - // 3. Revocar delegación on-chain en Soroban (best-effort - si el usuario cancela, el loop ya está detenido) - let revokeTxHash: string | undefined; - try { - const revokeResult = await vaultRevokeAgent(account.address, vaultId, NIRIUM_AGENT_KEY); - revokeTxHash = (revokeResult as any)?.txHash; - } catch { /* el usuario canceló o falló la firma - la DB ya está inactiva */ } - - toast.success(t.dashboard.auto_rebalance.toast_disabled, { - action: revokeTxHash ? { - label: t.dashboard.toasts.view_tx, - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${revokeTxHash}`, '_blank'), - } : undefined, - }); - } - } catch (e: any) { - toast.error(`${t.dashboard.auto_rebalance.toast_error}: ${e.message}`); - } finally { - setAutoRebalanceLoading(false); - } - }; - - const handleAutoExitToggle = async () => { - if (!account || !vaultId) { - toast.error(L("Connect your wallet and create a vault first", "Conecta tu wallet y crea una bóveda primero")); - return; - } - if (!delegationId) { - toast.error(t.dashboard.auto_exit.delegation_required); - return; - } - setAutoExitLoading(true); - try { - const newAutoExit = !autoExit; - const token = localStorage.getItem('nirium-token') || 'demo-token'; - // Optimistic update - persist locally first, then try backend - setAutoExit(newAutoExit); - localStorage.setItem(`nirium-autorebalance-${account.address}`, JSON.stringify({ autoRebalance: true, delegationId, autoExit: newAutoExit, txHash: delegationTxHash })); - try { - const res = await fetch(`${AGENT_API}/api/vault/delegate/${delegationId}/reverse`, { - method: 'PATCH', - headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, - body: JSON.stringify({ enabled: newAutoExit, reverse_threshold: reverseThreshold }), - }); - if (!res.ok) console.warn('[Auto-Exit] Backend update failed silently:', await res.text().catch(() => '')); - } catch { /* API unreachable - state already saved locally */ } - toast.success(autoExit ? t.dashboard.auto_exit.toast_disabled : t.dashboard.auto_exit.toast_enabled); - } catch (e: any) { - toast.error(`${t.dashboard.auto_exit.toast_error}: ${e.message}`); - } finally { - setAutoExitLoading(false); - } - }; - - const handleCreateVault = () => { - if (!account) { - toast.error(L("Please connect your Stellar wallet first", "Primero conecta tu wallet de Stellar")); - return; - } - - setConfirmConfig({ - isOpen: true, - // Lo que de verdad hace create_vault en nirium_vault.rs. El texto anterior - // hablaba de "OwnerCap" y "Hot Potato" (patrones de Move/Sui, no de - // Soroban) y de una "pequeña comisión de gas", cuando el contrato cobra - // 12.5 XLM. - title: language === 'es' ? '¿Crear tu bóveda?' : 'Create your vault?', - description: ( -
-

- {language === 'es' ? 'Crea una ' : 'Creates a '} - NiriumVault {baseAsset} - {language === 'es' ? ' en Stellar testnet.' : ' on Stellar testnet.'} -

-
-

- {language === 'es' ? ( - <>• Tú quedas como dueño: retirar a tu wallet requiere tu firma (require_auth)
• Si delegas al agente, opera solo hasta el tope acumulado que tú fijes, y lo puedes revocar cuando quieras - ) : ( - <>• You are the owner: withdrawing to your wallet requires your signature (require_auth)
• If you delegate to the agent, it can only act up to the cumulative cap you set, and you can revoke it anytime - )} -

-
-

- {language === 'es' - ? 'El contrato cobra 12.5 XLM de testnet por crear la bóveda (van a la tesorería de Nirium), más el fee de red.' - : 'The contract charges 12.5 testnet XLM to create the vault (sent to the Nirium treasury), plus the network fee.'} -

-
- ), - icon: , - confirmText: L("CREATE VAULT", "CREAR BÓVEDA"), - type: 'info', - onConfirm: () => { - setConfirmConfig(prev => ({ ...prev, isOpen: false })); - executeCreateVault(); - } - }); - }; - - const executeCreateVault = async () => { - if (!account) return; - - // Network Check (Strict) - if (account.chains?.[0] && account.chains[0] !== 'stellar:testnet') { - toast.error(L("Wrong network", "Red equivocada"), { - description: L("This dashboard runs on Stellar testnet. Switch your wallet's network.", "Este panel corre en Stellar testnet. Cambia la red de tu wallet.") - }); - return; - } - - const toastId = toast.loading(L("Creating your vault on Soroban...", "Creando tu bóveda en Soroban...")); - - try { - // Call the actual Soroban vault contract create_vault function - const vaultName = `Vault-${Date.now()}`; - const targetAssetId = baseAsset === 'USDC' - ? USDC_ASSET_ID - : baseAsset === 'CETES' - ? CETES_ASSET_ID - : NATIVE_ASSET_ID; - const result = await vaultCreate(account.address, targetAssetId, vaultName); - - toast.dismiss(toastId); - - if (result.success && result.result) { - // Extract the vault object from the result - const vaultData = result.result as any; - const numericVaultId = Number(vaultData.vault_id || vaultData.vaultId || vaultData[0]); - - if (!numericVaultId || isNaN(numericVaultId)) { - throw new Error('Failed to extract vault ID from contract response'); - } - - // Store vault data with numeric ID - const storageData = { - vaultId: numericVaultId, - ownerCapId: `cap_${numericVaultId}_${Date.now()}`, - createdAt: Date.now(), - txHash: result.txHash, - contractId: process.env.NEXT_PUBLIC_CONTRACT_VAULT || 'CDMFURE6MYROTA2A6DLD4TN2S4QTN64L2FZ2I2RY2AREONX6DUQOI2S2', - }; - - localStorage.setItem( - `nirium-vault-v2-${baseAsset}-${account.address}`, - JSON.stringify(storageData) - ); - - setVaultId(numericVaultId); - setOwnerCapId(storageData.ownerCapId); - - toast.success(L("Vault created", "Bóveda creada"), { - description: L(`Vault ID: ${numericVaultId} | on-chain`, `ID de bóveda: ${numericVaultId} | en la cadena`), - action: result.txHash ? { - label: "View Tx", - onClick: () => window.open( - `https://stellar.expert/explorer/testnet/tx/${result.txHash}`, - "_blank" - ) - } : undefined - }); - - writeLog( - `VAULT CREATED: ID=${numericVaultId} | Asset=${baseAsset} | Tx: ${result.txHash?.slice(0, 12)}...`, - 'success', - account?.address - ); - } else { - throw new Error(result.error || 'Failed to create vault'); - } - } catch (e: any) { - toast.dismiss(toastId); - console.error("Vault Creation Error:", e); - toast.error(L("Vault creation failed", "No se pudo crear la bóveda"), { - description: e.message || "Failed to create vault on-chain" - }); - writeLog(`VAULT CREATE FAILED: ${e.message}`, 'error', account?.address); - } - }; - - // ═══════════════════════════════════════════════════════ - // MXNE RAMP INTEGRATION - Etherfuse - // ═══════════════════════════════════════════════════════ - - const handleAddCETESTrustline = async () => { - if (!account) { - toast.error(L("Please connect your wallet first", "Primero conecta tu wallet")); - return; - } - - const toastId = toast.loading(L("Adding the CETES trustline...", "Agregando la trustline de CETES...")); - try { - const { signTransaction } = await import("@stellar/freighter-api"); - const { Horizon, Networks, TransactionBuilder, Asset, Operation } = await import("@stellar/stellar-sdk"); - - // 1. Load account from Horizon - const horizonServer = new Horizon.Server("https://horizon-testnet.stellar.org"); - const sourceAccount = await horizonServer.loadAccount(account.address); - - // 2. Build changeTrust transaction - const cetesAsset = new Asset(CETES_ASSET.code, CETES_ASSET.issuer); - const transaction = new TransactionBuilder(sourceAccount, { - fee: "100", - networkPassphrase: Networks.TESTNET, - }) - .addOperation(Operation.changeTrust({ - asset: cetesAsset, - limit: '1000000000', - })) - .setTimeout(300) - .build(); - - // 3. Sign with Freighter - MUST specify address to avoid tx_bad_auth - toast.loading(L("Sign the trustline in your wallet...", "Firma la trustline en tu wallet..."), { id: toastId }); - const txXdr = transaction.toXDR(); - const signedResult = await signTransaction(txXdr, { - networkPassphrase: Networks.TESTNET, - address: account.address, - }); - - if (signedResult && typeof signedResult === 'object' && (signedResult as any).error) { - throw new Error(String((signedResult as any).error)); - } - - const signedXdr = typeof signedResult === 'string' ? signedResult : (signedResult as any).signedTxXdr; - if (!signedXdr) { - throw new Error('Wallet signing was cancelled'); - } - - // 4. Submit signed transaction to Horizon - toast.loading(L("Sending to the Stellar network...", "Enviando a la red de Stellar..."), { id: toastId }); - const signedTx = TransactionBuilder.fromXDR(signedXdr, Networks.TESTNET); - const result = await horizonServer.submitTransaction(signedTx as any); - - toast.dismiss(toastId); - - if (result.successful) { - setHasCetesTrust(true); - toast.success(L("CETES trustline added", "Trustline de CETES agregada"), { - description: L("You can now receive CETES (Mexican treasury bonds) on Stellar", "Ya puedes recibir CETES (bonos del gobierno de México) en Stellar"), - action: { - label: "View Tx", - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${result.hash}`, "_blank") - } - }); - writeLog(`CETES TRUSTLINE ADDED | Tx: ${result.hash?.slice(0, 12)}...`, 'success', account.address); - } else { - throw new Error('Transaction was not successful'); - } - } catch (e: any) { - toast.dismiss(toastId); - - let errorMsg = e.message || "Failed to add CETES trustline"; - if (e.response?.data?.extras?.result_codes) { - const codes = e.response.data.extras.result_codes; - errorMsg = `Horizon: tx=${codes.transaction}, ops=${codes.operations?.join(', ')}`; - } - - toast.error(L("Trustline failed", "Falló la trustline"), { description: errorMsg }); - writeLog(`CETES TRUSTLINE FAILED: ${errorMsg}`, 'error', account?.address); - } - }; - - const handleOpenRamp = async () => { - if (!account) { - toast.error(L("Please connect your wallet first", "Primero conecta tu wallet")); - return; - } - - if (!hasCetesTrust) { - toast.error(L("Add the CETES trustline first", "Primero agrega la trustline de CETES"), { - description: L("You need the CETES trustline before buying", "Necesitas la trustline de CETES antes de comprar") - }); - return; - } - - const toastId = toast.loading(L("Opening the Etherfuse ramp...", "Abriendo la rampa de Etherfuse...")); - - try { - // Get or create persistent customer IDs for this wallet - const { customerId, bankAccountId } = getOrCreateCustomerIds(account.address); - - // Generate onboarding URL via Etherfuse API - const result = await generateOnboardingUrl({ - customerId, - bankAccountId, - publicKey: account.address, - blockchain: 'stellar', - }); - - toast.dismiss(toastId); - - if (result.success && result.data?.url) { - // Open the presigned URL in new tab - window.open(result.data.url, '_blank'); - - toast.success(L("Etherfuse ramp opened (test environment)", "Rampa de Etherfuse abierta (entorno de pruebas)"), { - description: L("Complete KYC to buy CETES with SPEI. The link expires in 15 minutes.", "Completa el KYC para comprar CETES con SPEI. El enlace vence en 15 minutos.") - }); - - writeLog(`ETHERFUSE RAMP: Opened for customer ${customerId}`, 'info', account.address); - } else { - // Fallback: open devnet directly - const fallbackUrl = 'https://devnet.etherfuse.com'; - window.open(fallbackUrl, '_blank'); - toast.info(L("Opened Etherfuse directly", "Se abrió Etherfuse directamente"), { - description: result.error || "Opened Etherfuse devnet portal." - }); - writeLog(`ETHERFUSE RAMP: API issue, opened devnet directly. ${result.error}`, 'warn', account?.address); - } - } catch (e: any) { - toast.dismiss(toastId); - window.open('https://devnet.etherfuse.com', '_blank'); - toast.info(L("Opened Etherfuse directly", "Se abrió Etherfuse directamente"), { - description: L("Couldn't create a signed link, so the portal opened directly.", "No se pudo generar el enlace firmado; se abrió el portal directamente.") - }); - writeLog(`ETHERFUSE RAMP FALLBACK: ${e.message}`, 'warn', account?.address); - } - }; - - const handleDestroyVault = async () => { - if (!account) { - toast.error(L("Please connect your Stellar wallet first", "Primero conecta tu wallet de Stellar")); - return; - } - if (!vaultId) return; - - // Load vault data from localStorage - const savedData = localStorage.getItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - if (!savedData) { - toast.error(L("Can't find the vault data", "No se encuentran los datos de la bóveda")); - return; - } - - let vaultData; - try { - vaultData = JSON.parse(savedData); - } catch { - // Old format without OwnerCap ID - allow force reset - setConfirmConfig({ - isOpen: true, - title: L("Old vault format", "Formato de bóveda antiguo"), - description: ( -
-

{L('This vault was saved in an older format. Resetting this view clears it from this browser only.', 'Esta bóveda se guardó en un formato anterior. Reiniciar la vista la quita solo de este navegador.')}

-
-

- {L('• Clears the saved vault from this browser', '• Borra la bóveda guardada en este navegador')}
- {L('• Nothing changes on-chain', '• No cambia nada en la cadena')} -

-
-
- ), - icon: , - confirmText: L("RESET LOCAL VIEW", "REINICIAR VISTA LOCAL"), - type: 'info', - onConfirm: () => { - localStorage.removeItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - setVaultId(null); - setConfirmConfig(prev => ({ ...prev, isOpen: false })); - toast.info(L("Vault disconnected from this view", "Bóveda desconectada de esta vista"), { - description: L("You can now create a new vault.", "Ya puedes crear una bóveda nueva.") - }); - } - }); - return; - } - - setConfirmConfig({ - isOpen: true, - title: L("Close your vault?", "¿Cerrar tu bóveda?"), - description: ( -
-

{L('This closes your vault on the NiriumVault contract.', 'Esto cierra tu bóveda en el contrato NiriumVault.')}

-
-
-
- {L('Closes the vault on-chain', 'Cierra la bóveda en la cadena')} -
-
-
- {L('Needs your signature (vault owner)', 'Requiere tu firma (dueño de la bóveda)')} -
-
-
- {L('Balance must be 0: withdraw first', 'El saldo debe ser 0: retira primero')} -
-
-

- {L("Can't be undone. Network fee applies.", 'No se puede deshacer. Aplica el fee de red.')} -

-
- ), - icon: , - confirmText: L("CLOSE VAULT", "CERRAR BÓVEDA"), - type: 'danger', - onConfirm: async () => { - setConfirmConfig(prev => ({ ...prev, isOpen: false })); - await executeVaultDestruction(vaultData); - } - }); - }; - - const executeVaultDestruction = async (vaultData: any) => { - if (!account) return; - - // Block close if vault still has balance - user must withdraw first - if (vaultBalance > 0) { - toast.error(L("Withdraw your funds first", "Primero retira tus fondos"), { - description: L(`Vault #${vaultData.vaultId} still has a balance. Withdraw everything before closing.`, `La bóveda #${vaultData.vaultId} todavía tiene saldo. Retira todo antes de cerrarla.`), - duration: 6000, - }); - return; - } - - const toastId = toast.loading(L("Closing the vault on-chain...", "Cerrando la bóveda en la cadena...")); - - try { - const result = await vaultClose(account.address, vaultData.vaultId); - - if (!result.success) { - toast.dismiss(toastId); - const errorMsg = result.error || ""; - // Legacy vault from old contract - can't be closed on-chain, just remove from UI - if (errorMsg.includes("UnreachableCodeReached") || errorMsg.includes("E_VAULT_NOT_FOUND") || errorMsg.includes("InvalidAction")) { - localStorage.removeItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - localStorage.removeItem(`nirium-vault-balance-${vaultData.vaultId}-${baseAsset}`); - setVaultId(null); - setOwnerCapId(null); - setVaultBalance(0); - toast.success(L("Old vault removed", "Bóveda antigua quitada"), { - description: L(`Vault #${vaultData.vaultId} was created on an earlier contract version and was removed from your dashboard. Nothing to do on-chain (it had a 0 balance).`, `La bóveda #${vaultData.vaultId} se creó con una versión anterior del contrato y se quitó de tu panel. No hay nada que hacer en la cadena (tenía saldo 0).`), - duration: 8000, - }); - } else if (errorMsg.includes("0 balance") || errorMsg.includes("withdraw")) { - toast.error(L("Withdraw your funds first", "Primero retira tus fondos"), { - description: L("The contract requires a 0 balance before closing.", "El contrato exige saldo 0 antes de cerrar."), - duration: 6000, - }); - } else { - toast.error(L("Couldn't close the vault", "No se pudo cerrar la bóveda"), { - description: errorMsg, - duration: 6000, - }); - } - return; - } - - const txHash = result.txHash || ""; - - // Clear local storage only after confirmed on-chain close - localStorage.removeItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - localStorage.removeItem(`nirium-vault-balance-${vaultData.vaultId}-${baseAsset}`); - - setVaultId(null); - setOwnerCapId(null); - setVaultBalance(0); - - toast.dismiss(toastId); - toast.success(L("Vault closed", "Bóveda cerrada"), { - description: L(`Vault ${vaultData.vaultId} closed on-chain. Tx: ${txHash.slice(0, 8)}...`, `Bóveda ${vaultData.vaultId} cerrada en la cadena. Tx: ${txHash.slice(0, 8)}...`), - duration: 6000, - action: { - label: "View Tx", - onClick: () => window.open(`https://stellar.expert/explorer/testnet/tx/${txHash}`, "_blank") - } - }); - - writeLog( - `VAULT CLOSED: ID=${vaultData.vaultId} | Tx: ${txHash.slice(0, 12)}...`, - 'success', - account?.address - ); - } catch (error: any) { - toast.dismiss(toastId); - console.error("Close Vault Error:", error); - const errStr = String(error?.message || error || ""); - if (errStr.includes("UnreachableCodeReached") || errStr.includes("E_VAULT_NOT_FOUND") || errStr.includes("InvalidAction")) { - localStorage.removeItem(`nirium-vault-v2-${baseAsset}-${account.address}`); - localStorage.removeItem(`nirium-vault-balance-${vaultData.vaultId}-${baseAsset}`); - setVaultId(null); - setOwnerCapId(null); - setVaultBalance(0); - toast.success(L("Old vault removed", "Bóveda antigua quitada"), { - description: L(`Vault #${vaultData.vaultId} was created on an earlier contract version and was removed from your dashboard.`, `La bóveda #${vaultData.vaultId} se creó con una versión anterior del contrato y se quitó de tu panel.`), - duration: 8000, - }); - } else { - handleWalletError(error); - } - } - }; - - const handleRevokeAgent = async (agentCapId?: string) => { - if (!account) return; - - toast.error(L("Revoking an agent from here isn't available yet.", "Revocar un agente desde aquí todavía no está disponible."), { - description: L("For now, stop agents with the toggle.", "Por ahora, detén los agentes con el interruptor."), - duration: 5000 - }); - - // TODO: Implement with actual object fetching: - // const tx = {} as any; - // const PACKAGE_ID = process.env.NEXT_PUBLIC_PACKAGE_ID; - // const agentCapObjectId = agentCapId || await fetchAgentCapId(account.address); - // - // tx.moveCall({ - // target: `${PACKAGE_ID}::atomic_engine::destroy_agent_cap`, - // arguments: [tx.object(agentCapObjectId)] - // }); - // - // signAndSubmitTransaction({ transaction: tx }, { - // onSuccess: () => { - // toast.success(L("Agent permission revoked", "Permiso del agente revocado")); - // } - // }); - }; - - // --- ACCESS GUARD (Removed for guest viewing) --- return ( -
-
- -
-

{t.dashboard.title}

-
-
{uiNet === 'mainnet' ? 'STELLAR MAINNET' : 'STELLAR TESTNET'} · {t.dashboard.version_live}
-
-
-
+
+
+
+ +
+

{t.dashboard.title}

+
+
{uiNet === 'mainnet' ? 'STELLAR MAINNET' : 'STELLAR TESTNET'} · {t.dashboard.version_live}
-
- - - - {/* 9-nov-2026: el dashboard solo mostraba la bóveda de testnet. La fila de - nodos sigue el switch TEST/MAIN; las herramientas de bóveda de abajo son - de NiriumVault, que solo existe en testnet, y lo dicen. */} -
- - {/* 16-nov-2026: recibos, cobros y reporting van antes que Treasury. */} - -
- -
-
-
- - - {/* Auto-Start Confirmation Modal */} - - {(showAutoStartModal && currentStrategy) && ( -
- setShowAutoStartModal(false)} - className="absolute inset-0 bg-black/80 backdrop-blur-sm" - /> - -
-
- {currentStrategy.emoji} -
-

{t.dashboard.modals.deploy_title.replace('{name}', currentStrategy.name)}

-
-
- {t.dashboard.modals.fee_label} - {t.dashboard.modals.fee_approved} -
- {/* create_vault (nirium_vault.rs) transfiere DEPLOYMENT_FEE = 12.5 XLM - del dueño a la tesorería; antes aquí decía 0.10. */} -

- 12.5 - XLM TESTNET -

-
-

- {t.dashboard.modals.deploy_desc} -

-
- - -
-
-
- )} -
- - - - {/* Strategy Details Modal */} - - {selectedStrategy && ( -
- setSelectedStrategy(null)} - className="absolute inset-0 bg-black/90 backdrop-blur-md" - /> - - {/* Header */} -
- -
-
-
- {selectedStrategy.emoji} -
-
-
-

{selectedStrategy.name}

- -
-

ID: {selectedStrategy.id.slice(0, 8)}...{selectedStrategy.id.slice(-4)}

-
-
-
- - {/* Content Scrollable */} -
- - {/* Key Metrics Grid. Solo lo que trae el registro de la estrategia: - antes había "Profit 24h" fijo en +0.24 XLM y "Uptime" con - Math.random(), presentados como métricas reales. */} -
-
-

{language === 'es' ? 'Tasa objetivo' : 'Target rate'}

-

{selectedStrategy.yield ?? '-'}

-

{language === 'es' ? 'No garantizada' : 'Not guaranteed'}

-
-
-

{language === 'es' ? 'Red' : 'Network'}

-

Testnet

-
-
- - {/* Transaction Info */} -
-

- - {L('Latest execution', 'Última ejecución')} -

- -
-
- -
- {L('Transaction hash', 'Hash de la transacción')} - {selectedStrategy.tx_digest ? ( - - {selectedStrategy.tx_digest.slice(0, 6)}...{selectedStrategy.tx_digest.slice(-4)} - - - ) : ( - {L('Pending...', 'Pendiente...')} - )} -
- -
-
-

{L('Network', 'Red')}

-

Stellar Testnet

-
-
- {/* El id tal cual. Antes se adivinaba un protocolo por - substring, con nombres que no son de Stellar - (Bluefin Perps, Wormhole) y "Blend / Soroswap" por - defecto para cualquier otro id. */} -

{language === 'es' ? 'Estrategia' : 'Strategy'}

-

- {selectedStrategy?.strategy_id ?? '-'} -

-
-
-
-
- - {/* Installed Plugins Section */} -
-

- - {L('Installed plugins', 'Plugins instalados')} -

- - {isSkillsLoading ? ( -
-
-
-
-
-
- ) : activePlugins.length > 0 ? ( -
- {activePlugins.map((skill: any) => ( -
-
-
- {skill.isGlobal ? '🌐' : '🛠️'} -
-
-
-

{skill.name}

- {skill.isGlobal && ( - GLOBAL - )} -
-

v{skill.version}

-
-
- -
- ))} -
- ) : ( -
-

{L('No plugins installed.', 'No hay plugins instalados.')}

-
- )} -
- - {/* Installed Skills Section */} -
-

- - {L('Installed skills', 'Skills instaladas')} -

- - {isSkillsLoading ? ( -
-
-
-
-
-
- ) : tradingSkills.length > 0 ? ( -
- {tradingSkills.map((skill: any) => ( -
-
-
- {skill.isGlobal ? '🌐' : '🛠️'} -
-
-
-

{skill.name}

- {skill.isGlobal && ( - GLOBAL - )} -
-

v{skill.version}

-
-
- -
- ))} -
- ) : ( -
-

{L('No skills installed.', 'No hay skills instaladas.')}

-
- )} -
- - {/* Agent Configuration (Technical) */} - {selectedStrategy.agentCapId && ( -
-

- - {L('Agent', 'Agente')} -

-
-
-

{L('Agent ID', 'ID del agente')}

-

{selectedStrategy.agentCapId}

-
- -
-
- )} -
- - {/* Actions Footer */} -
- - -
-
-
- )} -
- - {confirmConfig.isOpen && ( -
- setConfirmConfig(prev => ({ ...prev, isOpen: false }))} - className="absolute inset-0 bg-black/90 backdrop-blur-md" - /> - - {/* Decorative Glow */} -
- -
-
- {confirmConfig.icon && ( -
- {confirmConfig.icon} -
- )} -
- -

- {confirmConfig.title} -

- -
- {confirmConfig.description} -
- -
- - -
-
- -
- )} - - - {/* Treasury: herramientas de NiriumVault en testnet, plegadas por defecto. */} -
setTreasuryOpen((e.currentTarget as HTMLDetailsElement).open)} - className="max-w-[1600px] mx-auto px-4 md:px-8 mb-8 relative z-10 group/treasury" - > - -
-

- {L('Treasury · testnet vault tools', 'Treasury · herramientas de bóveda en testnet')} -

-

- {L('Create and fund a NiriumVault, delegate the agent and watch its feed. Testnet only, no real value.', 'Crea y fondea una NiriumVault, delega al agente y mira su feed. Solo testnet, sin valor real.')} -

-

- {L('On mainnet, Treasury is invite-only until we have a written legal opinion.', 'En mainnet, Treasury es solo por invitación hasta tener una opinión legal por escrito.')} -

-
- -
-
- {/* 21-nov-2026 (D3): en mainnet esto mostraba herramientas de NiriumVault en cero - (bóvedas 0, nodos 0, comisiones 0.0000). NiriumVault solo existe en testnet. */} - {uiNet === 'mainnet' ? ( -
-

- {L('NiriumVault lives on testnet. Switch to TEST in the menu to create a vault and try the nodes. On mainnet the treasury is a DeFindex vault you own, invite-only: ', 'NiriumVault vive en testnet. Cambia a TEST en el menú para crear una bóveda y probar los nodos. En mainnet la tesorería es una bóveda de DeFindex tuya, solo por invitación: ')} - /security. -

-
- ) : (<> - - - {/* On-Chain Soroban Verifiable Stats */} -
-
-

- - {t.dashboard.stats.wallets} -

-
- {onChainVaultCount !== null ? onChainVaultCount : '--'} - {language === 'es' ? 'DESPLIEGUES' : 'DEPLOYS'} -
-
-
-

- - {t.dashboard.stats.helpers} -

-
- {activeStrategies.length + (autoRebalance ? 1 : 0) + (autoExit ? 1 : 0)} - {language === 'es' ? 'NODOS' : 'NODES'} -
-
-
-
-

- - {t.dashboard.stats.treasury} - TESTNET -

-
- {onChainTotalFees !== null ? onChainTotalFees.toFixed(4) : '-'} - XLM -
-
-
- - {/* Real-Time Analytics Bar */} -
-
-

{t.dashboard.stats.secured_capital}

-
- {vaultBalance.toLocaleString(undefined, { maximumFractionDigits: 2 })} {baseAsset} -
-
-
- WALLET: {baseAsset === 'CETES' ? parseFloat(cetesBalance).toFixed(3) : walletBalance.toFixed(3)} {baseAsset} -
-
-
-

- 🇲🇽 {L('Tokenized CETES (Etherfuse, independent third party)', 'CETES tokenizados (Etherfuse, tercero independiente)')} -

-
- {parseFloat(cetesBalance).toLocaleString(undefined, { maximumFractionDigits: 2 })} CETES -
-
- {hasCetesTrust ? ( - <> -
- {language === 'es' - ? 'Comprar CETES vía SPEI (entorno de pruebas de Etherfuse)' - : 'Buy CETES via SPEI (Etherfuse test environment)'} - - ) : ( - - )} -
-
-
-

{t.dashboard.payment_streams.network_fee}

- {/* Sin dato, "-". Antes caía a 100 stroops y convertía a USD con un - precio de XLM fijo (0.155) que no se actualizaba. */} -
- {currentMarketState?.baseFee ?? '-'} stroops -
-
{language === 'es' ? 'Fee base de la red' : 'Network base fee'}
-
-
- -
- {/* Main Chart Section */} - - {/* Persistent Secure Vault Control */} -
-
-
-
- - {activeStrategies.length > 0 && vaultId && ( -
- )} -
-
-
-

- {t.dashboard.vault_control.title} - {vaultId && {t.dashboard.stats.status_active}} -

-
- - - -
-
-

- {vaultId ? `ID: ${vaultId}` : L('Vault ID: not created', 'ID de bóveda: sin crear')} • {vaultBalance.toFixed(2)} {baseAsset} {L('in the vault', 'en la bóveda')} -

-
- {vaultId ? ( - - - {t.dashboard.vault_control.unlocked} 🔓 - - ) : ( - - - {t.dashboard.vault_control.locked} 🔒 - - )} - {vaultId && ( - - )} -
-
-
+ -
- {!vaultId ? ( - - ) : ( -
- - -
- )} -
+
+ + +
+
- - {/* Auto-Rebalance Toggle - only for USDC vaults */} - {vaultId && baseAsset === 'USDC' && ( -
- {/* Threshold config - visible only when toggle is OFF */} - {!autoRebalance && ( -
-
-

- {language === 'es' ? 'Mover cuando CETES supere' : 'Move when CETES exceeds'} -

- {rebalanceThreshold.toFixed(1)}% -
- setRebalanceThreshold(parseFloat(e.target.value))} - className="w-full h-1.5 accent-stellar-teal cursor-pointer" - /> -
- 2% - {(currentMarketState?.etherfuseApy ?? 0) > 0 ? ( - - {language === 'es' ? 'Ref. fija (12-nov-2026)' : 'Fixed ref. (12 Nov 2026)'}: {currentMarketState!.etherfuseApy.toFixed(2)}% - - ) : null} - 8% -
-
- )} -
-
-

- - {t.dashboard.auto_rebalance.label} -

-

- {autoRebalance - ? `CETES > ${rebalanceThreshold.toFixed(1)}% - ${t.dashboard.auto_rebalance.enabled_desc}` - : t.dashboard.auto_rebalance.disabled_desc} -

-
- -
-
- )} - {vaultId && baseAsset === 'CETES' && ( -
- {!autoExit && delegationId && ( -
-
-

- {language === 'es' ? 'Salir a USDC si CETES baja de' : 'Exit to USDC if CETES drops below'} -

- {reverseThreshold.toFixed(1)}% -
- setReverseThreshold(parseFloat(e.target.value))} - className="w-full h-1.5 accent-amber-400 cursor-pointer" - /> -
- 1% - {(currentMarketState?.etherfuseApy ?? 0) > 0 ? ( - - {language === 'es' ? 'Ref. fija (12-nov-2026)' : 'Fixed ref. (12 Nov 2026)'}: {currentMarketState!.etherfuseApy.toFixed(2)}% - - ) : null} - 6% -
-
- )} -
-
-

- - {t.dashboard.auto_exit.label} -

-

- {autoExit - ? `CETES < ${reverseThreshold.toFixed(1)}% - ${t.dashboard.auto_exit.enabled_desc}` - : t.dashboard.auto_exit.disabled_desc} -

-
- -
-
- )} - {vaultId && baseAsset === 'XLM' && ( -
- -

- {t.dashboard.xlm_vault_info} -

-
- )} - - {/* Background Glow Effect */} -
0 ? 'bg-green-500' : 'bg-stellar-teal'}`}>
-
- - {/* Fleet Grid Section */} -
-
-

- 0 || autoRebalance) ? "animate-spin-slow text-stellar-teal" : "text-gray-600"} /> - {t.dashboard.stats.helpers} ({activeStrategies.length + (autoRebalance ? 1 : 0)}/10) -

- {activeStrategies.length === 0 && !autoRebalance && ( - - )} -
- - {(activeStrategies.length > 0 || autoRebalance || autoExit) ? ( -
- {/* Nirium Auto-Rebalance Agent Node */} - {autoRebalance && ( - -
-
-
- 🤖 -
-

{t.dashboard.auto_rebalance.node_title}

- - - {t.dashboard.auto_rebalance.agent_active} - -
-
-
-
-
-

{t.dashboard.auto_rebalance.node_trigger}

-

CETES > {rebalanceThreshold.toFixed(1)}%

-
-
-

{t.dashboard.auto_rebalance.node_vault}

-

#{vaultId}

-
-
-
- {delegationTxHash ? ( - - - Tx: {delegationTxHash.slice(0, 8)}...{delegationTxHash.slice(-4)} - - ) : ( - {t.dashboard.auto_rebalance.node_footer} - )} - -
- - )} - {/* Auto-Exit Node */} - {autoExit && ( - -
-
-
- 🔄 -
-

{t.dashboard.auto_exit.node_title}

- - - {t.dashboard.auto_exit.agent_active} - -
-
-
-
-
-

{t.dashboard.auto_exit.node_trigger}

-

CETES < {reverseThreshold.toFixed(1)}%

-
-
-

{t.dashboard.auto_exit.node_vault}

-

#{vaultId}

-
-
-
- {t.dashboard.auto_exit.node_footer} - -
- - )} - {activeStrategies.slice(0, 10).map((strat, i) => { - // Se muestra la tasa objetivo del registro. Antes era la APY de - // Blend + un "boost" sacado del primer carácter del id, con - // etiqueta "est.", y una curva SVG decorativa debajo. - return ( - -
-
- {strat.emoji} -
-

{strat.name}

- - - {t.dashboard.stats.status_active} - -
-
-
-
{strat.yield ?? '-'}
-
{language === 'es' ? 'Tasa objetivo, no garantizada' : 'Target rate, not guaranteed'}
-
-
- -
- -
- {strat.tx_digest ? ( - - Tx: {strat.tx_digest.slice(0, 6)}...{strat.tx_digest.slice(-4)} - - - ) : ( - {L('Starting...', 'Iniciando...')} - )} - - -
- - ); - })} -
- ) : ( -
-
-
- 💤 -
-
-

{t.dashboard.no_helpers}

-

{t.dashboard.onboarding_desc}

-
-
- )} -
- - {/* x402 / MPP institutional settlement panels hidden for now - the - capability is live but has no real settlement traffic yet (buyers - disabled for stability), so they showed empty $0.00 / "Awaiting - corporate routing". Re-enable once a separate buyer agent feeds them. -
- -
- */} -
- - {/* Right Column: Stats & Agent Controls */} -
- - {/* Active Strategies Fleet */} - -
- -
- -

- {t.dashboard.your_helpers} - {activeStrategies.length + (autoRebalance ? 1 : 0) + (autoExit ? 1 : 0)} {language === 'es' ? 'ACTIVOS' : 'ACTIVE'} -

- - {activeStrategies.length === 0 && !autoRebalance && !autoExit ? ( -
-
- 💤 -
-

{t.dashboard.no_helpers}

-

{t.dashboard.no_helpers_desc}

- -
- ) : ( -
- {activeStrategies.map((strat, idx) => ( -
-
-
- {strat.emoji} -
-

{strat.name}

- -
-
-
-
{strat.yield}
-
{t.dashboard.payment_streams.target_yield}
-
-
-
- - -
-
- ))} -
- )} - - {/* Quick Actions at the bottom of the Fleet card */} -
- - - - -
-
- - {/* CETES Reference Rate (replaces Blend/Phoenix) */} - {/* 21-nov-2026 (D4): aquí se repetían la tasa CETES (queda en el ticker) y el fee de red (queda arriba). */} - - {/* Telemetry Network Thought Process */} - - {/* El Audit Trail subió a la sección de recibos (16-nov-2026). */} -
-
- )} +
-
- {/* Background Elements */} -
-
-
-
- -
- ); -} - -export default function Dashboard() { - const { t } = useLanguage(); - return ( -
- {/* @ts-ignore - React 19 type mismatch in Next.js */} - -
-
-

{t.dashboard.loading_dashboard}

-
+
+
+
- }> - -
+
- ) + ); } diff --git a/apps/web/app/(app)/developers/layout.tsx b/apps/web/app/(app)/developers/layout.tsx index 4226af80..2bc6b41a 100644 --- a/apps/web/app/(app)/developers/layout.tsx +++ b/apps/web/app/(app)/developers/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/developers", title: "Build on Nirium", - description: "The nirium package for TypeScript and Python, a REST API, an MCP server and x402 per-request payments on Stellar.", + description: "The nirium package for TypeScript and Python, a REST API, an MCP server and x402 per-request payments on Stellar, plus nirium-solana and nirium-avalanche.", }); export default function DevelopersLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/developers/page.tsx b/apps/web/app/(app)/developers/page.tsx index 6357ba37..bab78869 100644 --- a/apps/web/app/(app)/developers/page.tsx +++ b/apps/web/app/(app)/developers/page.tsx @@ -7,7 +7,7 @@ import { Code2, Terminal, Zap, ArrowRight, CheckCircle2, Copy, Sparkles, Package, Cpu, Globe, ChevronRight, Server, Boxes, Layers, Shield, ExternalLink, Activity, - Lock, TrendingUp, Layers as LayersIcon, Send + Lock, Layers as LayersIcon, Send } from "lucide-react"; import { ComplianceBanner } from "@/components/ui/ComplianceBanner"; import { PollarPayCard } from "@/components/shared/PollarPayCard"; @@ -55,15 +55,15 @@ const agent = new Agent({ baseUrl: "https://nirium-agent.fly.dev", // mainnet: https://nirium-agent-mainnet.fly.dev }); -// Live market data - rates attributed to their source -const market = await agent.getMarket(); - -// The node catalog: what runs, on which network -const nodes = await agent.getNodes(); - // Anchor evidence to IPFS and get a verifiable CID back const { cid, document } = await agent.anchorAuditRecord({ hash: "" }); -// keep \`document\`: receiptCid(document) === cid, even if IPFS loses it`; +// keep \`document\`: receiptCid(document) === cid, even if IPFS loses it + +// Reporting: payments and receipts for a network and period +const summary = await agent.getReportingSummary({ network: "testnet" }); + +// The node catalog: what runs, on which network +const nodes = await agent.getNodes();`; const X402_CODE = `import { Agent } from "nirium"; @@ -141,12 +141,14 @@ const MCP_CODE = `// Claude Desktop: claude_desktop_config.json // esas filas devolvía 404 en la página que un desarrollador abre primero. const ENDPOINTS = [ // Público + // 27-nov-2026: Audit Trail y Reporting primero, como en el resto del sitio. + { method: 'POST', path: '/api/audit/log', desc_en: 'Anchor a record or hash to IPFS', desc_es: 'Ancla un registro o un hash en IPFS' }, + { method: 'GET', path: '/api/reporting/summary', desc_en: 'Payments and receipts by period', desc_es: 'Pagos y recibos por periodo' }, + { method: 'POST', path: '/api/audit/binding', desc_en: 'Receipts from Solana, Avalanche, Base and Arbitrum (payments and decisions)', desc_es: 'Recibos de Solana, Avalanche, Base y Arbitrum (pagos y decisiones)' }, { method: 'GET', path: '/health', desc_en: 'Liveness probe', desc_es: 'Sonda de disponibilidad' }, { method: 'GET', path: '/api/info', desc_en: 'Agent metadata, network and version', desc_es: 'Metadatos del agente, red y versión' }, - { method: 'GET', path: '/api/tickers', desc_en: 'CETES + Blend reference rates', desc_es: 'Tasas de referencia CETES + Blend' }, { method: 'GET', path: '/api/nodes', desc_en: 'Execution Node catalog (status + custody)', desc_es: 'Catálogo de Execution Nodes (estado + custodia)' }, { method: 'GET', path: '/api/loop/status', desc_en: 'Autonomous loop state + last decision', desc_es: 'Estado del loop autónomo + última decisión' }, - { method: 'POST', path: '/api/execute-demo', desc_en: 'Run a demo rebalance - no key required', desc_es: 'Corre un rebalanceo demo - sin llave' }, // Auth { method: 'POST', path: '/api/auth/token', desc_en: 'Exchange credentials for a JWT', desc_es: 'Cambia credenciales por un JWT' }, @@ -159,14 +161,12 @@ const ENDPOINTS = [ // responden 501 como si fueran igual de reales que market. { method: 'GET', path: '/api/v1/premium/signals', desc_en: 'Premium signals - $0.02 USDC (x402, testnet only)', desc_es: 'Señales premium - $0.02 USDC (x402, solo testnet)' }, { method: 'GET', path: '/api/v1/premium/market', desc_en: 'Enriched market state - $0.05 USDC (x402, mainnet + testnet)', desc_es: 'Estado de mercado - $0.05 USDC (x402, mainnet + testnet)' }, - { method: 'POST', path: '/api/v1/premium/execute', desc_en: 'Paid strategy execution - $0.25 USDC (x402, testnet only)', desc_es: 'Ejecución pagada - $0.25 USDC (x402, solo testnet)' }, // MPP Charge - mismo patrón: signals/execute 501 en el box de mainnet // (verificado en vivo), solo market corre en las dos redes. // signals y execute de MPP responden 501 en el nodo de mainnet (revisado 9-nov-2026), igual que en x402. { method: 'GET', path: '/api/v1/mpp/signals', desc_en: 'Premium signals - $0.02 USDC per call (testnet only; verified 15 Oct 2026)', desc_es: 'Señales premium - $0.02 USDC por llamada (solo testnet; verificado el 15-oct-2026)' }, { method: 'GET', path: '/api/v1/mpp/market', desc_en: 'Enriched market state - $0.05 USDC (testnet: verified 15 Oct 2026 · mainnet: not tested)', desc_es: 'Estado de mercado enriquecido - $0.05 USDC (testnet: verificado el 15-oct-2026 · mainnet: sin probar)' }, - { method: 'POST', path: '/api/v1/mpp/execute', desc_en: 'Paid strategy execution - $0.25 USDC (testnet only; implemented, not tested)', desc_es: 'Ejecución de estrategia pagada - $0.25 USDC (solo testnet; implementado, sin probar)' }, { method: 'GET', path: '/api/v1/mpp/info', desc_en: 'Active mode, routes and pricing', desc_es: 'Modo activo, rutas y precios' }, // Audit Trail @@ -177,24 +177,19 @@ const ENDPOINTS = [ { method: 'GET', path: '/api/reporting/summary', desc_en: 'Consolidated summary by period and network', desc_es: 'Sumario consolidado por periodo y red' }, { method: 'GET', path: '/api/reporting/export', desc_en: 'The rows behind the summary (CSV / JSON), no CIDs', desc_es: 'Las filas detrás del resumen (CSV / JSON), sin CIDs' }, - // Payouts - { method: 'POST', path: '/api/payroll/run', desc_en: 'Build a batch payout (unsigned XDR)', desc_es: 'Arma un pago batch (XDR sin firmar)' }, - { method: 'POST', path: '/api/payroll/submit', desc_en: 'Broadcast company-signed payout', desc_es: 'Transmite el pago firmado por la empresa' }, - { method: 'POST', path: '/api/payroll/onboard', desc_en: 'Add a USDC trustline (self-signed)', desc_es: 'Agrega trustline USDC (self-signed)' }, - { method: 'GET', path: '/api/payroll/runs', desc_en: 'Payout history: amount, recipient count, tx', desc_es: 'Historial de pagos: monto, destinatarios, tx' }, ]; // Descripciones tomadas de nirium-mcp 0.6.4 (server.tool). Antes la lista tenía 11 de 25 // y dejaba fuera anchor_audit_record, que es el producto principal. +// 28-nov-2026: desde nirium-mcp 0.7.0 las 11 de tesorería vienen apagadas (opt-in, solo testnet), +// así que aquí solo van herramientas que carga por defecto (14). const MCP_TOOLS = [ { name: 'anchor_audit_record', desc_en: 'Anchor evidence to IPFS and get back a CID. Free', desc_es: 'Ancla evidencia en IPFS y regresa un CID. Gratis' }, - { name: 'get_reporting_summary', desc_en: 'Summary of settled payouts, x402 receipts and IPFS anchors for a period', desc_es: 'Resumen de pagos liquidados, recibos x402 y anclajes en IPFS de un periodo' }, + { name: 'get_reporting_summary', desc_en: 'Summary of x402 receipts and IPFS anchors for a period', desc_es: 'Resumen de recibos x402 y anclajes en IPFS de un periodo' }, { name: 'get_nodes', desc_en: 'Nirium nodes with live status, custody model and network. Free', desc_es: 'Nodos de Nirium con estado en vivo, modelo de custodia y red. Gratis' }, { name: 'get_market_state', desc_en: 'XLM/USDC price, SDEX spread, base fee, Blend rate, CETES rate. Free', desc_es: 'Precio XLM/USDC, spread del SDEX, base fee, tasa de Blend y de CETES. Gratis' }, { name: 'get_premium_market', desc_en: 'Market state with sourced reference rates, paid via x402 ($0.05 USDC). Data, not advice', desc_es: 'Estado de mercado con tasas y su fuente, pagado vía x402 ($0.05 USDC). Datos, no consejo' }, - { name: 'get_treasury_info', desc_en: 'What role Nirium holds on DeFindex vaults and what it cannot do. Free', desc_es: 'Qué rol tiene Nirium en las bóvedas de DeFindex y qué no puede hacer. Gratis' }, - { name: 'get_treasury_vault', desc_en: "A DeFindex vault's roles, assets and managed funds. Free", desc_es: 'Roles, activos y fondos de una bóveda de DeFindex. Gratis' }, - { name: 'execute_demo', desc_en: 'Dry-run a strategy via Soroban simulation, no real transaction. Free', desc_es: 'Simula una estrategia en Soroban, sin transacción real. Gratis' }, + { name: 'get_wallet_info', desc_en: 'The wallet and payment setup of this MCP session. Free', desc_es: 'La wallet y la configuración de pagos de esta sesión MCP. Gratis' }, ]; @@ -271,6 +266,12 @@ export default function DevelopersPage() { pip ↗
+

+ {lang('On Solana or Avalanche? Charge, pay and bind the receipt to the transfer with ', '¿En Solana o Avalanche? Cobra, paga y liga el recibo a la transferencia con ')} + nirium-solana{lang(' or ', ' o ')} + nirium-avalanche{lang(': tested examples on ', ': ejemplos probados en ')} + /chains. +

@@ -291,8 +292,8 @@ export default function DevelopersPage() {

{isMain - ? lang('Read market data, list the nodes and anchor a receipt. Same code on mainnet with your API key; prices are on /pricing.', - 'Lee datos de mercado, lista los nodos y ancla un recibo. El mismo código en mainnet con tu API key; los precios están en /pricing.') + ? lang('Anchor a receipt, read the Reporting summary and list the nodes. Same code on mainnet with your API key; prices are on /pricing.', + 'Ancla un recibo, lee el resumen de Reporting y lista los nodos. El mismo código en mainnet con tu API key; los precios están en /pricing.') : t.developers_page.quickstart.subtitle}

@@ -361,8 +362,8 @@ export default function DevelopersPage() {
{lang('No facilitator', 'Sin facilitador')} @@ -400,12 +401,6 @@ export default function DevelopersPage() { avail: lang('Mainnet + testnet', 'Mainnet + testnet'), why: null, }, - { - ep: 'POST /api/v1/premium/execute', - price: '$0.25', - avail: lang('Testnet only', 'Solo testnet'), - why: lang('needs a signing key the mainnet box deliberately does not hold', 'necesita una llave firmante que el box de mainnet deliberadamente no tiene'), - }, { ep: 'GET /api/v1/mpp/signals', price: '$0.02', @@ -418,12 +413,6 @@ export default function DevelopersPage() { avail: lang('testnet: verified 15 Oct 2026 · mainnet: not tested', 'testnet: verificado el 15-oct-2026 · mainnet: sin probar'), why: lang('settled payments on Horizon testnet; for paid access on mainnet, use x402', 'pagos liquidados en Horizon testnet; para acceso pagado en mainnet, usa x402'), }, - { - ep: 'POST /api/v1/mpp/execute', - price: '$0.25', - avail: lang('Testnet only; implemented, not tested', 'Solo testnet; implementado, sin probar'), - why: lang('no MPP payment has been sent to this route yet; use x402', 'todavía no se ha enviado un pago MPP a esta ruta; usa x402'), - }, ].map((row) => ( {row.ep} @@ -514,7 +503,8 @@ export default function DevelopersPage() {
))}
@@ -537,7 +527,7 @@ export default function DevelopersPage() { className="mb-6 px-4 py-1.5 rounded-full bg-stellar-teal/10 border border-stellar-teal/30 flex items-center gap-2" > - {lang('25 tools in nirium-mcp 0.6.13', '25 herramientas en nirium-mcp 0.6.13')} + {lang('14 tools in nirium-mcp 0.8.0', '14 herramientas en nirium-mcp 0.8.0')}

@@ -599,28 +589,6 @@ export default function DevelopersPage() {
{[ - { - cat: language === 'es' ? 'Seguridad y Auth' : 'Auth & Security', - icon: Lock, - eps: [ - { m: 'POST', p: '/api/auth/token', d: 'Exchange credentials for a JWT', de: 'Cambia credenciales por un JWT', s: 'PUBLIC' }, - { m: 'POST', p: '/api/auth/keys', d: 'Issue an API key', de: 'Emite una API key', s: 'KEY' }, - { m: 'GET', p: '/health', d: 'Liveness probe', de: 'Comprueba que el nodo responde', s: 'PUBLIC' }, - { m: 'POST', p: '/api/public/authenticate', d: 'Wallet-signature verification', de: 'Verificación con firma de wallet', s: 'PUBLIC' }, - ] - }, - { - // Este loop es la demo de testnet (escanea y cotiza); el firmante real de - // Treasury en mainnet es otro proceso y no se controla desde aquí. - cat: language === 'es' ? 'Loop de escaneo (demo de testnet)' : 'Scan loop (testnet demo)', - icon: Cpu, - eps: [ - { m: 'POST', p: '/api/loop/start', d: 'Start the scan loop', de: 'Arranca el loop de escaneo', s: 'KEY' }, - { m: 'POST', p: '/api/loop/stop', d: 'Stop the scan loop', de: 'Detiene el loop de escaneo', s: 'KEY' }, - { m: 'POST', p: '/api/execute', d: 'Run one strategy step', de: 'Corre un paso de estrategia', s: 'KEY' }, - { m: 'GET', p: '/api/loop/status', d: 'Loop state and last decision', de: 'Estado del loop y última decisión', s: 'PUBLIC' }, - ] - }, { cat: language === 'es' ? 'Audit Trail y Reporting' : 'Audit Trail & Reporting', icon: Shield, @@ -630,26 +598,24 @@ export default function DevelopersPage() { { m: 'GET', p: '/api/reporting/summary', d: 'Summary by period and network', de: 'Resumen por periodo y red', s: 'PUBLIC' }, { m: 'GET', p: '/api/reporting/info', d: 'What Reporting exposes and its limits', de: 'Qué expone Reporting y sus límites', s: 'PUBLIC' }, { m: 'GET', p: '/api/reporting/export', d: 'Rows behind the summary, no CIDs', de: 'Filas detrás del resumen, sin CIDs', s: 'PUBLIC' }, + { m: 'POST', p: '/api/audit/binding', d: 'Anchor a payer-signed receipt from Solana or Avalanche: a payment bound to its USDC transfer, or a policy decision. Since 27 Nov 2026', de: 'Ancla un recibo firmado por quien paga en Solana o Avalanche: un pago ligado a su transferencia de USDC, o una decisión de la política. Desde el 27 nov 2026', s: 'PUBLIC' }, ] }, { - cat: language === 'es' ? 'Datos de mercado' : 'Market data', - icon: TrendingUp, + cat: language === 'es' ? 'Seguridad y Auth' : 'Auth & Security', + icon: Lock, eps: [ - { m: 'GET', p: '/api/market', d: 'Market state and reference rates', de: 'Estado del mercado y tasas de referencia', s: 'KEY' }, - { m: 'GET', p: '/api/tickers', d: 'CETES and Blend reference rates', de: 'Tasas de referencia de CETES y Blend', s: 'PUBLIC' }, - { m: 'GET', p: '/api/strategies', d: 'Built-in strategy catalog (testnet)', de: 'Catálogo de estrategias incluidas (testnet)', s: 'PUBLIC' }, - { m: 'GET', p: '/api/signals/recent', d: 'Recent signals from the scan loop (testnet)', de: 'Señales recientes del loop de escaneo (testnet)', s: 'PUBLIC' }, + { m: 'POST', p: '/api/auth/token', d: 'Exchange credentials for a JWT', de: 'Cambia credenciales por un JWT', s: 'PUBLIC' }, + { m: 'POST', p: '/api/auth/keys', d: 'Issue an API key', de: 'Emite una API key', s: 'KEY' }, + { m: 'GET', p: '/health', d: 'Liveness probe', de: 'Comprueba que el nodo responde', s: 'PUBLIC' }, + { m: 'POST', p: '/api/public/authenticate', d: 'Wallet-signature verification', de: 'Verificación con firma de wallet', s: 'PUBLIC' }, ] }, { - cat: language === 'es' ? 'Payouts y nodos' : 'Payouts & nodes', + cat: language === 'es' ? 'Nodos' : 'Nodes', icon: Send, eps: [ { m: 'GET', p: '/api/nodes', d: 'Node catalog', de: 'Catálogo de nodos', s: 'PUBLIC' }, - { m: 'POST', p: '/api/payroll/run', d: 'Build a batch payout (unsigned)', de: 'Arma una dispersión en lote (sin firmar)', s: 'KEY' }, - { m: 'POST', p: '/api/payroll/submit', d: 'Broadcast a signed payout', de: 'Transmite una dispersión firmada', s: 'KEY' }, - { m: 'POST', p: '/api/payroll/onboard', d: 'Self-signed USDC trustline', de: 'Trustline de USDC que firmas tú', s: 'KEY' }, ] }, ].map((group, gIdx) => ( @@ -721,8 +687,6 @@ export default function DevelopersPage() {
{[ - { name: 'NiriumVault', id: 'CDMFURE6MYROTA2A6DLD4TN2S4QTN64L2FZ2I2RY2AREONX6DUQOI2S2', desc_en: 'Vaults and agent delegation; supports a 2-of-3 pause, no cosigners registered yet', desc_es: 'Bóvedas y delegación a agentes; soporta pausa 2-de-3, sin cosignatarios registrados todavía' }, - { name: 'CETES (testnet)', id: 'CC72F57YTPX76HAA64JQOEGHQAPSADQWSY5DWVBR66JINPFDLNCQYHIC', desc_en: 'Etherfuse CETES token used by the testnet Treasury strategies', desc_es: 'Token CETES de Etherfuse que usan las estrategias de Treasury en testnet' }, { name: 'USDC (testnet SAC)', id: 'CBIELTK6YBZJU5UP2WWQEUCYKLPU6AUNZ2BQ4WWFEIE3USCIHMXQDAMA', desc_en: 'USDC the x402 endpoints charge on testnet', desc_es: 'USDC que cobran los endpoints x402 en testnet' }, ].map((contract) => (
@@ -783,7 +747,6 @@ export default function DevelopersPage() {
{[ { k: 'x402Settlements', d: lang('Mainnet payments - totals, distinct payers, each labeled internal/external', 'Pagos mainnet - totales, pagadores distintos, cada uno etiquetado interno/externo') }, - { k: 'treasuryRebalances', d: lang('Treasury Node rebalance() calls, mainnet', 'Llamadas rebalance() del Treasury Node, mainnet') }, { k: 'auditTrailAnchors', d: lang('IPFS anchor count from our own reporting API', 'Conteo de anclajes IPFS desde nuestra propia API de reportería') }, { k: 'npm / pypi', d: lang('Download counts, read live from npmjs.org / pypistats.org', 'Descargas, leídas en vivo de npmjs.org / pypistats.org') }, { k: 'externalMergedPRs', d: lang('PRs merged by maintainers we don’t control', 'PRs mergeadas por maintainers que no controlamos') }, diff --git a/apps/web/app/(app)/disclaimers/page.tsx b/apps/web/app/(app)/disclaimers/page.tsx index fdfc6618..a2f21eaa 100644 --- a/apps/web/app/(app)/disclaimers/page.tsx +++ b/apps/web/app/(app)/disclaimers/page.tsx @@ -4,7 +4,6 @@ import type { ReactNode } from "react"; import { AlertTriangle } from "lucide-react"; import LegalDisclaimer from "@/components/legal/LegalDisclaimer"; import { useLanguage } from "@/context/LanguageContext"; -import { CETES_REFERENCE_RATE_PCT, CETES_REFERENCE_DATE_LABEL_EN, CETES_REFERENCE_DATE_LABEL_ES } from "@/lib/cetesReference"; function H2({ children }: { children: ReactNode }) { return

{children}

; @@ -25,7 +24,7 @@ export default function DisclaimersPage() {

{t("Legal Disclaimers", "Avisos legales")}

-

{t("Last updated: November 25, 2026", "Última actualización: 25 de noviembre de 2026")}

+

{t("Last updated: December 1, 2026", "Última actualización: 1 de diciembre de 2026")}

@@ -33,53 +32,42 @@ export default function DisclaimersPage() {

{t("Network Status", "Estado de las redes")}

{t( -

Nirium runs across two Stellar networks. The non-custodial nodes - settlement (x402), audit anchoring and reporting - operate on Stellar Mainnet; these never hold or move client funds. Autonomous rebalancing runs on mainnet over DeFindex vaults structured so the client owns them (today’s live vault is Nirium’s own, self-funded), invite-only until we have a written legal opinion. NiriumVault, Nirium’s own contract, operates on Stellar Testnet, audit-gated, and will only reach mainnet after a formal external security audit. MPP Charge is experimental: verified on testnet, not tested on mainnet; for paid access on mainnet, use x402. The /ramp page is a demo on Etherfuse’s sandbox: the quote and the order are placed with Nirium’s test account at Etherfuse and no real money moves. To get real CETES, each person opens their own account at Etherfuse.

, -

Nirium corre en dos redes de Stellar. Los nodos no custodiales (liquidación x402, anclaje de auditoría y reportes) operan en Stellar Mainnet; nunca guardan ni mueven fondos de clientes. El rebalanceo autónomo corre en mainnet sobre bóvedas de DeFindex pensadas para que sean del cliente (la bóveda activa hoy es de Nirium, con fondos propios), solo por invitación hasta tener una opinión legal por escrito. NiriumVault, el contrato propio de Nirium, opera en Stellar Testnet y solo llegará a mainnet después de una auditoría de seguridad externa formal. MPP Charge es experimental: verificado en testnet, sin probar en mainnet; para acceso pagado en mainnet, usa x402. La página /ramp es una demo en el sandbox de Etherfuse: la cotización y la orden se hacen con la cuenta de pruebas de Nirium en Etherfuse y no se mueve dinero real. Para tener CETES reales, cada persona abre su propia cuenta en Etherfuse.

+

Nirium runs on Stellar (mainnet and testnet), with first versions on Solana, Avalanche, Base and Arbitrum. On Stellar, the non-custodial nodes - charging for Nirium’s own x402 endpoints (an independent facilitator settles each payment), audit anchoring and reporting - operate on Stellar Mainnet; these never hold or move client funds. MPP Charge is experimental: verified on testnet, not tested on mainnet; for paid access on mainnet, use x402. Treasury, Payouts and the /ramp CETES demo, tested only with the team’s own funds, were discontinued on 30 Nov 2026.

, +

Nirium corre en Stellar (mainnet y testnet), con primeras versiones en Solana, Avalanche, Base y Arbitrum. En Stellar, los nodos no custodiales (el cobro de los endpoints x402 propios de Nirium, cuya liquidación hace un facilitador independiente, el anclaje de auditoría y los reportes) operan en Stellar Mainnet; nunca guardan ni mueven fondos de clientes. MPP Charge es experimental: verificado en testnet, sin probar en mainnet; para acceso pagado en mainnet, usa x402. Tesorería, Payouts y la demo de CETES en /ramp, probados solo con fondos del propio equipo, se descontinuaron el 30-nov-2026.

)} {t( -

Update, 2026-10-04 (checked against the nirium 0.16.0 changelog that day): this section used to list MPP as part of the settlement running on mainnet and the treasury vault as testnet-only. Both were wrong: MPP Charge is experimental and not available on mainnet, and the treasury that runs on mainnet is DeFindex-based (testnet-only applies to NiriumVault). Testnet operations use test tokens with no real-world monetary value.

, -

Actualización, 2026-10-04 (revisado ese día contra el changelog de nirium 0.16.0): esta sección decía que MPP era parte de la liquidación en mainnet y que la bóveda de tesorería era solo de testnet. Las dos cosas estaban mal: MPP Charge es experimental y no está disponible en mainnet, y la tesorería que corre en mainnet usa DeFindex (lo de solo testnet aplica a NiriumVault). Las operaciones en testnet usan tokens de prueba sin valor monetario real.

+

Solana and Avalanche (first versions, since November 2026). Nirium sells its own network-data endpoint for $0.01 in USDC per query on Solana mainnet and Avalanche C-Chain mainnet; PayAI, an independent facilitator, settles each payment straight to Nirium’s address. The Nirium node anchors payer-signed receipts from those chains and reports totals per chain. The libraries (nirium-solana, nirium-avalanche) run in the user’s own code, and the user’s own wallet signs. Treasury and Payouts were never offered on those chains. So far the only mainnet payments there are Nirium’s own tests; see /chains. Base and Arbitrum (since 1 Dec 2026): the same $0.01 network-data market runs on Base mainnet and Arbitrum One, PayAI settles each payment, and the node anchors and reports receipts from both; their libraries are not published yet, the only payments there are Nirium’s own tests, and Treasury and Payouts were never offered there. Update, 2026-11-27: this section said Nirium runs on two Stellar networks.

, +

Solana y Avalanche (primeras versiones, desde noviembre de 2026). Nirium vende su propio endpoint de datos de la red por $0.01 en USDC por consulta en Solana mainnet y en Avalanche C-Chain mainnet; PayAI, un facilitador independiente, liquida cada pago directo a la dirección de Nirium. El nodo de Nirium ancla recibos firmados por quien paga en esas redes y reporta totales por red. Las librerías (nirium-solana, nirium-avalanche) corren en el código del propio usuario, y firma la wallet del propio usuario. Tesorería y Payouts nunca se ofrecieron en esas redes. Hasta ahora los únicos pagos en mainnet ahí son pruebas de Nirium; ver /chains. Base y Arbitrum (desde el 1-dic-2026): el mismo market de datos de la red por $0.01 corre en Base mainnet y Arbitrum One, PayAI liquida cada pago y el nodo ancla y reporta recibos de las dos; sus librerías todavía no se publican, los únicos pagos ahí son pruebas de Nirium, y Tesorería y Payouts nunca se ofrecieron ahí. Actualización, 27-nov-2026: esta sección decía que Nirium corre en dos redes de Stellar.

)} - -

{t("Rate Data and Displays", "Tasas y datos mostrados")}

{t( -

All rate figures displayed within Nirium - the Blend supply rate, the Etherfuse CETES reference rate, network fees - are public protocol reference data, attributed to their source. They are not return projections, guarantees, financial promises, or a recommendation to buy, sell or hold anything.

, -

Todas las tasas que muestra Nirium (la tasa de suministro de Blend, la tasa de referencia de CETES de Etherfuse, las comisiones de red) son datos públicos de referencia, atribuidos a su fuente. No son proyecciones de rendimiento, garantías, promesas financieras ni una recomendación para comprar, vender o mantener nada.

+

Update, 2026-12-01: two older notes on this page (4 Oct and 21 Nov 2026) described how Treasury’s vaults worked. They were removed after Treasury was discontinued. Testnet operations use test tokens with no real-world monetary value.

, +

Actualización, 1-dic-2026: dos notas anteriores de esta página (4-oct y 21-nov-2026) describían cómo funcionaban las bóvedas de Tesorería. Se quitaron al descontinuarse Tesorería. Las operaciones en testnet usan tokens de prueba sin valor monetario real.

)} -
    - {t( -
  • Blend Protocol Rate: Shown when the node can read it from Blend’s public smart contracts; a value of 0 means no data was available, not a 0% rate.
  • , -
  • Tasa de Blend: Se muestra cuando el nodo puede leerla de los contratos públicos de Blend; un valor de 0 significa que no hubo datos, no una tasa de 0%.
  • - )} - {t( -
  • Etherfuse CETES Rate: The {CETES_REFERENCE_RATE_PCT}% shown is a fixed reference value read from app.etherfuse.com/b/cetes on {CETES_REFERENCE_DATE_LABEL_EN}. It is not updated live and may differ from the current rate.
  • , -
  • Tasa de CETES de Etherfuse: El {CETES_REFERENCE_RATE_PCT}% que se muestra es un valor fijo de referencia leído de app.etherfuse.com/b/cetes en {CETES_REFERENCE_DATE_LABEL_ES}. No se actualiza en vivo y puede ser distinto de la tasa actual.
  • - )} -
-

{t("These figures are provided strictly for informational and UI demonstration purposes.", "Estas cifras se muestran solo con fines informativos y de demostración de la interfaz.")}

-

{t("Non-Custodial Architecture", "Arquitectura no custodial")}

+

{t("Reference Data", "Datos de referencia")}

{t( -

Nirium is purely a software infrastructure provider. We do not custody user funds. Client private keys never leave the client’s side, and signing happens with the client’s own wallet (for example, the Freighter extension). The only role Nirium can hold on a client’s DeFindex vault is the rebalance role: it can move funds between the vault’s own strategies or swap inside it (our code doesn’t send swaps), it cannot withdraw them, and the client can revoke it at any time. Outside that role, Nirium cannot access user funds or move them without a transaction the user signed. The one exception is NiriumVault’s emergency pause (testnet only): Nirium’s admin key can pause the contract, which freezes withdrawals until it is resumed, without moving any funds.

, -

Nirium es solo un proveedor de infraestructura de software. No custodiamos fondos de usuarios. Las llaves privadas del cliente nunca salen de su lado, y la firma se hace con la wallet del propio cliente (por ejemplo, la extensión Freighter). El único rol que Nirium puede tener en una bóveda de DeFindex de un cliente es el de rebalanceo: puede mover fondos entre las estrategias de la misma bóveda o hacer swaps dentro de ella (nuestro código no los manda), no puede retirarlos, y el cliente puede revocarlo cuando quiera. Fuera de ese rol, Nirium no puede acceder a fondos de usuarios ni moverlos sin una transacción firmada por el usuario. La única excepción es la pausa de emergencia de NiriumVault (solo testnet): la llave admin de Nirium puede pausar el contrato, lo que congela los retiros hasta reanudarlo, sin mover fondos.

+

Nirium’s paid test endpoint (/api/v1/premium/market) returns public network data, such as the base fee and Blend’s rate when the node can read it, plus a fixed CETES reference read on 12 Nov 2026. These are public reference data, attributed to their source. They are not return projections, guarantees, financial promises, or a recommendation to buy, sell or hold anything. A Blend value of 0 means no data was available, not a 0% rate.

, +

El endpoint de prueba de pago de Nirium (/api/v1/premium/market) devuelve datos públicos de la red, como la comisión base y la tasa de Blend cuando el nodo puede leerla, más una referencia fija de CETES leída el 12-nov-2026. Son datos públicos de referencia, atribuidos a su fuente. No son proyecciones de rendimiento, garantías, promesas financieras ni una recomendación para comprar, vender o mantener nada. Un valor de 0 en Blend significa que no hubo datos, no una tasa de 0%.

)} + +

{t("Non-Custodial Architecture", "Arquitectura no custodial")}

{t( -

Update, 2026-11-21 (checked against /security and the DeFindex rebalance instructions that day): this paragraph said Nirium could not “freeze” user funds and described the rebalance role as moving funds between strategies only. The admin key can pause NiriumVault on testnet, which freezes withdrawals, and the DeFindex role also allows swaps inside the vault. Both are now stated.

, -

Actualización, 2026-11-21 (revisado ese día contra /security y las instrucciones de rebalanceo de DeFindex): este párrafo decía que Nirium no podía “congelar” fondos de usuarios y describía el rol de rebalanceo solo como mover fondos entre estrategias. La llave admin puede pausar NiriumVault en testnet, lo que congela los retiros, y el rol de DeFindex también permite swaps dentro de la bóveda. Ahora se dicen las dos cosas.

+

Nirium is purely a software infrastructure provider. We do not custody user funds. Client private keys never leave the client’s side, and signing happens with the client’s own wallet (for example, the Freighter extension). Nirium cannot access user funds or move them without a transaction the user signed.

, +

Nirium es solo un proveedor de infraestructura de software. No custodiamos fondos de usuarios. Las llaves privadas del cliente nunca salen de su lado, y la firma se hace con la wallet del propio cliente (por ejemplo, la extensión Freighter). Nirium no puede acceder a fondos de usuarios ni moverlos sin una transacción firmada por el usuario.

)}

{t("Restricted Jurisdictions and Sanctions", "Jurisdicciones restringidas y sanciones")}

{t( -

Nirium Protocol operates from Mexico, run by its founders with no incorporated legal entity to date, and seeks not to offer services where they would constitute regulated activity without the corresponding authorization; that is why, until it has a written legal opinion, Payouts and Treasury on mainnet are invite-only. Access is prohibited from comprehensively sanctioned jurisdictions, jurisdictions subject to a Financial Action Task Force call for action, and mainland China. In the European Economic Area, the United Kingdom and the United States, pending a written legal opinion, Payouts and the Treasury node are not offered on mainnet; on testnet, where test tokens have no value, both stay available as a demonstration, and withdrawing from a vault you already own is never restricted there.

, -

Nirium Protocol opera desde México, a cargo de sus fundadores y sin una persona moral constituida a la fecha, y busca no ofrecer servicios donde constituirían una actividad regulada sin la autorización correspondiente; por eso, mientras no tenga una opinión legal por escrito, Payouts y Tesorería en mainnet son solo por invitación. Se prohíbe el acceso desde jurisdicciones con sanciones integrales, jurisdicciones sujetas a un llamado a la acción del Grupo de Acción Financiera Internacional (GAFI) y China continental. En el Espacio Económico Europeo, el Reino Unido y Estados Unidos, mientras no haya una opinión legal por escrito, Payouts y el nodo de Tesorería no se ofrecen en mainnet; en testnet, donde los tokens de prueba no tienen valor, los dos siguen disponibles como demostración, y retirar de una bóveda que ya es tuya nunca está restringido ahí.

+

Nirium Protocol operates from Mexico, run by its founders with no incorporated legal entity to date, and seeks not to offer services where they would constitute regulated activity without the corresponding authorization. Access is prohibited from comprehensively sanctioned jurisdictions, jurisdictions subject to a Financial Action Task Force call for action, and mainland China.

, +

Nirium Protocol opera desde México, a cargo de sus fundadores y sin una persona moral constituida a la fecha, y busca no ofrecer servicios donde constituirían una actividad regulada sin la autorización correspondiente. Se prohíbe el acceso desde jurisdicciones con sanciones integrales, jurisdicciones sujetas a un llamado a la acción del Grupo de Acción Financiera Internacional (GAFI) y China continental.

)} {t(

Update, 2026-11-21: this paragraph said Nirium “does not offer its services into jurisdictions where those services would constitute regulated activity, regardless of how the software is built”. Read that way it claimed Nirium already knows its services are not regulated in Mexico, which is the open question below. It now says what Nirium does about it.

,

Actualización, 2026-11-21: este párrafo decía que Nirium “no ofrece sus servicios en jurisdicciones donde constituirían una actividad regulada, sin importar cómo esté construido el software”. Así leído, afirmaba que Nirium ya sabe que en México no es actividad regulada, que es justo la pregunta abierta de abajo. Ahora dice qué hace Nirium al respecto.

)} {t( -

By using any Nirium service you represent, on every occasion of use, that you are not located in or resident of a prohibited jurisdiction and are not a sanctioned person or acting for one. Nirium may block access by technical means, including IP geolocation, and may refuse or terminate service without notice. Because Nirium never holds funds, termination never strands assets: your keys, accounts and vaults remain fully usable without us.

, -

Al usar cualquier servicio de Nirium declaras, cada vez que lo usas, que no estás ubicado ni resides en una jurisdicción prohibida y que no eres una persona sancionada ni actúas en nombre de una. Nirium puede bloquear el acceso por medios técnicos, incluida la geolocalización por IP, y puede negar o terminar el servicio sin aviso. Como Nirium nunca guarda fondos, terminar el servicio nunca deja activos atrapados: tus llaves, cuentas y bóvedas siguen funcionando sin nosotros.

+

By using any Nirium service you represent, on every occasion of use, that you are not located in or resident of a prohibited jurisdiction and are not a sanctioned person or acting for one. Nirium may block access by technical means, including IP geolocation, and may refuse or terminate service without notice. Because Nirium never holds funds, termination never strands assets: your keys and accounts remain fully usable without us.

, +

Al usar cualquier servicio de Nirium declaras, cada vez que lo usas, que no estás ubicado ni resides en una jurisdicción prohibida y que no eres una persona sancionada ni actúas en nombre de una. Nirium puede bloquear el acceso por medios técnicos, incluida la geolocalización por IP, y puede negar o terminar el servicio sin aviso. Como Nirium nunca guarda fondos, terminar el servicio nunca deja activos atrapados: tus llaves y cuentas siguen funcionando sin nosotros.

)}

{t("The full policy governs: ", "La política completa es la que rige: ")} @@ -91,14 +79,15 @@ export default function DisclaimersPage() {

{t("Open Source Licensing", "Licencias de código abierto")}

{t("The core components of the Nirium ecosystem are open-sourced to ensure transparency:", "Los componentes principales de Nirium son de código abierto, por transparencia:")}

    -
  • {t("Smart Contracts, SDK, MCP, and Agent API:", "Contratos inteligentes, SDK, MCP y API del agente:")} {t("Licensed under the Apache License 2.0.", "Licencia Apache 2.0.")}
  • -
  • {t("Dashboard Interface:", "Interfaz del dashboard:")} {t("Licensed under the Apache 2.0 License.", "Licencia Apache 2.0.")}
  • +
  • {t("Smart contracts, the TypeScript and Python packages, the CLI, the MCP server and the Solana and Avalanche libraries:", "Contratos inteligentes, los paquetes de TypeScript y Python, el CLI, el servidor MCP y las librerías de Solana y Avalanche:")} {t("Apache License 2.0 (nirium-protocol on GitHub).", "Licencia Apache 2.0 (nirium-protocol en GitHub).")}
  • +
  • {t("Web interface:", "Interfaz web:")} {t("Apache License 2.0, published in nirium-protocol/nirium-core.", "Licencia Apache 2.0, publicada en nirium-protocol/nirium-core.")}
  • +
  • {t("Hosted node API:", "API de los nodos alojados:")} {t("not open source. The receipts it anchors can be checked without it.", "no es de código abierto. Los recibos que ancla se pueden comprobar sin ella.")}

{t("Ecosystem Participation", "Participación en el ecosistema")}

{t( - "Nirium is an independent project in the Stellar developer ecosystem. It has received SCF Instaward grants for technical validation, completed under full KYC procedures. Amounts are not disclosed here. Nirium follows the Stellar Code of Conduct and builds transparently, with on-chain activity verifiable by anyone.", - "Nirium es un proyecto independiente del ecosistema de desarrolladores de Stellar. Ha recibido Instawards del SCF para validación técnica, con el proceso completo de KYC. Los montos no se publican aquí. Nirium sigue el Código de Conducta de Stellar y construye de forma transparente, con actividad on-chain que cualquiera puede verificar." + "Nirium is an independent project in the Stellar developer ecosystem. Nirium follows the Stellar Code of Conduct and builds transparently, with on-chain activity verifiable by anyone.", + "Nirium es un proyecto independiente del ecosistema de desarrolladores de Stellar. Nirium sigue el Código de Conducta de Stellar y construye de forma transparente, con actividad on-chain que cualquiera puede verificar." )}

{t("Stellar Code of Conduct", "Código de Conducta de Stellar")}

@@ -114,14 +103,14 @@ export default function DisclaimersPage() {

{t("Security Audits", "Auditorías de seguridad")}

{t( -

Nirium’s own smart contracts (NiriumVault and NiriumProtocol) have not yet been formally audited by an independent third party. A full external audit is required before NiriumVault operates on mainnet. Until then, NiriumVault runs on testnet only; the non-custodial settlement, audit and reporting nodes - which never touch client funds - run on mainnet. The mainnet Treasury node runs on third-party contracts that do have independent audits: DeFindex (OtterSec, March 2025) and Blend (a Code4rena audit and two Certora reports, marked as draft). Those audits are theirs, not Nirium’s, and do not cover each deployed vault’s configuration.

, -

Los contratos inteligentes propios de Nirium (NiriumVault y NiriumProtocol) todavía no tienen una auditoría formal de un tercero independiente. Se requiere una auditoría externa completa antes de que NiriumVault opere en mainnet. Mientras tanto, NiriumVault corre solo en testnet; los nodos no custodiales de liquidación, auditoría y reportes, que nunca tocan fondos de clientes, corren en mainnet. El nodo de Tesorería en mainnet corre sobre contratos de terceros que sí tienen auditorías independientes: DeFindex (OtterSec, marzo de 2025) y Blend (una auditoría de Code4rena y dos reportes de Certora, marcados como borrador). Esas auditorías son de ellos, no de Nirium, y no cubren la configuración de cada bóveda desplegada.

+

Nirium’s own smart contracts (NiriumVault and NiriumProtocol) have not yet been formally audited by an independent third party. NiriumVault ran on testnet only and was archived with Treasury on 30 Nov 2026; it will not reach mainnet. The non-custodial nodes - charging for Nirium’s own x402 endpoints, audit anchoring and reporting - never touch client funds and run on mainnet.

, +

Los contratos inteligentes propios de Nirium (NiriumVault y NiriumProtocol) todavía no tienen una auditoría formal de un tercero independiente. NiriumVault solo corrió en testnet y se archivó junto con Tesorería el 30-nov-2026; no llegará a mainnet. Los nodos no custodiales (el cobro de los endpoints x402 propios de Nirium, el anclaje de auditoría y los reportes) nunca tocan fondos de clientes y corren en mainnet.

)}

{t("Mexico Legal & Regulatory Position", "Posición legal y regulatoria en México")}

{t( -

Nirium provides software-only infrastructure. It is not authorized as a Financial Technology Institution (Institución de Tecnología Financiera - ITF), and it holds no client balance or electronic payment funds. It does not buy, sell or exchange virtual assets as its own business. The main open question is whether the autonomous Treasury rebalance and Payouts fall under fraction XVI of article 17 of the LFPIORPI, a vulnerable activity in force since 2019. Since 2019 that fraction has covered platforms that facilitate their clients’ purchases or sales of virtual assets or “provide means to [...] transfer” virtual assets; since July 2025 it also expressly includes operations with Mexican citizens from another jurisdiction. Article 24 Bis 4 of the SHCP’s General Rules under that law (added by Acuerdo 115/2026, applicable from November 30, 2026) defines that facilitation and says it applies even without control of the assets. If it applies, Nirium would be an Obligated Subject (Sujeto Obligado) for that activity. Nirium has not yet obtained a written legal opinion on it. Until it does, both stay invite-only on mainnet and Payouts collects client identification there. Audit anchoring, reporting and x402 settlement of Nirium’s own paid endpoints only record or report facts, or charge for Nirium’s own service. Nirium reads them as outside that question; no lawyer has confirmed it. A second, separate question is also open: whether a tokenized CETES counts as a security (valor) under Mexico’s Securities Market Law (see the Risk Disclosure). We do not provide financial advice, broker services, or custody of fiat or digital assets. Update, 2026-11-25: this paragraph said Nirium “does not operate as” an ITF and that anchoring, reporting and its own x402 endpoints “are not part of that question”. Those are legal conclusions no lawyer has reviewed.

, -

Nirium ofrece infraestructura que es solo software. No está autorizada como Institución de Tecnología Financiera (ITF), y no guarda saldos de clientes ni fondos de pago electrónico. No compra, vende ni intercambia activos virtuales como negocio propio. La principal pregunta abierta es si el rebalanceo autónomo de Tesorería y Payouts caen en la fracción XVI del artículo 17 de la LFPIORPI, actividad vulnerable vigente desde 2019. Desde 2019 esa fracción cubre a las plataformas que facilitan compras o ventas de activos virtuales de sus clientes o que “provean medios para [...] transferir” activos virtuales; desde julio de 2025 incluye también, de forma expresa, las operaciones con ciudadanos mexicanos desde otra jurisdicción. El artículo 24 Bis 4 de las Reglas de Carácter General de la SHCP para esa ley (agregado por el Acuerdo 115/2026, aplicable desde el 30 de noviembre de 2026) define esa facilitación y dice que aplica aun sin tener el control de los activos. Si aplicara, Nirium sería Sujeto Obligado por esa actividad. Nirium todavía no tiene una opinión legal por escrito sobre esto. Mientras no la tenga, los dos siguen solo por invitación en mainnet y Payouts recaba la identificación del cliente ahí. El anclaje de auditoría, los reportes y la liquidación x402 de los endpoints de pago propios de Nirium solo registran o reportan hechos, o cobran por el servicio propio de Nirium. Nirium los lee como fuera de esa pregunta; ningún abogado lo ha confirmado. Hay una segunda pregunta abierta, aparte: si un CETES tokenizado cuenta como valor bajo la Ley del Mercado de Valores (ver el Aviso de riesgos). No damos asesoría financiera, servicios de intermediación ni custodia de dinero fiat o activos digitales. Actualización, 25-nov-2026: este párrafo decía que Nirium no “opera como” una ITF y que el anclaje, los reportes y sus propios endpoints x402 “no son parte de esa pregunta”. Son conclusiones legales que ningún abogado ha revisado.

+

Nirium provides software-only infrastructure. It is not authorized as a Financial Technology Institution (Institución de Tecnología Financiera - ITF), and it holds no client balance or electronic payment funds. It does not buy, sell or exchange virtual assets as its own business. The open question was whether the autonomous Treasury rebalance and Payouts fell under fraction XVI of article 17 of the LFPIORPI, a vulnerable activity in force since 2019. Since 2019 that fraction has covered platforms that facilitate their clients’ purchases or sales of virtual assets or “provide means to [...] transfer” virtual assets; since July 2025 it also expressly includes operations with Mexican citizens from another jurisdiction. Article 24 Bis 4 of the SHCP’s General Rules under that law (added by Acuerdo 115/2026, applicable since November 30, 2026) defines that facilitation and says it applies even without control of the assets. Nirium never obtained a written legal opinion on it; it paused both on mainnet (27 and 28 Nov 2026) and archived them on 30 Nov 2026, so they are not offered on any network. Audit anchoring (Solana, Avalanche, Base and Arbitrum receipts included), reporting and the charging of Nirium’s own paid x402 endpoints, including the Solana, Avalanche, Base and Arbitrum markets that sell their own network data for USDC on mainnet, only record or report facts, or charge for Nirium’s own service; an independent facilitator settles each payment. Nirium reads them as outside that question; no lawyer has confirmed it. We do not provide financial advice, broker services, or custody of fiat or digital assets. Update, 2026-11-25: this paragraph said Nirium “does not operate as” an ITF and that anchoring, reporting and its own x402 endpoints “are not part of that question”. Those are legal conclusions no lawyer has reviewed. Update, 2026-11-27: this paragraph spoke of “x402 settlement”; Nirium does not settle payments, it charges for its own endpoints and a facilitator settles. It now also covers Solana and Avalanche. Update, 2026-11-30: Treasury and Payouts were archived; this paragraph described them as paused, and also raised whether tokenized CETES count as securities, which only Treasury touched.

, +

Nirium ofrece infraestructura que es solo software. No está autorizada como Institución de Tecnología Financiera (ITF), y no guarda saldos de clientes ni fondos de pago electrónico. No compra, vende ni intercambia activos virtuales como negocio propio. La pregunta abierta era si el rebalanceo autónomo de Tesorería y Payouts caían en la fracción XVI del artículo 17 de la LFPIORPI, actividad vulnerable vigente desde 2019. Desde 2019 esa fracción cubre a las plataformas que facilitan compras o ventas de activos virtuales de sus clientes o que “provean medios para [...] transferir” activos virtuales; desde julio de 2025 incluye también, de forma expresa, las operaciones con ciudadanos mexicanos desde otra jurisdicción. El artículo 24 Bis 4 de las Reglas de Carácter General de la SHCP para esa ley (agregado por el Acuerdo 115/2026, aplicable desde el 30 de noviembre de 2026) define esa facilitación y dice que aplica aun sin tener el control de los activos. Nirium nunca obtuvo una opinión legal por escrito sobre esto; pausó los dos en mainnet (27 y 28-nov-2026) y los archivó el 30-nov-2026, así que no se ofrecen en ninguna red. El anclaje de auditoría (también de recibos de Solana, Avalanche, Base y Arbitrum), los reportes y el cobro de los endpoints x402 propios de Nirium, incluidos los markets de Solana, Avalanche, Base y Arbitrum que venden sus propios datos por USDC en mainnet, solo registran o reportan hechos, o cobran por el servicio propio de Nirium; la liquidación de cada pago la hace un facilitador independiente. Nirium los lee como fuera de esa pregunta; ningún abogado lo ha confirmado. No damos asesoría financiera, servicios de intermediación ni custodia de dinero fiat o activos digitales. Actualización, 25-nov-2026: este párrafo decía que Nirium no “opera como” una ITF y que el anclaje, los reportes y sus propios endpoints x402 “no son parte de esa pregunta”. Son conclusiones legales que ningún abogado ha revisado. Actualización, 27-nov-2026: este párrafo hablaba de “la liquidación x402”; Nirium no liquida pagos, cobra por sus propios endpoints y un facilitador liquida. Ahora también cubre Solana y Avalanche. Actualización, 30-nov-2026: Tesorería y Payouts se archivaron; este párrafo los describía en pausa, y también planteaba si los CETES tokenizados cuentan como valores, algo que solo tocaba Tesorería.

)} {t(

This is how Nirium reads its own position, not legal advice to anyone. Each user should consult their own counsel on the law that applies to them.

, diff --git a/apps/web/app/(app)/docs/page.tsx b/apps/web/app/(app)/docs/page.tsx index 19403826..10fb122a 100644 --- a/apps/web/app/(app)/docs/page.tsx +++ b/apps/web/app/(app)/docs/page.tsx @@ -14,7 +14,7 @@ import { useLanguage } from "@/context/LanguageContext"; // /docs — Audit Trail: Verifiable Receipts // ═══════════════════════════════════════════════════════════════ // -// Rewritten 29-oct-2026 as a single-focus reference for SCF Build Award #46 +// Rewritten 29-oct-2026 as a single-focus reference for // reviewers: what a Nirium receipt is, how to get one, and how to check it // yourself without trusting Nirium. Every command, hash and CID below was // run live against nirium-agent.fly.dev (testnet) and @@ -300,8 +300,8 @@ function DocsContent() { )} POST /api/audit/log{" "} {lang( - "currently accepts requests with no key at all during the open beta - rate-limited to 20 requests/minute per IP on each box - so this step is optional right now and will matter once audit pricing goes live. Payouts does require one. The x402 and MPP routes don't: the payment itself is the access.", - "hoy acepta solicitudes sin ninguna key durante la beta abierta (con límite de 20 solicitudes por minuto por IP en cada servidor), así que este paso es opcional por ahora y va a importar cuando el cobro del audit entre en vigor. Payouts sí la requiere. Las rutas x402 y MPP no: el pago mismo es el acceso." + "currently accepts requests with no key at all during the open beta - rate-limited to 20 requests/minute per IP on each box - so this step is optional right now and will matter once audit pricing goes live. The x402 and MPP routes don't: the payment itself is the access.", + "hoy acepta solicitudes sin ninguna key durante la beta abierta (con límite de 20 solicitudes por minuto por IP en cada servidor), así que este paso es opcional por ahora y va a importar cuando el cobro del audit entre en vigor. Las rutas x402 y MPP no: el pago mismo es el acceso." )}

@@ -502,6 +502,30 @@ CID: QmehRz7Xab8Cg27fypBiffVgW11Yoac6BJcgd3g1pH5V7m signMessage{" "} {lang("both work.", "de una wallet funcionan.")}

+

+ {lang( + "You don't have to build it by hand: ", + "No tienes que armarla a mano: " + )} + nirium 0.21.0 {lang("signs with ", "firma con ")} + anchorAuditRecord({ record, signer }) + {lang(", the MCP tool ", ", la herramienta del MCP ")} + anchor_audit_record {lang("with ", "con ")} + sign: true (nirium-mcp 0.8.0) + {lang(", and the Pollar adapter with ", ", y el adaptador de Pollar con ")} + attester (0.7.0).{" "} + {lang( + "Put the context of the payment (order or quote id, amount, asset, who approved it) inside ", + "Pon el contexto del pago (id de orden o cotización, monto, activo, quién lo aprobó) dentro de " + )} + record + {lang(": ", ": ")} + txHash{lang(" and ", " y ")}tag + {lang( + " are node metadata, outside the hash and the signature.", + " son metadatos del nodo, fuera del hash y de la firma." + )} +

@@ -613,6 +637,13 @@ $ npx nirium-cli verify QmaofB6naeySxZsgA4R4p8YWzz3fujTitAa1ndJ1PQjbme --evidenc "Guarda tu propia copia. Un recibo sigue en IPFS solo mientras alguien lo mantenga fijado. Hoy Nirium fija cada recibo en Pinata; una segunda copia en Filebase ya está construida pero no está activa hasta que esa cuenta pase a un plan de pago (GET /api/audit/info muestra el estado en vivo). La respuesta del anclaje incluye el documento exacto que se fijó: nirium anchor --save receipt.json lo guarda, nirium cid receipt.json --expect muestra que es el original (nirium-cli 3.2.7 o más nuevo), y volver a subir esos bytes a IPFS da el mismo CID." )}

+

+ {lang( + "Receipts from Solana, Avalanche, Base and Arbitrum (payments bound to the exact USDC transfer, and policy decisions) use their own format and verifier: check them on nirium.xyz/solana, nirium.xyz/avalanche, nirium.xyz/base and nirium.xyz/arbitrum, or with npx -p nirium-solana nirium-verify-svm and npx -p nirium-avalanche nirium-verify-evm. /verify recognizes them and sends you there.", + "Los recibos de Solana, Avalanche, Base y Arbitrum (pagos ligados a la transferencia exacta de USDC, y decisiones de la política) usan su propio formato y verificador: compruébalos en nirium.xyz/solana, nirium.xyz/avalanche, nirium.xyz/base y nirium.xyz/arbitrum, o con npx -p nirium-solana nirium-verify-svm y npx -p nirium-avalanche nirium-verify-evm. /verify los reconoce y te manda ahí." + )}{" "} + {lang("What works on each chain", "Qué funciona en cada red")} +

{lang("Anchor from the terminal (nirium-cli 3.1.0+).", "Anclar desde la terminal (nirium-cli 3.1.0 o más nuevo).")}

@@ -668,8 +699,8 @@ $ npx nirium-cli verify QmS1dJaMat4yWfMJ2HwYGkNMUxQD2fF7unUgFTnuLmRPfh \\

{lang( - "The Reporting node is a read-only summary of what the Nirium agent already records: Audit Trail anchors, payment receipts from Nirium's own x402 endpoint, and Payouts runs. It holds no funds and no keys, and it needs no API key. Requests are rate-limited.", - "El nodo de Reporting es un resumen de solo lectura de lo que el agente de Nirium ya registra: anclajes de Audit Trail, recibos de pago del endpoint x402 propio de Nirium y corridas de Payouts. No guarda fondos ni llaves, y no necesita API key. Las peticiones tienen límite de frecuencia." + "The Reporting node is a read-only summary of what the Nirium agent already records: Audit Trail anchors, and payment receipts from Nirium's own x402 endpoint. It holds no funds and no keys, and it needs no API key. Requests are rate-limited.", + "El nodo de Reporting es un resumen de solo lectura de lo que el agente de Nirium ya registra: anclajes de Audit Trail, y recibos de pago del endpoint x402 propio de Nirium. No guarda fondos ni llaves, y no necesita API key. Las peticiones tienen límite de frecuencia." )}

@@ -692,8 +723,8 @@ $ npx nirium-cli verify QmS1dJaMat4yWfMJ2HwYGkNMUxQD2fF7unUgFTnuLmRPfh \\

{lang("Endpoints", "Endpoints")}

    -
  • GET /api/reporting/summary - {lang("totals for a period: Payouts runs, payment receipts, anchors and when the last anchor happened.", "totales de un periodo: corridas de Payouts, recibos de pago, anclajes y cuándo fue el último anclaje.")}
  • -
  • GET /api/reporting/export?type=anchors|payments|payroll&format=csv|json - {lang("the rows behind those totals, as CSV or JSON. No CIDs and no Payouts run ids: those belong to whoever anchored or paid.", "las filas detrás de esos totales, en CSV o JSON. Sin CIDs ni ids de corrida de Payouts: son de quien ancló o pagó.")}
  • +
  • GET /api/reporting/summary - {lang("totals for a period: payment receipts, anchors and when the last anchor happened.", "totales de un periodo: recibos de pago, anclajes y cuándo fue el último anclaje.")}
  • +
  • GET /api/reporting/export?type=anchors|payments&format=csv|json - {lang("the rows behind those totals, as CSV or JSON. No CIDs: those belong to whoever anchored or paid.", "las filas detrás de esos totales, en CSV o JSON. Sin CIDs: son de quien ancló o pagó.")}
  • GET /api/reporting/info - {lang("node metadata and the list of endpoints.", "metadatos del nodo y la lista de endpoints.")}

@@ -868,8 +899,8 @@ app.use('/premium', x402Serve({ {lang("To test an x402 client against a real seller, point it at ", "Para probar un cliente x402 contra un vendedor real, apúntalo a ")} GET /api/v1/premium/market {lang( - ". It answers 402 for 0.05 USDC and, once paid, returns Stellar network state: the base fee, the Blend rate when the node can read it, and the fixed CETES reference (read 12 Nov 2026). It is a test target, not a data product: much of what it returns is fixed or public. On testnet it costs test USDC; on mainnet it charges real USDC. Who has paid it so far is in Evidence (§9). The other two premium routes answer 501 on mainnet without charging, because that box runs no signal loop and holds no signing key.", - ". Responde 402 por 0.05 USDC y, una vez pagado, devuelve el estado de la red Stellar: la comisión base, la tasa de Blend cuando el nodo puede leerla y la referencia fija de CETES (leída el 12 de noviembre de 2026). Es un endpoint de prueba, no un producto de datos: buena parte de lo que devuelve es fijo o público. En testnet cuesta USDC de prueba; en mainnet cobra USDC real. Quién lo ha pagado hasta hoy está en Evidencia (§9). Las otras dos rutas premium responden 501 en mainnet sin cobrar, porque ese servidor no corre el loop de señales ni tiene llave para firmar." + ". It answers 402 for 0.05 USDC and, once paid, returns Stellar network state: the base fee, the Blend rate when the node can read it, and the fixed CETES reference (read 12 Nov 2026). It is a test target, not a data product: much of what it returns is fixed or public. On testnet it costs test USDC; on mainnet it charges real USDC. Who has paid it so far is in Evidence (§9). On mainnet, signals answers 501 without charging, because that box runs no signal loop; execute is no longer available (410).", + ". Responde 402 por 0.05 USDC y, una vez pagado, devuelve el estado de la red Stellar: la comisión base, la tasa de Blend cuando el nodo puede leerla y la referencia fija de CETES (leída el 12 de noviembre de 2026). Es un endpoint de prueba, no un producto de datos: buena parte de lo que devuelve es fijo o público. En testnet cuesta USDC de prueba; en mainnet cobra USDC real. Quién lo ha pagado hasta hoy está en Evidencia (§9). En mainnet, signals responde 501 sin cobrar, porque ese servidor no corre el loop de señales; execute ya no está disponible (410)." )}

{` @@ -1048,13 +1079,15 @@ payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIi... { proves: lang("Same integration, fifth receipt - TIA's second key, tag niriumtober", "Misma integración, quinto recibo - la segunda llave de TIA, etiqueta niriumtober"), ref: "QmPS1snVHEzXaQe9YmXyDFrm5XfCXLWLAD6v59chSJqZby", date: "2026-11-06", link: "https://gateway.pinata.cloud/ipfs/QmPS1snVHEzXaQe9YmXyDFrm5XfCXLWLAD6v59chSJqZby" }, { proves: lang("Same integration, sixth receipt - same call, 2 s later, tag tia-route", "Misma integración, sexto recibo - misma llamada, 2 s después, etiqueta tia-route"), ref: "QmXT33ZyUvwxzamEMeGYyUxpAWt86bsPpRkFFu4D1fPkso", date: "2026-11-06", link: "https://gateway.pinata.cloud/ipfs/QmXT33ZyUvwxzamEMeGYyUxpAWt86bsPpRkFFu4D1fPkso" }, { proves: lang("Same integration, seventh anchored receipt", "Misma integración, séptimo recibo anclado"), ref: "QmZ9bQxXLqoCvAQ6AtRChd18MS9YkjBF6MbT9k5e84PTTv", date: "2026-11-12", link: "https://gateway.pinata.cloud/ipfs/QmZ9bQxXLqoCvAQ6AtRChd18MS9YkjBF6MbT9k5e84PTTv" }, + { proves: lang("Same integration, eighth receipt - 2 Nov, 22:02 UTC, tag tia-route. Found in our 25 Nov 2026 recount; earlier versions of this list showed seven", "Misma integración, octavo recibo - 2 nov, 22:02 UTC, etiqueta tia-route. Lo encontramos al recontar el 25 nov 2026; antes esta lista mostraba siete"), ref: "QmXnUQxWdzCBKN2rEi4JPYirVyhu3Rebt2mtyoXuJRAL18", date: "2026-11-02", link: "https://gateway.pinata.cloud/ipfs/QmXnUQxWdzCBKN2rEi4JPYirVyhu3Rebt2mtyoXuJRAL18" }, { proves: lang("x402 payment, our own test of nirium 0.20.0 - the most recent of the 40", "Pago x402, prueba propia de nirium 0.20.0; el más reciente de los 40"), ref: "786db50b8cba033f56f987adb113e53d2dee7d8a08066ed9e5664fc41f3ec336", date: "2026-11-24", link: "https://stellar.expert/explorer/public/tx/786db50b8cba033f56f987adb113e53d2dee7d8a08066ed9e5664fc41f3ec336" }, { proves: lang("AgentRail's receipt, signed with its own agent key, for a 0.001 XLM payment to its own treasury - a test by its founder", "Recibo de AgentRail, firmado con la llave de su agente, de un pago de 0.001 XLM a su propia tesorería; una prueba de su fundador"), ref: "QmdJowsxyyDjv8UxwgceawgpZN4zsDUDaKeSiqDpQX3p8a", date: "2026-11-24", link: "https://gateway.pinata.cloud/ipfs/QmdJowsxyyDjv8UxwgceawgpZN4zsDUDaKeSiqDpQX3p8a" }, + { proves: lang("AgentRail's correction of that receipt: the record listed a wrong contractId; same transaction, same agent key, hash-only", "Corrección de AgentRail a ese recibo: el registro traía un contractId equivocado; misma transacción, misma llave del agente, solo hash"), ref: "QmSKQP8gHc7yQNs1dqhS8dTWYBj5MpF7V5NMkFKxeZ3mEe", date: "2026-11-30", link: "https://gateway.pinata.cloud/ipfs/QmSKQP8gHc7yQNs1dqhS8dTWYBj5MpF7V5NMkFKxeZ3mEe" }, { proves: lang("Our own notice: the hash of our Restricted Jurisdictions policy v1.5, signed with a Nirium test key (own use)", "Aviso propio: el hash de nuestra política de Jurisdicciones Restringidas v1.5, firmado con una llave de pruebas de Nirium (uso propio)"), ref: "Qmd7yun1FUDZ3p2DK36BxRpLaAA2EQjjWfZ1S77R4Z1v4F", date: "2026-11-25", link: "https://gateway.pinata.cloud/ipfs/Qmd7yun1FUDZ3p2DK36BxRpLaAA2EQjjWfZ1S77R4Z1v4F" }, { proves: lang("Trustless Work escrow, full lifecycle, own-funds test (0.50 USDC)", "Escrow de Trustless Work, ciclo completo, prueba con fondos propios (0.50 USDC)"), ref: "0c533088ab6326a78b9f79c197b7636ca4662a0d72562968ddea37f370a8192b", date: "2026-09-03", link: "https://stellar.expert/explorer/public/tx/0c533088ab6326a78b9f79c197b7636ca4662a0d72562968ddea37f370a8192b" }, ]} />

- {lang("The seven TIA receipts are signed with two TIA keys: five by ", "Los siete recibos de TIA están firmados con dos llaves de TIA: cinco con ")} + {lang("The eight TIA receipts are signed with two TIA keys: six by ", "Los ocho recibos de TIA están firmados con dos llaves de TIA: seis con ")} GATT3MOLOCTDOUGS3FDNZUYV3UKDLIQE4PN7JJ4JYZBYJOOXBVJV4KXI{" "} {lang("(quotes and routes) and two by ", "(cotizaciones y rutas) y dos con ")} GBMCX53NIDNHE6WL3FJGROYWTSGOQMWD6R7Y2ORBWR2G2SCLEKM376DY{" "} @@ -1159,12 +1192,6 @@ payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIi... {lang("A free key from ", "Una key gratis de ")}/keys{" "} {lang("is self-service and wallet-signed, scoped to the free tier by default.", "es de autoservicio y se firma con wallet, limitada al nivel gratis por default.")} -

  • - {lang( - "Free keys cannot trigger mainnet Payouts, or deploy, deposit into or rebalance a Treasury vault on mainnet - those stay invite-only (institutional/enterprise tier, assigned manually). Withdrawing from your own vault stays open to any key.", - "Las keys gratis no pueden disparar Payouts en mainnet, ni desplegar, depositar o rebalancear una bóveda de Treasury en mainnet: eso se queda por invitación (nivel institucional/enterprise, asignado a mano). Retirar de tu propia bóveda sigue abierto para cualquier key." - )} -
  • {lang("Known limits, stated plainly:", "Límites conocidos, dichos de frente:")}

      @@ -1183,17 +1210,14 @@ payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIi... )}
    -

    - {lang("Treasury and Payouts are separate, invite-only modules, not covered here.", "Treasury y Payouts son módulos aparte, por invitación, que no se cubren aquí.")} -

    {lang("Planned, not live:", "Planeado, no en vivo:")}{" "} {lang( - "batching anchored receipts into a Soroban registry contract, so a receipt's existence can be checked on-chain directly instead of only via an IPFS CID. No date set yet.", - "agrupar recibos anclados en un contrato de registro en Soroban, para que la existencia de un recibo se pueda comprobar directo en cadena, no solo vía un CID de IPFS. Todavía sin fecha." + "a receipt bound to the payment: the verifier checks the receipt against the transfer on Stellar (a classic payment or a contract transfer event), and a classic payment can carry the receipt's hash as its memo, which gives the record the ledger's time instead of our server's clock. An on-chain registry contract is not planned until a user needs it.", + "un recibo ligado al pago: el verificador compara el recibo con la transferencia en Stellar (un pago clásico o el evento de transferencia de un contrato), y un pago clásico puede llevar el hash del recibo como memo, lo que le da al registro la hora del ledger y no la de nuestro servidor. Un contrato de registro en la cadena no está planeado hasta que un usuario lo necesite." )}

    @@ -1203,8 +1227,8 @@ payment-required: eyJ4NDAyVmVyc2lvbiI6MiwiZXJyb3IiOiJQYXltZW50IHJlcXVpcmVkIi... )} ReceiptRegistry{" "} {lang( - "prototype was measured on testnet on 29 Oct 2026 - a cost check, not a launch: contract", - "se midió en testnet el 29 de octubre de 2026, una revisión de costo, no un lanzamiento: contrato" + "prototype was measured on testnet on 29 Oct 2026 - a cost check, not a launch, and not on the plan above: contract", + "se midió en testnet el 29 de octubre de 2026, una revisión de costo, no un lanzamiento, y no está en el plan de arriba: contrato" )}{" "} CBK7GBTO32ZFARQP4D2LVPLR3AOFZZJZXQSMZJWRUPPU7OYIDFPIWQBG,{" "} {lang( diff --git a/apps/web/app/(app)/how-to-use/layout.tsx b/apps/web/app/(app)/how-to-use/layout.tsx index be80a833..ed638dfe 100644 --- a/apps/web/app/(app)/how-to-use/layout.tsx +++ b/apps/web/app/(app)/how-to-use/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/how-to-use", title: "How to Use Nirium", - description: "Getting started with Nirium: an API key, x402 payments, the invite-only Treasury rebalancer and Audit Trail receipts anyone can verify.", + description: "Getting started with Nirium: an API key, x402 payments and Audit Trail receipts anyone can verify.", }); export default function HowToUseLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/keys/layout.tsx b/apps/web/app/(app)/keys/layout.tsx index a53e1037..451c5412 100644 --- a/apps/web/app/(app)/keys/layout.tsx +++ b/apps/web/app/(app)/keys/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/keys", title: "API Keys", - description: "Issue a free Nirium API key tied to your Stellar wallet, proven by signature. One key works on testnet and mainnet; mainnet Payouts and Treasury are invite-only.", + description: "Issue a free Nirium API key tied to your wallet, proven by signature. One key works on testnet and mainnet for audit anchoring and Reporting.", }); export default function KeysLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/keys/page.tsx b/apps/web/app/(app)/keys/page.tsx index 91ef35da..04285375 100644 --- a/apps/web/app/(app)/keys/page.tsx +++ b/apps/web/app/(app)/keys/page.tsx @@ -277,8 +277,8 @@ export default function KeysPage() {

    API Keys

    {lang( - "Issue real API keys for the Nirium agent - audit anchoring, reporting and authenticated endpoints. One key works on testnet and mainnet for audit anchoring and reporting. On mainnet, Payouts and Treasury need a key Nirium authorizes (invite-only). Today anchoring and Reporting need no key (open beta); the key counts once Audit Trail pricing starts, and for Payouts and Treasury.", - "Emite API keys reales del agente Nirium - anclaje de auditoría, reportería y endpoints autenticados. Una misma key funciona en testnet y mainnet para anclaje y reportería. En mainnet, Payouts y Treasury necesitan una key que Nirium autorice (por invitación). Hoy anclar y consultar Reporting no necesitan key (beta abierta); la key cuenta cuando entre el cobro de Audit Trail y para Payouts y Treasury.")} + "Issue real API keys for the Nirium agent - audit anchoring, reporting and authenticated endpoints. One key works on testnet and mainnet for audit anchoring and reporting. Today anchoring and Reporting need no key (open beta); the key counts once Audit Trail pricing starts.", + "Emite API keys reales del agente Nirium - anclaje de auditoría, reportería y endpoints autenticados. Una misma key funciona en testnet y mainnet para anclaje y reportería. Hoy anclar y consultar Reporting no necesitan key (beta abierta); la key cuenta cuando entre el cobro de Audit Trail.")}

    {[ diff --git a/apps/web/app/(app)/manifesto/layout.tsx b/apps/web/app/(app)/manifesto/layout.tsx index 00d24344..00dabb9e 100644 --- a/apps/web/app/(app)/manifesto/layout.tsx +++ b/apps/web/app/(app)/manifesto/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/manifesto", title: "Manifesto", - description: "Why autonomous agents need payment, audit and execution rails, and why Nirium builds them on Stellar.", + description: "Why money that moves because of a document needs a signed record of that document anyone can check.", noindex: true, }); diff --git a/apps/web/app/(app)/payouts/layout.tsx b/apps/web/app/(app)/payouts/layout.tsx index d9a31e55..4ffb7238 100644 --- a/apps/web/app/(app)/payouts/layout.tsx +++ b/apps/web/app/(app)/payouts/layout.tsx @@ -2,8 +2,8 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/payouts", - title: "Payouts", - description: "Pay up to 100 recipients per batch (99 if the batch carries a fee) from one company wallet in a single signed Stellar transaction. Nirium builds it, you sign it. Invite-only on mainnet.", + title: "Payouts (discontinued)", + description: "Payouts was tested only with the team's own funds and discontinued on 30 Nov 2026.", }); export default function PayoutsLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/payouts/page.tsx b/apps/web/app/(app)/payouts/page.tsx index 051f83da..24c497e2 100644 --- a/apps/web/app/(app)/payouts/page.tsx +++ b/apps/web/app/(app)/payouts/page.tsx @@ -1,476 +1,6 @@ -"use client"; +import { redirect } from "next/navigation"; -// ─────────────────────────────────────────────────────────────── -// Payroll / Disbursement Node - operator console -// -// Fan-out one treasury to many employees in a single signed batch payment. -// Non-custodial: the agent builds the unsigned XDR from the CONNECTED wallet -// (the treasury/source), the company signs it in Freighter, and every settled -// run gets an IPFS receipt bound to LCP legal terms. Dual-network: testnet -// (Box A) por default; MAINNET early access (Box B) mueve fondos reales y -// exige aceptación explícita de los términos de payouts (gate 403 del agente). -// i18n via the shared dictionaries (en/es). -// ─────────────────────────────────────────────────────────────── - -import { useCallback, useEffect, useState } from "react"; -import { useFreighter } from "@/hooks/useFreighter"; -import { useLanguage } from "@/context/LanguageContext"; -import { useNetwork } from "@/context/NetworkContext"; - -const PASSPHRASES = { - testnet: "Test SDF Network ; September 2015", - mainnet: "Public Global Stellar Network ; September 2015", -} as const; -type Net = keyof typeof PASSPHRASES; - -type Recipient = { wallet: string; amount: string }; -type ClientInfo = { legalName: string; taxId: string; repName: string }; -type RecipientResult = { wallet: string; amount: string; status: "ok" | "skipped"; reason?: string }; -type Receipt = { txHash?: string; explorer?: string; cid?: string; totalAmount?: string; recipientCount?: number }; -type Run = { - asset: string; totalAmount: string; recipientCount: number; - txHash?: string; explorer?: string; -}; -type LegalDoc = { - terms: string; atrHash?: string; - disputeResolution?: { source?: string; clauseId?: string }; -}; - -const shorten = (s: string, n = 6) => (s.length > n * 2 ? `${s.slice(0, n)}…${s.slice(-n)}` : s); -// El recibo se abre en /verify, que recalcula el hash (antes: JSON crudo en Pinata). -const verifyUrl = (cid: string) => `/verify?cid=${encodeURIComponent(cid)}`; - -async function signXdr( - signTransaction: (xdr: string, opts?: any) => Promise, - xdr: string, - address: string, - passphrase: string, -): Promise { - // Pin the signer to the CONNECTED address: without this the wallet may sign - // with whatever account is currently active, which won't match the tx source - // (the treasury) → tx_bad_auth. - const res = await signTransaction(xdr, { networkPassphrase: passphrase, address }); - const signed = typeof res === "string" ? res : (res as any).signedTxXdr; - if (!signed) throw new Error("wallet returned no signed transaction"); - return signed; -} - -export default function PayrollPage() { - const { address, isConnected, connect, signTransaction, getAddress } = useFreighter(); - const { t, language } = useLanguage(); - const lang = (en: string, es: string) => (language === 'es' ? es : en); - const p = t.payroll; - - const [asset, setAsset] = useState<"USDC" | "XLM">("USDC"); - // Red global (sidebar) - no un estado local: dos toggles independientes - // (este y el del sidebar) es justo el bug que causaba que "Corridas - // recientes" siguiera mostrando testnet tras cambiar a mainnet desde el - // sidebar. Un solo lugar para cambiar de red, como treasury/vault/page.tsx. - const { network, setNetwork } = useNetwork(); - // Blindaje legal: la corrida exige aceptación explícita de los términos - // (el agente responde 403 sin acknowledgeTerms - en AMBAS redes). - const [ackTerms, setAckTerms] = useState(false); - // Identificación de cliente - solo mainnet, de cara a LFPIORPI fracc. XVI - // (vigente desde 2019, no 2027 - ver NiriumMainnet.md §3.7). El agente responde 403 sin ella en mainnet. - const [clientInfo, setClientInfo] = useState({ legalName: "", taxId: "", repName: "" }); - const [memo, setMemo] = useState(""); - const [recipients, setRecipients] = useState([{ wallet: "", amount: "" }]); - const [phase, setPhase] = useState<"idle" | "building" | "signing" | "submitting">("idle"); - const [error, setError] = useState(null); - const [skipped, setSkipped] = useState([]); - const [receipt, setReceipt] = useState(null); - - const [onboardPhase, setOnboardPhase] = useState<"idle" | "working">("idle"); - const [onboardMsg, setOnboardMsg] = useState(null); - - const [runs, setRuns] = useState([]); - const [legal, setLegal] = useState(null); - - // LCP discovery - read our own published .well-known file (same origin). - useEffect(() => { - fetch("/.well-known/legal-context.json", { cache: "no-store" }) - .then((r) => (r.ok ? r.json() : null)) - .then((d) => setLegal(d)) - .catch(() => { /* not published yet - banner hidden */ }); - }, []); - - const loadRuns = useCallback(async () => { - try { - const r = await fetch(`/api/payroll/runs?network=${network}`, { cache: "no-store" }); - const d = await r.json(); - setRuns(Array.isArray(d.runs) ? d.runs : []); - } catch { /* agent offline - leave list as-is */ } - }, [network]); - - useEffect(() => { loadRuns(); }, [loadRuns]); - - const busy = phase !== "idle"; - const clientInfoComplete = Boolean(clientInfo.legalName.trim() && clientInfo.taxId.trim() && clientInfo.repName.trim()); - const total = recipients.reduce((s, r) => s + (Number(r.amount) || 0), 0); - const filledCount = recipients.filter((r) => r.wallet && r.amount).length; - - const setRow = (i: number, key: keyof Recipient, val: string) => - setRecipients((rs) => rs.map((r, j) => (j === i ? { ...r, [key]: val } : r))); - const addRow = () => setRecipients((rs) => [...rs, { wallet: "", amount: "" }]); - const removeRow = (i: number) => setRecipients((rs) => rs.length > 1 ? rs.filter((_, j) => j !== i) : rs); - - const actionLabel = - phase === "building" ? p.actions.building - : phase === "signing" ? p.actions.signing - : phase === "submitting" ? p.actions.settling - : p.actions.buildSign; - - async function runPayroll() { - setError(null); setSkipped([]); setReceipt(null); - if (!isConnected || !address) { await connect(); return; } - const clean = recipients - .map((r) => ({ wallet: r.wallet.trim(), amount: r.amount.trim() })) - .filter((r) => r.wallet && r.amount); - if (clean.length === 0) { setError(p.errors.needRecipient); return; } - if (!ackTerms) { setError(p.errors.needTerms); return; } - if (network === "mainnet" && !clientInfoComplete) { setError(p.errors.needClientInfo); return; } - - try { - setPhase("building"); - // The treasury (tx source) is the connected account. If the wallet has - // since switched to a different active account, signing would use that - // account → tx_bad_auth. Guard explicitly instead of failing cryptically. - const active = await getAddress(); - if (active && active !== address) { setPhase("idle"); setError(p.errors.accountMismatch); return; } - const built = await fetch("/api/payroll/run", { - method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - walletAddress: address, recipients: clean, asset, memo: memo || undefined, network, acknowledgeTerms: ackTerms, - clientInfo: network === "mainnet" ? clientInfo : undefined, - }), - }).then((r) => r.json()); - if (built.error) throw new Error(built.error); - - const dropped: RecipientResult[] = (built.recipients || []).filter((r: RecipientResult) => r.status === "skipped"); - setSkipped(dropped); - if (!built.xdr) { setPhase("idle"); setError(p.errors.noPayable); return; } - - setPhase("signing"); - const signedXdr = await signXdr(signTransaction, built.xdr, address, PASSPHRASES[network]); - - setPhase("submitting"); - const settled = await fetch("/api/payroll/submit", { - method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ walletAddress: address, runId: built.runId, signedXdr, network }), - }).then((r) => r.json()); - if (settled.error) throw new Error(settled.error); - - setReceipt({ - txHash: settled.txHash, explorer: settled.explorer, cid: settled.cid, - totalAmount: settled.totalAmount, recipientCount: settled.recipientCount, - }); - loadRuns(); - } catch (e) { - setError(e instanceof Error ? e.message : String(e)); - } finally { - setPhase("idle"); - } - } - - async function onboardWorker() { - setOnboardMsg(null); - if (!isConnected || !address) { await connect(); return; } - try { - setOnboardPhase("working"); - // Self-service: add the USDC trustline to the CONNECTED account (it signs - // its own changeTrust - one signature). Guard against a wallet account - // switch so we don't sign with the wrong account (tx_bad_auth). - const active = await getAddress(); - if (active && active !== address) { setOnboardMsg(p.errors.accountMismatch); return; } - const built = await fetch("/api/payroll/onboard", { - method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ walletAddress: address, employee: address, network }), - }).then((r) => r.json()); - if (built.error) throw new Error(built.error); - if (built.status === "skipped") { setOnboardMsg(`${built.reason}`); return; } - if (!built.xdr) throw new Error("agent did not return a transaction to sign"); - - const signedXdr = await signXdr(signTransaction, built.xdr, address, PASSPHRASES[network]); - const settled = await fetch("/api/payroll/onboard/submit", { - method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ walletAddress: address, signedXdr, network }), - }).then((r) => r.json()); - if (settled.error) throw new Error(settled.error); - setOnboardMsg(`✅ TX ${shorten(settled.txHash || "", 5)}`); - } catch (e) { - setOnboardMsg(e instanceof Error ? e.message : String(e)); - } finally { - setOnboardPhase("idle"); - } - } - - return ( -
    -
    - {/* Header */} -

    - {p.eyebrow} -

    -

    {p.title}

    -

    {p.subtitle}

    -
    - {[p.badges.nonCustodial, p.badges.batch, p.badges.ipfs, p.badges.lcp, network === "mainnet" ? p.badges.mainnet : p.badges.testnet].map((b) => ( - {b} - ))} -
    - - {/* Precio - LICENCIA MENSUAL POR CAPACIDAD, $0 durante la Beta. - Era "por destinatario" y contradecía los propios términos que - el cliente acepta dos recuadros más abajo (§9: nunca un cargo - por pago). Cobrar por pago procesado es como cobra un - procesador de pagos, y la tesis entera es que no lo somos. */} -
    -

    {p.pricing.label}

    -
    - $99{p.pricing.tier1} - $249{p.pricing.tier2} -
    -

    {p.pricing.note}

    -
    - - {/* LCP legal context - published discovery file */} - {legal && ( -
    - {p.legal.label} - {p.legal.terms} - {legal.atrHash && ( - atrHash {legal.atrHash.replace("sha-256:", "").slice(0, 10)}… - )} - {legal.disputeResolution?.source && {p.legal.dispute} · {language === 'es' && legal.disputeResolution.source === 'Courts of Mexico City (arbitration only by written agreement)' ? 'Tribunales de la Ciudad de México (arbitraje solo por acuerdo escrito)' : legal.disputeResolution.source}} -
    - )} - - {/* Wallet */} -
    -
    -

    {p.wallet.signer}

    - - {isConnected && address ? shorten(address, 7) : p.wallet.notConnected} - -
    - {!isConnected && ( - - )} -
    - - {/* Batch payout */} -
    -
    -

    {p.batch.title}

    -
    -
    - {(["testnet", "mainnet"] as const).map((n) => ( - - ))} -
    - {network === "testnet" && ( -
    - {(["USDC", "XLM"] as const).map((a) => ( - - ))} -
    - )} -
    -
    - - {/* Mainnet: sin formulario. El sitio pide al agente un token de nivel - 'free' para cualquier wallet (/api/auth/token) y la corrida en - mainnet exige nivel institucional (requirePayrollMainnetAccess), - así que desde aquí siempre terminaba en 403, incluso para un - invitado. Las empresas invitadas lo corren por API con su llave - autorizada. Decidido el 8-nov-2026. */} - {network === "mainnet" && ( -
    -

    {p.badges.mainnet}

    -

    {p.network.privateAccessNote}

    - -
    - )} - - {network === "testnet" && (<> -
    - {recipients.map((r, i) => ( -
    -
    - setRow(i, "wallet", e.target.value)} - placeholder={p.batch.walletPlaceholder} - className="flex-1 min-w-0 h-11 px-3 rounded-lg bg-black border border-white/10 font-mono text-sm text-white/90 placeholder:text-white/25 focus:border-stellar-teal/60 outline-none" /> -
    -
    - setRow(i, "amount", e.target.value)} - inputMode="decimal" placeholder="0.00" - className="flex-1 sm:w-28 sm:flex-none h-11 px-3 rounded-lg bg-black border border-white/10 font-mono text-sm text-right text-white/90 placeholder:text-white/25 focus:border-stellar-teal/60 outline-none" /> - -
    -
    - ))} -
    - - - - setMemo(e.target.value)} maxLength={28} - placeholder={p.batch.memoPlaceholder} - className="w-full h-11 px-3 mb-5 rounded-lg bg-black border border-white/10 font-mono text-sm text-white/90 placeholder:text-white/25 focus:border-stellar-teal/60 outline-none" /> - - - - {/* La representación del usuario es la protección jurídica REAL - el - bloqueo por IP se salta con una VPN, una declaración no. Va junto al - botón que construye la corrida, no enterrada en un PDF, porque una - declaración que nadie leyó no declara nada. */} -

    - {lang( - 'By continuing you represent, on this and every occasion of use, that you are not located in or a resident of a prohibited jurisdiction, that you are not a sanctioned person or acting for one, and, on mainnet, that Payouts is offered where you are (today mainnet excludes the EEA, the UK and the US; testnet is open there as a demonstration). Nirium relies on this.', - 'Al continuar declaras, en esta y en cada ocasión de uso, que no te encuentras ni resides en una jurisdicción prohibida, que no eres una persona sancionada ni actúas por cuenta de una, y, en mainnet, que Payouts se ofrece donde estás (hoy mainnet excluye al EEE, el Reino Unido y Estados Unidos; testnet está abierto ahí como demostración). Nirium confía en esta declaración.')} -

    - -
    -

    - {p.batch.total} {total.toFixed(4)} {asset} - · {filledCount} {p.batch.recipients} -

    - -
    - - {error &&

    {error}

    } - - {skipped.length > 0 && ( -
    -

    {skipped.length} {p.skipped}

    -
      - {skipped.map((s, i) => ( -
    • - {shorten(s.wallet, 5)} - {s.reason} -
    • - ))} -
    -
    - )} - - {receipt && ( -
    -

    - ✅ {p.receipt.settled} · {receipt.recipientCount} {p.receipt.paid} · {receipt.totalAmount} {asset} -

    -
    - {receipt.explorer && ( - - {p.receipt.tx} · {shorten(receipt.txHash || "", 8)} ↗ - - )} - {receipt.cid && ( - - {p.receipt.ipfs} · {shorten(receipt.cid, 8)} ↗ - - )} - {/* Antes: "Vinculado a los términos · LCP L2 · SHA-256 verificado". - Con LCP_ENABLED apagado el recibo no lleva el contexto legal - (auditPayroll en ipfsAuditBridge.ts), así que no se afirma. */} -
    -
    - )} - )} -
    - - {/* Onboarding */} -
    -

    {p.onboard.title}

    -

    {p.onboard.desc}

    -
    - - {isConnected && address ? address : p.wallet.notConnected} - - -
    - {onboardMsg &&

    {onboardMsg}

    } -
    - - {/* Recent runs */} -
    -

    {p.runs.title}

    - {runs.length === 0 ? ( -

    {p.runs.empty}

    - ) : ( - // Sin ID de corrida ni CID del recibo: el recibo es evidencia de la - // empresa que pagó (misma regla que el Audit Trail del dashboard). - // La tx sí, porque ya es pública en la cadena. El proxy - // /api/payroll/runs tampoco devuelve esos dos campos. -
    - {runs.map((run, i) => ( -
    -
    -

    - {Number.isFinite(Number(run.totalAmount)) ? Number(run.totalAmount).toLocaleString('en-US', { maximumFractionDigits: 7 }) : run.totalAmount} {run.asset} - · {run.recipientCount} {Number(run.recipientCount) === 1 ? lang('recipient', 'destinatario') : lang('recipients', 'destinatarios')} -

    -
    -
    - {run.explorer && {p.receipt.tx} ↗} -
    -
    - ))} -
    - )} -
    - -

    - {network === "mainnet" ? p.network.mainnet : p.network.testnet} · {p.footerSuffix} -

    -
    -
    - ); +// Archivado el 30-nov-2026 (decidido por Giovanny): Payouts. Redirige a /treasury, la página de archivo. +export default function Page() { + redirect("/treasury"); } diff --git a/apps/web/app/(app)/pollar-adapter-documentation/page.tsx b/apps/web/app/(app)/pollar-adapter-documentation/page.tsx index a5079c30..a3b61c4a 100644 --- a/apps/web/app/(app)/pollar-adapter-documentation/page.tsx +++ b/apps/web/app/(app)/pollar-adapter-documentation/page.tsx @@ -91,7 +91,7 @@ export default function PollarAdapterDocumentationPage() {

    npm

    -

    nirium-pollar-adapter@0.6.6

    +

    nirium-pollar-adapter@0.7.0

    Peer requerido

    @@ -140,6 +140,11 @@ export default function PollarAdapterDocumentationPage() {

    El adaptador ya corre en la propia app de Nirium: el login social de Pollar está integrado en el navbar y en la consola de API keys, y cualquier persona puede probarlo hoy sin instalar nada.

    + +

    + Desde la 0.7.0 (29 de noviembre de 2026), el recibo de cada pago puede llevar adentro su contexto: qué orden, qué cotización, quién lo aprobó. Va dentro del registro firmado, no al lado, y si la app activa la opción y no da contexto, no se emite recibo. La app firma con su propia llave, nunca con la del usuario, y puede guardar el contexto para sí y poner en el recibo solo su huella. La propuesta para que cada app nueva de Pollar lo traiga por defecto está en{' '} + pollar-xyz/pollar#95. +

    {/* 03 · Lo que cambió */} @@ -218,7 +223,7 @@ export default function PollarAdapterDocumentationPage() {

    06 · Lo que ya está abierto

    Sin acceso especial que pedir

    - Audit Trail y Reporting ya son públicos en mainnet: cualquiera ancla y verifica recibos, y consulta los resúmenes, sin pedir acceso. Los recibos que ancla cada quien se quedan con quien los hizo; Nirium no los comparte con terceros. Treasury y Payouts siguen solo por invitación hasta tener una opinión legal por escrito. + Audit Trail y Reporting ya son públicos en mainnet: cualquiera ancla y verifica recibos, y consulta los resúmenes, sin pedir acceso. Los recibos que ancla cada quien se quedan con quien los hizo; Nirium no los comparte con terceros. Treasury y Payouts están en pausa en mainnet hasta tener una opinión legal por escrito.

    @@ -229,7 +234,7 @@ export default function PollarAdapterDocumentationPage() { GitHub nirium.xyz
    - nirium-pollar-adapter v0.6.6 + nirium-pollar-adapter v0.7.0
    diff --git a/apps/web/app/(app)/pricing/page.tsx b/apps/web/app/(app)/pricing/page.tsx index a555942d..d03b11c2 100644 --- a/apps/web/app/(app)/pricing/page.tsx +++ b/apps/web/app/(app)/pricing/page.tsx @@ -11,18 +11,14 @@ import { useLanguage } from "@/context/LanguageContext"; type Feature = { en: string; es: string }; const FEATURES_FREE: Feature[] = [ - { en: 'Testnet vault (NiriumVault on Soroban)', es: 'Vault testnet (NiriumVault en Soroban)' }, { en: 'Free API key: 10 requests/min and 100/day on keyed routes; anchoring and Reporting need no key today', es: 'API key gratis: 10 solicitudes/min y 100/día en rutas con key; anclar y Reporting hoy no piden key' }, { en: 'Audit trail (SHA-256 · IPFS)', es: 'Audit trail (SHA-256 · IPFS)' }, - { en: 'Payouts node (batch disbursement)', es: 'Nodo de dispersiones (batch)' }, { en: 'Package access (npm: nirium)', es: 'Acceso al paquete (npm: nirium)' }, { en: 'MCP server (Claude/Cursor)', es: 'MCP server (Claude/Cursor)' }, // Estas dos cobran donde existe la capacidad, no donde queda mejor en el // copy: la señal la produce el loop autónomo y la ejecución necesita una // llave firmante. El box de mainnet no tiene ninguna de las dos y responde // 501 sin cobrar, así que anunciarlas allá sería vender una puerta cerrada. - { en: 'x402 snapshot - $0.02 per call (factual loop data, not a recommendation)', es: 'Snapshot x402 - $0.02 por llamada (datos del loop, no una recomendación)' }, - { en: 'x402 execute - $0.25 per call (execution needs a signing key; mainnet box holds none)', es: 'Execute x402 - $0.25 por llamada (ejecutar necesita llave firmante; el box de mainnet no tiene)' }, ]; const FEATURES_MAINNET: Feature[] = [ @@ -38,12 +34,9 @@ const FEATURES_MAINNET: Feature[] = [ // pregunta de cualquiera que va a meter dinero en un contrato, y omitirla se // lee como que la salida está gated. El costo va medido, no adjetivado. // 9-nov-2026: fuera "~1.4 XLM, medido en mainnet": no se encontró la tx que lo respalde. - // Los 12.5 XLM son de NiriumVault en testnet (DEPLOYMENT_FEE en nirium_vault.rs). - { en: 'Treasury vault on DeFindex - deploy, deposit and withdraw, all with your own signature (deploying and depositing from this site are invite-only on mainnet until we have a written legal opinion); the vault is yours, Nirium can never withdraw from it, and you pay only the Stellar network fee, from your own wallet - Nirium charges nothing to deploy it', es: 'Bóveda de tesorería en DeFindex - desplegar, depositar y retirar, todo con tu propia firma (desplegar y depositar desde este sitio son solo por invitación en mainnet hasta tener una opinión legal por escrito); la bóveda es tuya, Nirium nunca puede retirar de ella, y solo pagas el fee de red de Stellar, desde tu propia wallet - Nirium no cobra nada por desplegarla' }, // El precio de payouts dejó de ser por-destinatario: cobrar por pago procesado // es como cobra un procesador de pagos, y contradecía los propios términos. // Ahora es licencia mensual por capacidad - misma economía, otra forma jurídica. - { en: 'Batch payouts - monthly software licence by permitted volume ($99 up to 250 records/mo, $249 up to 1,000), never a per-payment charge and never a percentage of what you disburse; mainnet is private Beta, invite-only (early access: network fee only today)', es: 'Payouts en lote - licencia mensual de software por volumen permitido ($99 hasta 250 registros/mes, $249 hasta 1,000), nunca un cargo por pago ni un porcentaje de lo que dispersas; mainnet en Beta privada, solo por invitación (early access: hoy solo fee de red)' }, { en: 'Audit anchoring - free during beta. Anchor hashes, not personal data: we can\'t guarantee anything is deleted from IPFS.', es: 'Anclaje de auditoría - gratis en beta. Ancla hashes, no datos personales: no podemos garantizar que algo se borre de IPFS.' }, { en: 'Reporting API - free (read-only). Institutional format; what you file with a regulator remains yours to decide', es: 'API de reportería - gratis (lectura). Formato institucional; lo que presentes ante un regulador lo decides tú' }, { en: 'Settled on-chain in USDC, per request', es: 'Liquidado on-chain en USDC, por request' }, @@ -52,31 +45,25 @@ const FEATURES_MAINNET: Feature[] = [ const FEATURES_GROWTH: Feature[] = [ { en: 'Everything in Free', es: 'Todo lo de Free' }, - // Dos bóvedas distintas y hay que decirlo, o se lee como que la audit-gated - // ya está viva: NiriumVault es contrato nuestro y espera auditoría; la de - // DeFindex es contrato ajeno ya auditado y del cliente - por eso una puede - // ir a mainnet hoy y la otra no. - { en: 'Nirium’s own mainnet vault (planned, after an audit)', es: 'Vault propio de Nirium en mainnet (planeado, después de una auditoría)' }, - { en: 'Treasury node - autonomously moves idle capital into the yield strategy and back out, on a DeFindex vault structured for you to own (early access, no cost during beta - invite-only on mainnet until there is a written legal opinion)', es: 'Nodo de tesorería - mueve solo el capital ocioso hacia la estrategia de rendimiento y de regreso, sobre una bóveda DeFindex pensada para que sea tuya (early access, sin costo durante la beta - solo por invitación en mainnet hasta tener una opinión legal por escrito)' }, { en: 'Higher API rate limits, set per account', es: 'Límites de API más altos, definidos por cuenta' }, { en: 'Institutional-format exports (CSV/JSON)', es: 'Exportes formato institucional (CSV/JSON)' }, { en: 'IPFS anchoring (Pinata)', es: 'Anclaje IPFS (Pinata)' }, { en: 'x402 agentic payments', es: 'Pagos agénticos x402' }, - { en: 'Payouts / batch disbursement', es: 'Dispersiones / pagos por lote' }, { en: 'LCP legal layer (planned, switched off today)', es: 'Capa legal LCP (planeada, hoy apagada)' }, - // 9-nov-2026: fuera "Cross-border USDC transfers" (ya lo cubre Payouts, no es - // otro producto) y "Canal Slack dedicado" (Nirium no tiene Slack; tiene Discord). - { en: 'CETES and USDC reference rates, attributed to their source', es: 'Tasas de referencia CETES y USDC, con su fuente' }, - { en: 'Visual Strategy Builder (drag & drop; saves drafts, does not execute)', es: 'Strategy Builder visual (drag & drop; guarda borradores, no ejecuta)' }, { en: 'Priority support (response time by agreement)', es: 'Soporte prioritario (tiempo de respuesta por acuerdo)' }, { en: 'Dedicated channel on the Nirium Discord', es: 'Canal dedicado en el Discord de Nirium' }, + // Dos bóvedas distintas y hay que decirlo, o se lee como que la audit-gated + // ya está viva: NiriumVault es contrato nuestro y espera auditoría; la de + // DeFindex es contrato ajeno ya auditado y del cliente - por eso una puede + // ir a mainnet hoy y la otra no. + // 9-nov-2026: fuera "Cross-border USDC transfers" (ya lo cubre Payouts, no es + // otro producto) y "Canal Slack dedicado" (Nirium no tiene Slack; tiene Discord). ]; const FEATURES_ENTERPRISE: Feature[] = [ { en: 'Everything in Growth', es: 'Todo lo de Growth' }, { en: 'Volume API pricing', es: 'Precios por volumen de API' }, { en: 'White-label option', es: 'Opción white-label' }, - { en: 'Custom Soroban vault logic', es: 'Lógica de vault Soroban custom' }, { en: 'Audit-readiness support', es: 'Soporte de preparación para auditorías' }, { en: 'Support SLA by agreement', es: 'SLA de soporte por acuerdo' }, { en: 'Custom integrations (ERP, Core Banking)', es: 'Integraciones custom (ERP, Core Banking)' }, @@ -91,9 +78,7 @@ type ComparisonRow = { }; const COMPARISON: ComparisonRow[] = [ - { feature: { en: 'Treasury vault', es: 'Bóveda de tesorería' }, free: { en: 'NiriumVault (testnet)', es: 'NiriumVault (testnet)' }, growth: { en: 'DeFindex (mainnet, invite-only)', es: 'DeFindex (mainnet, por invitación)' }, enterprise: 'Custom' }, { feature: { en: 'API rate limit', es: 'Límite de API' }, free: { en: '10 req/min · 100/day (keyed routes)', es: '10 req/min · 100/día (rutas con key)' }, growth: { en: 'Higher, per account', es: 'Más alto, por cuenta' }, enterprise: { en: 'By agreement', es: 'Por acuerdo' } }, - { feature: { en: 'Signing model', es: 'Modelo de firma' }, free: { en: 'Your key withdraws; the agent spends up to a cap you set (NiriumVault)', es: 'Tu llave retira; el agente gasta hasta un tope que tú fijas (NiriumVault)' }, growth: { en: 'Your keys + revocable rebalance role', es: 'Tus llaves + rol de rebalanceo revocable' }, enterprise: { en: 'Configurable', es: 'Configurable' } }, { feature: { en: 'Institutional export', es: 'Export institucional' }, free: '✓', growth: '✓', enterprise: '✓' }, { feature: { en: 'IPFS anchoring', es: 'Anclaje IPFS' }, free: { en: 'Free during beta', es: 'Gratis en beta' }, growth: '✓', enterprise: '✓' }, { feature: { en: 'x402', es: 'x402' }, free: { en: 'Testnet', es: 'Testnet' }, growth: '✓', enterprise: '✓' }, @@ -131,8 +116,8 @@ export default function PricingPage() {

    {lang( - 'Start free. On mainnet you pay per request - your agent settles in USDC on-chain, no card needed.', - 'Empieza gratis. En mainnet pagas por request - tu agente liquida en USDC on-chain, sin tarjeta.')} + 'Start free. On mainnet you pay per request - your agent pays in USDC on-chain, no card needed.', + 'Empieza gratis. En mainnet pagas por request - tu agente paga en USDC on-chain, sin tarjeta.')}

    @@ -173,13 +158,15 @@ export default function PricingPage() {

    {lang('MPP Charge: experimental, untested on mainnet - for paid access, use x402.', 'MPP Charge: experimental, sin probar en mainnet; para acceso pagado usa x402.')}

    -

    +

    + {lang('Dated corrections (MPP Charge)', 'Correcciones con fecha (MPP Charge)')} +

    {lang('Update, 2026-10-04 (checked against the nirium 0.16.0 changelog that day):', 'Actualización, 2026-10-04 (verificado contra el changelog de nirium 0.16.0 ese día):')}{' '} {lang( 'this card used to list MPP Charge as live on mainnet. That was wrong: MPP Charge has never been verified end to end against our hosted endpoints (the testnet one rejected the payment when tested on 2026-10-01; mainnet was never tested). Use x402 for paid access.', 'esta tarjeta listaba MPP Charge como en vivo en mainnet. Era incorrecto: MPP Charge nunca se verificó de punta a punta contra nuestros endpoints alojados (el de testnet rechazó el pago al probarlo el 2026-10-01; el de mainnet nunca se probó). Usa x402 para acceso pagado.')}

    -

    +

    {lang('Update, 2026-10-15 (checked against Horizon testnet that day):', 'Actualización, 2026-10-15 (verificado contra Horizon testnet ese día):')}{' '} {lang( 'the note above no longer holds for testnet. MPP Charge was verified on testnet on 2026-10-15 with the nirium SDK, in pull and push mode, both settled:', @@ -188,6 +175,7 @@ export default function PricingPage() { 96d43d6f….{' '} {lang('These were internal tests, not customer usage. Mainnet is untested.', 'Fueron pruebas internas, no uso de clientes. Mainnet sigue sin probarse.')}

    +
    diff --git a/apps/web/app/(app)/ramp/page.tsx b/apps/web/app/(app)/ramp/page.tsx index e73cd3f6..133a7b6d 100644 --- a/apps/web/app/(app)/ramp/page.tsx +++ b/apps/web/app/(app)/ramp/page.tsx @@ -1,60 +1,6 @@ -'use client'; -import { motion } from 'framer-motion'; -import FiatRamp from "@/components/layout/FiatRamp"; -import { SectionBrandLogo } from "@/components/ui/SectionBrandLogo"; -import { useLanguage } from "@/context/LanguageContext"; +import { redirect } from "next/navigation"; -import { ComplianceBanner } from '@/components/ui/ComplianceBanner'; - -export default function RampPage() { - const { t } = useLanguage(); - - return ( -
    - -
    - {/* Background FX */} -
    -
    -
    -
    -
    -
    - -
    - - - -
    - -
    - 🏦 - {t.ramp.header.badge} -
    -
    -

    - {t.ramp.header.title} -

    -

    - {t.ramp.header.subtitle} -

    -
    - - - - -
    -
    -
    - ); +// Archivado el 30-nov-2026 (decidido por Giovanny): la rampa de CETES vía Etherfuse. Redirige a /treasury, la página de archivo. +export default function Page() { + redirect("/treasury"); } diff --git a/apps/web/app/(app)/risk-disclosure/layout.tsx b/apps/web/app/(app)/risk-disclosure/layout.tsx index 9c2eeafe..d20b2874 100644 --- a/apps/web/app/(app)/risk-disclosure/layout.tsx +++ b/apps/web/app/(app)/risk-disclosure/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/risk-disclosure", title: "Risk Disclosure", - description: "The technical and operational risks of using Nirium's automation, smart contracts and the Stellar network.", + description: "The technical and operational risks of using Nirium: the pre-sign policy, smart contracts and the networks it runs on.", }); export default function RiskDisclosureLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/risk-disclosure/page.tsx b/apps/web/app/(app)/risk-disclosure/page.tsx index 6d2ba069..90f76615 100644 --- a/apps/web/app/(app)/risk-disclosure/page.tsx +++ b/apps/web/app/(app)/risk-disclosure/page.tsx @@ -11,8 +11,8 @@ export default function RiskDisclosurePage() { const risk = t.risk_disclosure || { title: "Risk Disclosure", badge: "Risk notice", - last_updated: "Last updated: November 19, 2026", - mandatory: "Read this before using Nirium: it is experimental open-source software on Stellar.", + last_updated: "Last updated: December 1, 2026", + mandatory: "Read this before using Nirium: it is experimental software on Stellar; its packages are open source.", sections: {}, footer: "Using Nirium means you have read these risks." }; diff --git a/apps/web/app/(app)/security/layout.tsx b/apps/web/app/(app)/security/layout.tsx index b5709764..86561832 100644 --- a/apps/web/app/(app)/security/layout.tsx +++ b/apps/web/app/(app)/security/layout.tsx @@ -3,7 +3,7 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/security", title: "Security", - description: "How Nirium stays non-custodial: who holds the keys, what the agent can and cannot sign, and how vaults are controlled.", + description: "How Nirium stays non-custodial: who holds the keys in each node, and what Nirium can and cannot sign.", }); export default function SecurityLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/security/page.tsx b/apps/web/app/(app)/security/page.tsx index 3248b484..8097de50 100644 --- a/apps/web/app/(app)/security/page.tsx +++ b/apps/web/app/(app)/security/page.tsx @@ -1,4 +1,4 @@ -/** Nirium Security - who holds the keys, on mainnet (DeFindex) and testnet (NiriumVault) **/ +/** Nirium Security - who holds the keys, node by node. 30-nov-2026: Treasury, Payouts y NiriumVault archivados; sus secciones salieron. **/ 'use client'; // Revisado el 8-nov-2026 contra la cadena y el código: @@ -85,8 +85,8 @@ const NODE_ROWS: NodeRow[] = [ node: 'x402', en: "The buyer's own wallet signs each payment and a facilitator settles it on Stellar. If you sell with x402Serve, the USDC goes from the buyer straight to your account: Nirium is not in the path. If you pay Nirium's own API, Nirium is the seller and receives that payment.", es: 'La wallet del comprador firma cada pago y un facilitador lo liquida en Stellar. Si vendes con x402Serve, el USDC va del comprador directo a tu cuenta: Nirium no está en medio. Si pagas la API de Nirium, Nirium es el vendedor y recibe ese pago.', - mainEn: 'The mainnet API server (x402, Audit Trail, Reporting) has no Stellar signing key. The only key Nirium runs on mainnet is a separate rebalancer\'s, and it holds only the DeFindex rebalance role (see Treasury below).', - mainEs: 'El servidor de la API en mainnet (x402, Audit Trail, Reporting) no tiene ninguna llave de Stellar. La única llave que Nirium corre en mainnet es la de un rebalanceador aparte, y solo tiene el rol de rebalanceo de DeFindex (ver Tesorería abajo).', + mainEn: 'The mainnet API server (x402, Audit Trail, Reporting) has no Stellar signing key. The rebalancer that held a DeFindex rebalance role is stopped and archived with Treasury.', + mainEs: 'El servidor de la API en mainnet (x402, Audit Trail, Reporting) no tiene ninguna llave de Stellar. El rebalanceador que tenía un rol de rebalanceo en DeFindex está detenido y archivado junto con Tesorería.', testEn: 'The testnet agent holds its own test key to pay for demo calls.', testEs: 'El agente de testnet tiene su propia llave de prueba para pagar las llamadas de demostración.', }, @@ -111,31 +111,13 @@ const NODE_ROWS: NodeRow[] = [ }, { node: 'Reporting', - en: 'Read-only. It summarizes what is already recorded (payments, receipts, payout runs). It cannot sign or move anything.', - es: 'Solo lectura. Resume lo que ya está registrado (pagos, recibos, lotes de pago). No puede firmar ni mover nada.', + en: 'Read-only. It summarizes what is already recorded (payments and receipts). It cannot sign or move anything.', + es: 'Solo lectura. Resume lo que ya está registrado (pagos y recibos). No puede firmar ni mover nada.', mainEn: 'Public summary, no key needed.', mainEs: 'Resumen público, sin llave.', testEn: 'Public summary, no key needed.', testEs: 'Resumen público, sin llave.', }, - { - node: 'Payouts', - en: 'Nirium builds each batch as an unsigned transaction. The company signs it with its own wallet, and only then is it sent. Nirium never holds the funds being paid out.', - es: 'Nirium arma cada lote como una transacción sin firmar. La empresa la firma con su propia wallet, y solo entonces se envía. Nirium nunca sostiene los fondos que se pagan.', - mainEn: 'Invite-only, and every run requires accepting the Payouts Terms.', - mainEs: 'Solo por invitación, y cada lote exige aceptar los Términos de Payouts.', - testEn: 'Testnet only: on Trustless Work escrows, the agent can sign milestone approvals and releases with its own key, limited to allowlisted escrow contracts and authorized API keys.', - testEs: 'Solo en testnet: en escrows de Trustless Work, el agente puede firmar la aprobación y liberación de milestones con su propia llave, limitado a contratos de escrow en la lista permitida y a API keys autorizadas.', - }, - { - node: 'Treasury', - en: "The agent can only rebalance, never withdraw. Details for each network are in the sections below.", - es: 'El agente solo puede rebalancear, nunca retirar. El detalle de cada red está en las secciones de abajo.', - mainEn: 'Invite-only: a DeFindex vault you own, where the agent holds only the rebalance role. Deploying, depositing and asking for proposals through Nirium need an invited (institutional) key; withdrawing is always open.', - mainEs: 'Solo por invitación: una bóveda de DeFindex que es tuya, donde el agente solo tiene el rol de rebalanceo. Desplegar, depositar y pedir propuestas a través de Nirium requiere una llave invitada (institucional); retirar siempre está abierto.', - testEn: 'NiriumVault, source-verified: only your key withdraws.', - testEs: 'NiriumVault, con código verificado: solo tu llave retira.', - }, ]; export default function SecurityPage() { @@ -163,8 +145,8 @@ export default function SecurityPage() {

    {lang( - "Nirium never holds a key that can withdraw your funds, in any node. Below: who signs in each one, on the network you have selected, and then Payouts, Audit Trail and the treasury in detail.", - 'Nirium nunca tiene una llave que pueda retirar tus fondos, en ningún nodo. Abajo: quién firma en cada uno, en la red que tienes elegida, y luego Payouts, Audit Trail y la tesorería a detalle.')} + "Nirium never holds a key that can withdraw your funds, in any node. Below: who signs in each one, on the network you have selected, and then Audit Trail in detail.", + 'Nirium nunca tiene una llave que pueda retirar tus fondos, en ningún nodo. Abajo: quién firma en cada uno, en la red que tienes elegida, y luego Audit Trail a detalle.')}

    @@ -192,57 +174,14 @@ export default function SecurityPage() {
    ))}
    -
    - - - {/* PAYOUTS (11-nov-2026): antes solo tenía una tarjeta. */} -
    -
    -
    - - {lang('Payouts · batches and milestone escrows', 'Payouts · lotes y escrows por milestone')} - -
    -

    - {lang('Payouts: the company signs, the receiver is fixed by a person', 'Payouts: la empresa firma, el receptor lo fija una persona')} -

    -
    -
    - -
    {lang('Batch payments: your wallet signs', 'Pagos por lote: firma tu wallet')}
    -

    - {lang( - 'Nirium builds each batch as an unsigned transaction. The company signs it with its own wallet, and Nirium only sends the transaction it already signed. On mainnet it is invite-only: an authorized API key, the Payouts Terms accepted on every run, and the company identifies itself.', - 'Nirium arma cada lote como una transacción sin firmar. La empresa la firma con su propia wallet, y Nirium solo envía la transacción que ella ya firmó. En mainnet es solo por invitación: una API key autorizada, los Términos de Payouts aceptados en cada lote y la empresa se identifica.')} -

    -
    -
    - -
    {lang('Milestone escrows: testnet only', 'Escrows por milestone: solo testnet')}
    -

    - {lang( - "With Trustless Work escrows, a person signs the deployment, and that fixes who each milestone pays. If the escrow names Nirium's agent as approver or release signer, the agent can sign approvals and releases with its own key. Only for contracts on an allowlist that is empty by default and set on our server, and only for authorized API keys.", - 'En los escrows de Trustless Work, una persona firma el despliegue, y eso fija a quién paga cada milestone. Si el escrow nombra al agente de Nirium como aprobador o firmante de liberación, el agente puede firmar aprobaciones y liberaciones con su propia llave. Solo en contratos de una lista permitida, vacía por default y fijada en nuestro servidor, y solo con API keys autorizadas.')} -

    -
    -
    - -
    {lang("Worst case if the agent's key leaks", 'El peor caso si se filtra la llave del agente')}
    -

    - {lang( - 'Someone could approve or release milestones of allowlisted escrows early. They could not send the money anywhere new: the approve and release calls take a milestone number, never a receiver. This flow is not enabled on mainnet.', - 'Alguien podría aprobar o liberar antes de tiempo milestones de escrows en la lista permitida. No podría mandar el dinero a otro lado: las llamadas de aprobar y liberar reciben un número de milestone, nunca un receptor. Este flujo no está activo en mainnet.')} -

    -
    -
    - + {/* 27-nov-2026: comprobado en Fly ese día: los dos markets no tienen ningún secreto y + el nodo de mainnet no guarda llaves de Solana ni de EVM. */} +

    + {lang( + 'On Solana, Avalanche, Base and Arbitrum: whoever pays signs with their own wallet, and the Nirium node holds no key on those chains. The four x402 markets only receive payments, to an address whose key is not on the server.', + 'En Solana, Avalanche, Base y Arbitrum: quien paga firma con su propia wallet, y el nodo de Nirium no tiene ninguna llave en esas redes. Los cuatro markets x402 solo reciben pagos, a una dirección cuya llave no está en el servidor.')}{' '} + {lang('What works on each chain', 'Qué funciona en cada red')} +

    @@ -305,120 +244,6 @@ export default function SecurityPage() {
    - {/* MAINNET: DEFINDEX */} -
    -
    -
    - - {lang('Mainnet · invite-only', 'Mainnet · solo por invitación')} - -
    -

    - {lang('Treasury on mainnet: a DeFindex vault you own', 'Tesorería en mainnet: una bóveda de DeFindex que es tuya')} -

    -
    - {[ - { - t: lang('The agent can only rebalance', 'El agente solo puede rebalancear'), - d: lang( - "Nirium's agent holds DeFindex's RebalanceManager role, nothing else. Our code only sends Invest and Unwind. The contract's rebalance() also accepts two swap instructions, but none of the four takes a destination address: whatever they produce stays in the vault, so the role cannot send funds anywhere. Worst case if the agent's key leaked: someone could swap at a bad price inside the vault and lose value to slippage.", - 'El agente de Nirium tiene el rol RebalanceManager de DeFindex y nada más. Nuestro código solo manda Invest y Unwind. El rebalance() del contrato también acepta dos instrucciones de swap, pero ninguna de las cuatro recibe una dirección de destino: lo que producen se queda en la bóveda, así que ese rol no puede mandar fondos a ningún lado. Peor caso si se filtrara la llave del agente: alguien podría hacer swaps a mal precio dentro de la bóveda y perder valor por slippage.'), - }, - { - t: lang('Withdrawals stay with the owner', 'Los retiros son del dueño'), - d: lang( - "The role that can withdraw (Manager) sits with the vault owner's key, separate from the agent's key. The owner can also replace the agent's role at any time.", - 'El rol que puede retirar (Manager) está en la llave del dueño de la bóveda, separada de la del agente. El dueño además puede quitarle el rol al agente cuando quiera.'), - }, - { - t: lang('Audited, third-party contract', 'Contrato de terceros, auditado'), - d: lang( - 'The vault contract is DeFindex (PaltaLabs), audited by OtterSec in March 2025. Nirium did not write it.', - 'El contrato de la bóveda es de DeFindex (PaltaLabs), auditado por OtterSec en marzo de 2025. Nirium no lo escribió.'), - }, - ].map((c) => ( -
    - -
    {c.t}
    -

    {c.d}

    -
    - ))} -
    -

    - {lang( - "Today the only live vault is Nirium's own, with its own funds: it proves the mechanism, not client use. Access for clients is invite-only until we have a written legal opinion.", - 'Hoy la única bóveda en vivo es la de Nirium, con fondos propios: prueba el mecanismo, no uso de clientes. El acceso para clientes es solo por invitación hasta tener una opinión legal por escrito.')} -

    -
    - {DEFINDEX_EVIDENCE.map((e) => ( - - {lang(e.en, e.es)} - - ))} - - {lang('How to verify it yourself', 'Cómo verificarlo tú mismo')} - -
    -
    -
    - - {/* TESTNET: NIRIUMVAULT - two kinds of control */} -
    -
    -
    - - {lang('Testnet · NiriumVault', 'Testnet · NiriumVault')} - -
    -

    - {lang("Nirium's own contract: two kinds of control", 'El contrato propio de Nirium: dos tipos de control')} -

    - -
    -
    -
    - -

    {lang('Your vault: your key', 'Tu bóveda: tu llave')}

    -
    -
      - {[ - lang('Only your key withdraws, and only to your own address', 'Solo tu llave retira, y solo a tu propia dirección'), - lang('Only your key closes the vault (its balance must be 0)', 'Solo tu llave cierra la bóveda (su saldo debe ser 0)'), - lang('You can delegate to the agent up to a cumulative cap you set (max_execution_amount)', 'Puedes delegar al agente hasta un tope acumulado que tú fijas (max_execution_amount)'), - lang('You can revoke the agent at any time, even while the contract is paused', 'Puedes revocar al agente cuando quieras, incluso con el contrato en pausa'), - ].map((x) => ( -
    • - - {x} -
    • - ))} -
    -
    - -
    -
    - -

    {lang('Emergency pause: Nirium', 'Pausa de emergencia: Nirium')}

    -
    -
      - {[ - lang("Nirium's admin key can pause the whole contract (every vault) in an emergency", 'La llave admin de Nirium puede pausar todo el contrato (todas las bóvedas) en una emergencia'), - lang('While paused, nobody can withdraw, deposit or close a vault, including you. Pausing never moves funds', 'En pausa, nadie puede retirar, depositar ni cerrar una bóveda, tampoco tú. Pausar nunca mueve fondos'), - lang('The contract supports a 2-of-3 pause (admin plus one cosigner). It is not active yet: no cosigners are registered on contract CDMFURE6… (checked on-chain, 21 Nov 2026), so today the admin pauses alone. Registering them is planned', 'El contrato admite una pausa 2-de-3 (admin más un cosignatario). Todavía no está activa: no hay cosignatarios registrados en el contrato CDMFURE6… (revisado en la cadena, 21 nov 2026), así que hoy el admin pausa solo. Registrarlos está planeado'), - lang('Cosigners are contract-wide and set by the admin, not by each vault owner', 'Los cosignatarios son de todo el contrato y los fija el admin, no cada dueño de bóveda'), - ].map((x) => ( -
    • - - {x} -
    • - ))} -
    -
    -
    -
    -
    - {/* WHAT NIRIUM CANNOT DO */}
    @@ -434,10 +259,7 @@ export default function SecurityPage() {
    {[ lang('Withdraw your funds, or send them to any address', 'Retirar tus fondos, o mandarlos a cualquier dirección'), - lang('Spend more than the cap you set when delegating (NiriumVault)', 'Gastar más del tope que fijaste al delegar (NiriumVault)'), lang('Access your private keys', 'Acceder a tus llaves privadas'), - lang('Change who a milestone escrow pays: a person fixes that when deploying it', 'Cambiar a quién paga un escrow por milestone: eso lo fija una persona al desplegarlo'), - lang('Change NiriumVault code once deployed: the live WASM has no upgrade function', 'Cambiar el código de NiriumVault una vez desplegado: el WASM en vivo no tiene función de actualización'), ].map((item) => (
    ))}
    -
    - -

    - {lang( - "What Nirium CAN do on NiriumVault (testnet): pause the whole contract with its admin key. Today that takes no second signature. It freezes withdrawals until it is unpaused, but it cannot move funds.", - 'Lo que Nirium SÍ puede hacer en NiriumVault (testnet): pausar todo el contrato con su llave admin. Hoy eso no requiere una segunda firma. Congela los retiros hasta que se reanude, pero no puede mover fondos.')} -

    -
    -
    -
    - - {/* THE CONTRACT */} -
    -
    -

    - {lang('The real contract', 'El contrato real')} -

    -

    - {lang( - 'NiriumVault is deployed on Stellar Testnet and is verifiable.', - 'NiriumVault está desplegado en Stellar Testnet y es verificable.')} -

    - -
    -
    - Contract ID - Stellar Testnet -
    - {VAULT_ID} - -
    -
    - WASM hash - {lang('verified on Stellar Expert, 9 Nov 2026', 'verificado en Stellar Expert, 9 nov 2026')} -
    - {VAULT_WASM} -

    - {lang( - `GitHub built this WASM from the public repo (commit 8489481) and attested it, and that exact file is what was deployed. Stellar Expert matched it to the source and shows the contract as "verified". The code has no upgrade, migrate or set_wasm function and never calls update_current_contract_wasm, so it cannot be changed after deployment. Check it yourself: stellar contract fetch --id ${VAULT_ID} --network testnet, then compare its sha256 with the release file.`, - `GitHub compiló este WASM desde el repo público (commit 8489481) y lo firmó, y ese archivo exacto es el que se desplegó. Stellar Expert lo comparó con el código y marca el contrato como "verified". El código no tiene función upgrade, migrate ni set_wasm y nunca llama a update_current_contract_wasm, así que no se puede cambiar después de desplegado. Compruébalo tú: stellar contract fetch --id ${VAULT_ID} --network testnet, y compara su sha256 con el archivo del release.`)} -

    - - - {lang('The release: WASM and build attestation', 'El release: WASM y atestación del build')} - -
    -
    -
    -
    - - {/* PREVIOUS CONTRACTS + 2-OF-3 (9-nov-2026) */} -
    -
    -
    -

    {lang('Previous NiriumVault deployments (testnet)', 'Despliegues anteriores de NiriumVault (testnet)')}

    -

    - {lang( - 'They stay on testnet and cannot be changed. nirium.xyz no longer uses them, so vault counts restart on the verified contract.', - 'Siguen en testnet y no se pueden cambiar. nirium.xyz ya no los usa, así que el conteo de bóvedas empieza de nuevo en el contrato verificado.')} -

    -
    - {PREVIOUS_VAULTS.map((v) => ( -
    - {v.id} -

    {language === 'es' ? v.es : v.en}

    -
    - ))} -
    -
    - -
    -

    {lang('Not built yet: withdrawals that need 2 of 3 people', 'Todavía no construido: retiros que piden a 2 de 3 personas')}

    -

    - {lang( - "Today a withdrawal needs one signature: the vault owner's. The 2-of-3 in the contract only covers the emergency pause, and no cosigners are registered yet. A company that wants, say, its CFO, CEO and accountant to approve every withdrawal can get that from Stellar itself, without changing the contract: the vault owner is a Stellar account with three signers and a threshold of two. Soroban checks that account's signers against its medium threshold, so a withdrawal with a single signature is rejected by the network. What is missing is on our side: nirium.xyz signs with one wallet and cannot collect a second signature yet. Planned, not built.", - 'Hoy un retiro pide una sola firma: la del dueño de la bóveda. El 2-de-3 del contrato solo cubre la pausa de emergencia, y todavía no hay cosignatarios registrados. Una empresa que quiera que, por ejemplo, su CFO, su CEO y su contador aprueben cada retiro puede obtenerlo de Stellar mismo, sin cambiar el contrato: el dueño de la bóveda es una cuenta de Stellar con tres firmantes y umbral de dos. Soroban revisa los firmantes de esa cuenta contra su umbral medio, así que la red rechaza un retiro con una sola firma. Lo que falta es de nuestro lado: nirium.xyz firma con una sola wallet y todavía no puede juntar una segunda firma. Planeado, no construido.')} -

    - - - {lang('Stellar docs: authorization and multisig', 'Docs de Stellar: autorización y multifirma')} - -
    -
    -
    - - {/* AUDIT */} -
    -
    -

    - {lang('Audit', 'Auditoría')} -

    -
    -
    - -
    {lang('DeFindex (mainnet)', 'DeFindex (mainnet)')}
    -
    {lang('OtterSec, Mar 2025', 'OtterSec, mar 2025')}
    -

    {lang("Third-party contract; the audit is published by its authors (PaltaLabs) in their repo", 'Contrato de terceros; la auditoría la publican sus autores (PaltaLabs) en su repo')}

    -
    -
    - -
    {lang('NiriumVault (testnet)', 'NiriumVault (testnet)')}
    -
    {lang('Pending', 'Pendiente')}
    -

    - {lang('No external audit yet: it stays on testnet until one is done', 'Sin auditoría externa todavía: se queda en testnet hasta que se haga')} -

    -
    -
    @@ -586,17 +282,16 @@ export default function SecurityPage() { {lang('Your keys, your funds', 'Tus llaves, tus fondos')}
    - {/* Antes llevaba a /build/niriumtober, que ya cerró. Las bóvedas de - testnet se crean en el dashboard. */} - + {/* 30-nov-2026: Tesorería archivada; el CTA lleva a verificar un recibo. */} + - +
    diff --git a/apps/web/app/(app)/stats/StatsClient.tsx b/apps/web/app/(app)/stats/StatsClient.tsx index 20b841ff..bed04299 100644 --- a/apps/web/app/(app)/stats/StatsClient.tsx +++ b/apps/web/app/(app)/stats/StatsClient.tsx @@ -125,17 +125,6 @@ interface StatsResponse { }; } -const INSTAWARDS = [ - { - label: { en: 'Instaward #1', es: 'Instaward #1' }, - hash: 'fd0f7469ae78b76ca5c4186cd7e1b24c081c407758a92cff3a56f376d01e91d1', - }, - { - label: { en: 'Instaward #2', es: 'Instaward #2' }, - hash: '7784ad6eb2b27ace75ce2fe4b7290fb1b8241da425331bfbda2e939b47759b7e', - }, -]; - function fmtDate(iso: string | null, lang: (en: string, es: string) => string): string { if (!iso) return lang('never', 'nunca'); return new Date(iso).toLocaleDateString(lang('en-US', 'es-MX'), { year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' }); @@ -259,8 +248,8 @@ export default function StatsClient({ initialData }: { initialData: StatsRespons

    {lang( - 'Every number below is fetched live when you load this page: from Horizon, npm, PyPI and GitHub, and, for Audit Trail and Payouts, from our own public reporting API (labeled on each card). No number is typed in by hand. Each card links to the exact query that produced it.', - 'Cada número de abajo se lee en vivo al cargar esta página: de Horizon, npm, PyPI y GitHub y, para Audit Trail y Payouts, de nuestra propia API pública de reporting (marcado en cada tarjeta). Ningún número se escribe a mano. Cada tarjeta enlaza a la consulta exacta que lo produjo.')} + 'Every number below is fetched live when you load this page: from Horizon, npm, PyPI and GitHub, and, for Audit Trail, from our own public reporting API (labeled on each card). No number is typed in by hand. Each card links to the exact query that produced it.', + 'Cada número de abajo se lee en vivo al cargar esta página: de Horizon, npm, PyPI y GitHub y, para Audit Trail, de nuestra propia API pública de reporting (marcado en cada tarjeta). Ningún número se escribe a mano. Cada tarjeta enlaza a la consulta exacta que lo produjo.')}

    {/* 15-nov-2026: el bloque de testnet ya no depende del selector TEST/MAIN. NetworkContext arranca en 'testnet' y luego lee la elección guardada, así que @@ -344,18 +333,6 @@ export default function StatsClient({ initialData }: { initialData: StatsRespons } /> - - {data?.treasuryRebalances && <>{lang('last', 'último')}: {fmtDate(rb.lastAt, lang)}} - - - } - /> } /> - {lang('What the Payouts node registers (mainnet-labeled). Mainnet is invite-only.', 'Lo que el nodo de Payouts registra (etiquetado mainnet). Mainnet es solo por invitación.')}} - /> )} - {/* DELIVERY HISTORY */} -
    -
    -

    {lang('Delivery history', 'Historial de entrega')}

    -
    - {INSTAWARDS.map((iw) => ( -
    - - {lang(iw.label.en, iw.label.es)} - Stellar Community Fund - - {iw.hash} -
    - ))} -
    -
    -
    - {/* METHODOLOGY */}
    @@ -866,11 +816,11 @@ export default function StatsClient({ initialData }: { initialData: StatsRespons anterior mientras se genera la nueva (medido: el snapshot del 8-nov traía datos de 11 h antes). La hora de generación siempre se muestra arriba. */}
  • {lang('Every metric is fetched server-side from its source, never hand-edited. The page is regenerated at most every 30 minutes; the first visit after a quiet period can get the previous version while a new one is built - the time it was generated is shown at the top.', 'Cada métrica se obtiene del lado del servidor desde su fuente, nunca se edita a mano. La página se regenera como máximo cada 30 minutos; la primera visita después de un rato sin tráfico puede recibir la versión anterior mientras se genera la nueva - arriba se muestra a qué hora se generó.')}
  • -
  • {lang('x402 settlements and Treasury rebalances are counted directly from Horizon operations on the mainnet accounts - see the source link on each card.', 'Las liquidaciones x402 y los rebalanceos del Treasury se cuentan directo de las operaciones en Horizon sobre las cuentas de mainnet - ver el link de fuente en cada tarjeta.')}
  • +
  • {lang('x402 settlements are counted directly from Horizon operations on the mainnet accounts - see the source link on each card.', 'Las liquidaciones x402 se cuentan directo de las operaciones en Horizon sobre las cuentas de mainnet - ver el link de fuente en cada tarjeta.')}
  • {lang('GitHub-backed lists (external merged PRs, community contributions) are cached up to 1 hour to stay inside GitHub\u2019s unauthenticated rate limit. A request that fails is shown as a failure, never silently dropped.', 'Las listas que vienen de GitHub (PRs externos mergeados, contribuciones de la comunidad) se cachean hasta 1 hora para no pasarse del límite sin autenticación de GitHub. Una consulta que falla se muestra como falla, nunca se omite en silencio.')}
  • {lang('Testnet activity has its own section, labeled TESTNET, right after the main mainnet block. It includes automated development and testing traffic, so it is never counted in the mainnet numbers.', 'La actividad de testnet tiene su propia sección, marcada TESTNET, justo después del bloque principal de mainnet. Incluye tráfico automatizado de desarrollo y pruebas, así que nunca se suma a los números de mainnet.')}
  • {lang('Payers are read from the USDC transfer itself, not the transaction source (x402 routes every payment through a per-transaction facilitator account). A wallet counts as internal only with proof we hold its key, and as external only with its operator\u2019s own public statement; a third party\u2019s wallet that we coordinated and initially funded is listed apart as an integration test, not as an external payer. Who created or funded a wallet is never treated as proof of who controls it, and funding origin is disclosed.', 'Los pagadores se leen de la transferencia de USDC, no de la fuente de la transacción (x402 pasa cada pago por una cuenta de facilitador distinta). Una wallet cuenta como interna solo con prueba de que tenemos su llave, y como externa solo con declaración pública de su operador; la wallet de un tercero que coordinamos y fondeamos al inicio se lista aparte como prueba de integración, no como pagador externo. Quién creó o fondeó una wallet nunca se toma como prueba de quién la controla, y el origen del fondeo se revela.')}
  • -
  • {lang('Audit Trail and Payouts figures come from Nirium\u2019s own public reporting API, filtered to mainnet-labeled rows only - older rows with no network label are disclosed, not counted. It is not an independent third party: the link on each card lets you call it yourself and see the raw response.', 'Las cifras de Audit Trail y Payouts vienen de la API pública de reportería de Nirium, filtradas a filas etiquetadas mainnet - las filas antiguas sin etiqueta de red se revelan, no se cuentan. No es un tercero independiente: el link de cada tarjeta te deja llamarla tú mismo y ver la respuesta cruda.')}
  • +
  • {lang('Audit Trail figures come from Nirium\u2019s own public reporting API, filtered to mainnet-labeled rows only - older rows with no network label are disclosed, not counted. It is not an independent third party: the link on each card lets you call it yourself and see the raw response.', 'Las cifras de Audit Trail vienen de la API pública de reportería de Nirium, filtradas a filas etiquetadas mainnet - las filas antiguas sin etiqueta de red se revelan, no se cuentan. No es un tercero independiente: el link de cada tarjeta te deja llamarla tú mismo y ver la respuesta cruda.')}
  • {lang('This page is server-rendered, so the numbers are already in the HTML a crawler sees - not behind a client-only fetch. Once a day, a snapshot of this exact data is committed, hashed and published at ', 'Esta página se renderiza en el servidor, así que los números ya están en el HTML que ve un crawler - no detrás de un fetch solo del cliente. Una vez al día se comitea, hashea y publica un snapshot de estos mismos datos en ')} /stats/history.json diff --git a/apps/web/app/(app)/treasury/builder/CustomNode.tsx b/apps/web/app/(app)/treasury/builder/CustomNode.tsx deleted file mode 100644 index 5fcc84af..00000000 --- a/apps/web/app/(app)/treasury/builder/CustomNode.tsx +++ /dev/null @@ -1,90 +0,0 @@ -'use client'; - -import React, { memo } from 'react'; -import { Handle, Position, NodeProps } from '@xyflow/react'; -import { useLanguage } from "@/context/LanguageContext"; -import { - LucideIcon, Plus, Play, Save, Box, Activity, Zap, ArrowRight, Trash2, - Settings, Search, ZoomIn, ZoomOut, Undo, Redo, - LayoutGrid, Cpu, History, Clock, Landmark, Coins, Shield, Database, - Twitter, MessageSquare, Bell, Share2, BarChart3, Fingerprint, Lock, Repeat, RefreshCw, - Layers, MousePointer2, Info, ChevronRight, Download, Bolt, KeyRound, TrendingUp, FlaskConical -} from 'lucide-react'; - -const ICON_MAP: any = { - Plus, Play, Save, Box, Activity, Zap, ArrowRight, Trash2, - Settings, Search, ZoomIn, ZoomOut, Undo, Redo, - LayoutGrid, Cpu, History, Clock, Landmark, Coins, Shield, Database, - Twitter, MessageSquare, Bell, Share2, BarChart3, Fingerprint, Lock, Repeat, RefreshCw, - Layers, MousePointer2, Info, ChevronRight, Download, - Bolt, KeyRound, TrendingUp, FlaskConical -}; - -const CustomNode = ({ data, selected }: NodeProps) => { - const { t } = useLanguage(); - const Icon = typeof data.icon === 'string' ? ICON_MAP[data.icon] || Box : (data.icon as LucideIcon || Box); - const gradColor = (data.color as string) || 'from-gray-500 to-gray-700'; - - // Try to find localized label/desc based on node ID (key) - const nodeKey = String(data.label).toLowerCase(); - const localizedData = t.treasury.nodes[nodeKey as keyof typeof t.treasury.nodes] || { label: data.label, desc: data.desc }; - - return ( -
    -
    - - - -
    -
    -
    - -
    -
    -

    - {localizedData.label} -

    -
    -
    - - {data.type as string} - -
    - {!!localizedData.desc && ( -

    - {localizedData.desc} -

    - )} -
    -
    -
    -
    - - - - {selected && ( -
    - )} -
    - ); -}; - -export default memo(CustomNode); diff --git a/apps/web/app/(app)/treasury/builder/layout.tsx b/apps/web/app/(app)/treasury/builder/layout.tsx index 9031cbb7..1d4def89 100644 --- a/apps/web/app/(app)/treasury/builder/layout.tsx +++ b/apps/web/app/(app)/treasury/builder/layout.tsx @@ -2,8 +2,8 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/treasury/builder", - title: "Treasury Strategy Builder (preview)", - description: "A preview canvas to compose a treasury strategy. Execution runs in the Treasury node.", + title: "Treasury (discontinued)", + description: "Treasury was tested only with the team's own funds and discontinued on 30 Nov 2026.", }); export default function TreasuryBuilderLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/treasury/builder/page.tsx b/apps/web/app/(app)/treasury/builder/page.tsx index c68a77ab..a3aac88a 100644 --- a/apps/web/app/(app)/treasury/builder/page.tsx +++ b/apps/web/app/(app)/treasury/builder/page.tsx @@ -1,884 +1,6 @@ -'use client'; +import { redirect } from "next/navigation"; -import React, { useState, useCallback, useRef, useEffect } from 'react'; -import { - ReactFlow, - MiniMap, - Controls, - Background, - useNodesState, - useEdgesState, - addEdge, - Panel, - Connection, - Edge, - ReactFlowProvider, - Node, - BackgroundVariant, -} from '@xyflow/react'; -import '@xyflow/react/dist/style.css'; - -import Link from "next/link"; -import { SectionBrandLogo } from "@/components/ui/SectionBrandLogo"; -import { useLanguage } from "@/context/LanguageContext"; -import { useNetwork } from "@/context/NetworkContext"; -import { - Plus, Play, Save, Box, Activity, Zap, ArrowRight, Trash2, - Settings, Search, ZoomIn, ZoomOut, Undo, Redo, - LayoutGrid, Cpu, History, Clock, Landmark, Coins, Shield, Database, - Twitter, MessageSquare, Bell, Share2, BarChart3, Fingerprint, Lock, Repeat, RefreshCw, - Layers, MousePointer2, Info, ChevronRight, Download, Upload, X, Menu, Bolt, - FlaskConical, KeyRound, TrendingUp, Terminal, Mail, Send, Smartphone, ArrowLeftRight, CheckSquare -} from "lucide-react"; -import { motion, AnimatePresence } from 'framer-motion'; -import { useFreighter } from "@/hooks/useFreighter"; -import { useRouter } from 'next/navigation'; -import { toast } from 'sonner'; - -import CustomNode from './CustomNode'; - -const nodeTypes: any = { niriumNode: CustomNode }; - -const ICON_MAP: any = { - Plus, Play, Save, Box, Activity, Zap, ArrowRight, Trash2, - Settings, Search, ZoomIn, ZoomOut, Undo, Redo, - LayoutGrid, Cpu, History, Clock, Landmark, Coins, Shield, Database, - Twitter, MessageSquare, Bell, Share2, BarChart3, Fingerprint, Lock, Repeat, RefreshCw, - Layers, MousePointer2, Info, ChevronRight, Download, Bolt, FlaskConical, KeyRound, TrendingUp, - Mail, Send, Smartphone, ArrowLeftRight, CheckSquare -}; - -const initialNodes: Node[] = [ - { - id: 'start-0', - type: 'niriumNode', - data: { label: 'START', icon: 'Play', type: 'trigger', color: 'from-stellar-teal to-blue-500' }, - position: { x: 100, y: 100 }, - }, -]; - -const initialEdges: Edge[] = []; - -let id = 0; -const getId = () => `node_${Date.now()}_${id++}`; - -function StrategyBuilderInner() { - const { t, language } = useLanguage(); - const { network } = useNetwork(); - const reactFlowWrapper = useRef(null); - const [nodes, setNodes, onNodesChange] = useNodesState(initialNodes); - const [edges, setEdges, onEdgesChange] = useEdgesState(initialEdges); - const [reactFlowInstance, setReactFlowInstance] = useState(null); - const [strategyName, setStrategyName] = useState(t.treasury.header.title); - const [strategyId, setStrategyId] = useState(null); - const [isSaving, setIsSaving] = useState(false); - const [searchQuery, setSearchQuery] = useState(''); - const [mounted, setMounted] = useState(false); - const [showHistory, setShowHistory] = useState(false); - const [history, setHistory] = useState([]); - const [isLoadingHistory, setIsLoadingHistory] = useState(false); - const [sidebarOpen, setSidebarOpen] = useState(true); - const [selectedAsset, setSelectedAsset] = useState<'USDC' | 'CETES'>('USDC'); - const [draggedTemplate, setDraggedTemplate] = useState(null); - const [dropHint, setDropHint] = useState<{ x: number, y: number, label: string, desc: string, targetNode?: string, position?: 'before' | 'after' } | null>(null); - - const { address: accountStr, isConnected } = useFreighter(); - const account = isConnected ? { address: accountStr, chains: ['stellar:testnet'] } : null; - const router = useRouter(); - - // PALETA RECONSTRUIDA SOBRE LO QUE CORRE (7-ago-2026). - // - // Se retiraron cinco bloques, y cuatro no por estar sin construir sino - // porque contradecían la posición legal que el sitio publica: - // - // SPEI_DEPOSIT - Nirium no toca fiat, nunca. Es restricción dura. - // KYC_VERIFY - no somos Sujeto Obligado y no hacemos KYC. Ofrecerlo - // es declararse ejecutor de una función regulada. - // OFAC_SCREENING - la política dice, con todas sus letras, que solo se - // screenean las direcciones operativas propias y NUNCA - // usuarios finales, "porque esto no es una institución - // financiera y no debe actuar como una". - // SOROSWAP_HEDGE / DEX_SWAP - los swaps se retiraron del nodo de tesorería - // el 6-ago por la fracc. XVI de la LFPIORPI. Seguir - // ofreciéndolos en el lienzo reintroduce el verbo. - // - // Ponerlos tras el plan de $299 sería peor, no mejor: pasaría de anunciar - // una función regulada a cobrarla. - // - // Lo que queda es el flujo real de DeFindex, que además es mejor demo. - const NODE_TEMPLATES = [ - { - category: t.treasury.sidebar.categories.bank, - color: 'from-blue-400 to-cyan-500', - items: [ - { type: 'trigger', label: 'X402_SETTLEMENT', icon: 'Coins' }, - { type: 'trigger', label: 'MPP_CHARGE', icon: 'RefreshCw' }, - ] - }, - { - category: t.treasury.sidebar.categories.triggers, - color: 'from-stellar-teal to-blue-500', - items: [ - { type: 'trigger', label: 'RATE_THRESHOLD', icon: 'Activity' }, - { type: 'trigger', label: 'IDLE_MINIMUM', icon: 'Database' }, - { type: 'trigger', label: 'SCHEDULE', icon: 'Clock' }, - { type: 'trigger', label: 'BALANCE_CHECK', icon: 'LayoutGrid' }, - ] - }, - { - category: t.treasury.sidebar.categories.actions, - color: 'from-emerald-400 to-green-600', - items: [ - { type: 'action', label: 'VAULT_DEPLOY', icon: 'Box' }, - { type: 'action', label: 'VAULT_DEPOSIT', icon: 'TrendingUp' }, - { type: 'action', label: 'INVEST', icon: 'Zap' }, - { type: 'action', label: 'UNWIND', icon: 'History' }, - { type: 'action', label: 'MPP_FUNDING', icon: 'Send' }, - ] - }, - { - category: t.treasury.sidebar.categories.safety, - color: 'from-purple-500 to-indigo-600', - items: [ - { type: 'condition', label: 'CLIENT_SIGNATURE', icon: 'Shield' }, - { type: 'action', label: 'ONCHAIN_AUDIT', icon: 'Fingerprint' }, - ] - }, - { - category: t.treasury.sidebar.categories.alerts, - color: 'from-orange-400 to-rose-500', - items: [ - { type: 'action', label: 'TELEGRAM_ALERTS', icon: 'Send' }, - { type: 'action', label: 'EMAIL_REPORT', icon: 'Mail' }, - ] - }, - ]; - - useEffect(() => { setMounted(true); }, []); - - useEffect(() => { - const handleResize = () => { - if (window.innerWidth < 1024) setSidebarOpen(false); - }; - handleResize(); - window.addEventListener('resize', handleResize); - return () => window.removeEventListener('resize', handleResize); - }, []); - - const onConnect = useCallback( - (params: Connection) => setEdges((eds) => addEdge({ ...params, animated: true, style: { stroke: '#2DEBE8' } }, eds)), - [setEdges] - ); - - const onDragStart = (event: React.DragEvent, nodeData: any) => { - setDraggedTemplate(nodeData); - event.dataTransfer.setData('application/reactflow', JSON.stringify(nodeData)); - event.dataTransfer.effectAllowed = 'move'; - - // Custom drag ghost - const ghost = document.createElement('div'); - ghost.style.opacity = '0'; - document.body.appendChild(ghost); - event.dataTransfer.setDragImage(ghost, 0, 0); - setTimeout(() => document.body.removeChild(ghost), 0); - }; - - const onDragOver = useCallback((event: React.DragEvent) => { - event.preventDefault(); - event.dataTransfer.dropEffect = 'move'; - - if (!draggedTemplate || !reactFlowInstance) return; - - const bounds = reactFlowWrapper.current?.getBoundingClientRect(); - if (!bounds) return; - - const position = reactFlowInstance.screenToFlowPosition({ - x: event.clientX, - y: event.clientY, - }); - - // Find nearest node - let nearestNode: Node | null = null; - let minDistance = 150; - - nodes.forEach(node => { - const dx = node.position.x - position.x; - const dy = node.position.y - position.y; - const distance = Math.sqrt(dx * dx + dy * dy); - if (distance < minDistance) { - minDistance = distance; - nearestNode = node; - } - }); - - if (nearestNode) { - const isBefore = position.x < (nearestNode as Node).position.x; - const locNode = t.treasury.nodes[draggedTemplate.label.toLowerCase() as keyof typeof t.treasury.nodes] || { label: draggedTemplate.label, desc: '' }; - - setDropHint({ - x: event.clientX, - y: event.clientY, - label: locNode.label, - desc: locNode.desc, - targetNode: (nearestNode as Node).data.label as string, - position: isBefore ? 'before' : 'after' - }); - } else { - const locNode = t.treasury.nodes[draggedTemplate.label.toLowerCase() as keyof typeof t.treasury.nodes] || { label: draggedTemplate.label, desc: '' }; - setDropHint({ - x: event.clientX, - y: event.clientY, - label: locNode.label, - desc: locNode.desc - }); - } - }, [draggedTemplate, reactFlowInstance, nodes, t.treasury.nodes]); - - const onAddNode = useCallback((template: any) => { - let position = { x: 300, y: 300 }; - if (reactFlowInstance) { - const { x, y, zoom } = reactFlowInstance.getViewport(); - const wrapper = reactFlowWrapper.current?.getBoundingClientRect(); - if (wrapper) { - position = { - x: (wrapper.width / 2 - x) / zoom, - y: (wrapper.height / 2 - y) / zoom, - }; - } - } - const newId = getId(); - const newNode: Node = { - id: newId, - type: 'niriumNode', - position, - data: { - label: template.label, - icon: template.icon, - type: template.type, - color: NODE_TEMPLATES.find(c => c.items.some(i => i.label === template.label))?.color - }, - }; - setNodes((nds) => { - const lastNode = nds[nds.length - 1]; - if (lastNode) { - setEdges((eds) => { - const edgeId = `edge_${lastNode.id}_to_${newId}`; - if (eds.some((e) => e.id === edgeId)) return eds; - return [ - ...eds, - { - id: edgeId, - source: lastNode.id, - target: newId, - animated: true, - style: { stroke: '#2DEBE8' } - } - ]; - }); - } - return [...nds, newNode]; - }); - toast.success(`${template.label}`); - }, [reactFlowInstance, setNodes, setEdges]); - - const onDrop = useCallback( - (event: React.DragEvent) => { - event.preventDefault(); - setDraggedTemplate(null); - setDropHint(null); - - const reactFlowBounds = reactFlowWrapper.current?.getBoundingClientRect(); - const rawData = event.dataTransfer.getData('application/reactflow'); - if (!rawData || !reactFlowBounds) return; - const template = JSON.parse(rawData); - const position = reactFlowInstance.screenToFlowPosition({ - x: event.clientX, - y: event.clientY, - }); - - // Find nearest node for connection logic - let nearestDropNode: Node | null = null; - let minDistance = 150; - nodes.forEach(node => { - const dx = node.position.x - position.x; - const dy = node.position.y - position.y; - const distance = Math.sqrt(dx * dx + dy * dy); - if (distance < minDistance) { - minDistance = distance; - nearestDropNode = node; - } - }); - - const newId = getId(); - const newNode: Node = { - id: newId, - type: 'niriumNode', - position, - data: { - label: template.label, - icon: template.icon, - type: template.type, - color: NODE_TEMPLATES.find(c => c.items.some(i => i.label === template.label))?.color - }, - }; - setNodes((nds) => { - const lastNode = nearestDropNode || nds[nds.length - 1]; - if (lastNode) { - setEdges((eds) => { - const edgeId = `edge_${lastNode.id}_to_${newId}`; - if (eds.some((e) => e.id === edgeId)) return eds; - return [ - ...eds, - { - id: edgeId, - source: lastNode.id, - target: newId, - animated: true, - style: { stroke: '#2DEBE8' } - } - ]; - }); - } - return [...nds, newNode]; - }); - }, - [reactFlowInstance, setNodes, setEdges, nodes] - ); - - // ─── Borradores: solo en este navegador (8-nov-2026) ─────────────────── - // Antes se escribían también en la tabla nirium_protocol_records, cuya política - // es "Allow all for anon": cualquiera con la llave pública (va en el sitio) podía - // leer, cambiar o borrar los borradores de cualquier wallet. Nada ejecuta estos - // diagramas, así que no hace falta una tabla: se guardan aquí y se respaldan con - // Exportar / Importar. No pide wallet: el dibujo vive en el navegador de quien lo hizo. - const DRAFTS_KEY = 'nirium-builder-drafts'; - const readDrafts = (): any[] => { - try { - const own = JSON.parse(localStorage.getItem(DRAFTS_KEY) || '[]'); - // Borradores viejos guardados por wallet: se siguen mostrando para no perderlos. - const legacy = account?.address - ? JSON.parse(localStorage.getItem(`nirium-fleet-${account.address}`) || '[]') - .filter((d: any) => d?.config?.nodes) - : []; - const seen = new Set(); - return [...(Array.isArray(own) ? own : []), ...legacy].filter((d: any) => { - const k = d?.id || d?.strategy_id; - if (!k || seen.has(k)) return false; - seen.add(k); - return true; - }); - } catch { return []; } - }; - - const handleSave = async () => { - setIsSaving(true); - try { - const flow = reactFlowInstance.toObject(); - const sid = strategyId || `custom-${Date.now()}`; - if (!strategyId) setStrategyId(sid); - const draft = { - id: sid, - strategy_id: sid, - name: strategyName, - emoji: '🏗️', - status: 'DRAFT', - rate: '-', - asset: selectedAsset, - created_at: new Date().toISOString(), - config: flow, - }; - const own = JSON.parse(localStorage.getItem(DRAFTS_KEY) || '[]'); - const rest = (Array.isArray(own) ? own : []).filter((d: any) => d.id !== sid); - localStorage.setItem(DRAFTS_KEY, JSON.stringify([draft, ...rest].slice(0, 50))); - toast.success(language === 'es' - ? 'Guardado en este navegador. Usa Exportar para tener una copia.' - : 'Saved in this browser. Use Export to keep a copy.'); - fetchHistory(); - } catch { - toast.error(t.toasts.broadcast_failed); - } finally { - setIsSaving(false); - } - }; - - const fetchHistory = async () => { - setIsLoadingHistory(true); - setHistory(readDrafts()); - setIsLoadingHistory(false); - }; - - const handleExport = () => { - if (!reactFlowInstance) return; - const flow = reactFlowInstance.toObject(); - const schema = { - version: '0.0.7', - exported_at: new Date().toISOString(), - kernel_name: strategyName, - kernel_id: strategyId || `custom-${Date.now()}`, - asset: selectedAsset, - node_count: flow.nodes?.length || 0, - edge_count: flow.edges?.length || 0, - flow, - }; - const blob = new Blob([JSON.stringify(schema, null, 2)], { type: 'application/json' }); - const url = URL.createObjectURL(blob); - const a = document.createElement('a'); - a.href = url; - a.download = `${strategyName.toLowerCase().replace(/\s+/g, '_')}_kernel.json`; - document.body.appendChild(a); - a.click(); - URL.revokeObjectURL(url); - document.body.removeChild(a); - toast.success(t.marketplace.custom_builder.export); - }; - - // Lee un archivo hecho con Exportar. Solo acepta la forma que Exportar produce; - // cualquier otra cosa se rechaza con un mensaje, no se intenta adivinar. - const importInputRef = useRef(null); - const handleImport = async (file: File) => { - try { - const schema = JSON.parse(await file.text()); - const flow = schema?.flow; - if (!flow || !Array.isArray(flow.nodes) || !Array.isArray(flow.edges)) throw new Error('shape'); - setNodes(flow.nodes); - setEdges(flow.edges); - if (typeof schema.kernel_name === 'string') setStrategyName(schema.kernel_name); - if (typeof schema.kernel_id === 'string') setStrategyId(schema.kernel_id); - if (schema.asset === 'USDC' || schema.asset === 'CETES') setSelectedAsset(schema.asset); - setTimeout(() => { reactFlowInstance?.fitView({ duration: 800 }); }, 100); - toast.success(language === 'es' ? 'Esquema importado.' : 'Schema imported.'); - } catch { - toast.error(language === 'es' - ? 'Ese archivo no es un esquema exportado desde aquí.' - : 'That file is not a schema exported from here.'); - } - }; - - // "Publicar" se quitó el 8-nov-2026: subía el diagrama por /api/pinata (abierto, - // sin login ni límite) y lo listaba en un mercado de estrategias de testnet con - // suscripción de 1 USDC. El contrato tenía 0 estrategias publicadas, y vender - // estrategias por suscripción roza la asesoría de inversión que la política dice - // que no damos. - - const loadKernel = (strat: any) => { - if (strat.config && strat.config.nodes) { - setNodes(strat.config.nodes || []); - setEdges(strat.config.edges || []); - setStrategyName(strat.name); - setStrategyId(strat.strategy_id || strat.id); - if (strat.asset === 'USDC' || strat.asset === 'CETES') setSelectedAsset(strat.asset); - setShowHistory(false); - toast.success(strat.name); - setTimeout(() => { reactFlowInstance?.fitView({ duration: 800 }); }, 100); - } - }; - - if (!mounted) return null; - - const filteredTemplates = NODE_TEMPLATES.map(cat => ({ - ...cat, - items: cat.items.filter(i => { - const loc = t.treasury.nodes[i.label.toLowerCase() as keyof typeof t.treasury.nodes] || { label: i.label }; - return loc.label.toLowerCase().includes(searchQuery.toLowerCase()); - }) - })).filter(cat => cat.items.length > 0); - - return ( -
    - - {sidebarOpen && ( - setSidebarOpen(false)} - className="fixed inset-0 bg-black/60 z-[55] lg:hidden backdrop-blur-sm" - /> - )} - - - - {!sidebarOpen && ( - setSidebarOpen(true)} - className="lg:hidden absolute top-6 left-4 sm:left-6 z-50 bg-[#121212]/90 backdrop-blur-xl border border-white/10 p-3 sm:p-4 rounded-xl sm:rounded-2xl text-stellar-teal hover:border-stellar-teal/50 shadow-[0_0_20px_rgba(45,235,232,0.2)] transition-all" - > - - - )} - - - - -
    - - - - - -
    -
    - -
    -
    -
    - - {/* Nada lee este diagrama: el agente decide con los umbrales de la bóveda - (REBALANCE_VAULTS / rebalanceDecision.ts), no con lo que se dibuja aquí. */} - {language === "es" ? "VISTA PREVIA · NO SE EJECUTA: EL AGENTE USA LOS UMBRALES DE TU BÓVEDA" : "PREVIEW · NOT EXECUTED: THE AGENT USES YOUR VAULT'S THRESHOLDS"} -
    - setStrategyName(e.target.value)} - className="bg-transparent border-none focus:outline-none font-black text-sm sm:text-xl tracking-tighter text-white uppercase font-mono italic w-full truncate" - /> - {/* 8-nov-2026: se quitaron "OPERATIVO" (con punto pulsante) y "Ética - alineada". El lienzo no corre nada; eran decorado con forma de estado. */} -
    -
    -
    - - {/* Apilado hasta 2xl: en pantallas medianas (sidebar del sitio - + paleta del builder abiertos) los tres botones en fila no - caben junto a la tarjeta del esquema y el último se corta. */} - - - {/* "EJECUTAR" (8-nov-2026) no ejecutaba nada y "PUBLICAR" se quitó: - ver el comentario junto a handleImport. */} - - - - - { const f = e.target.files?.[0]; if (f) handleImport(f); e.target.value = ''; }} - /> - - - -
    - - - {dropHint && ( - -
    -
    -
    -
    - -
    -
    -
    {t.treasury.controls?.creating}
    -
    {dropHint.label}
    -
    -
    - -

    - "{dropHint.desc}" -

    - - {dropHint.targetNode ? ( -
    -
    -
    - - {t.treasury.controls?.logic_mapping} - -
    -
    -
    - {dropHint.position === 'before' ? ( - <>{t.treasury.controls?.place_before.replace('{node}', '')} BEFORE node {dropHint.targetNode} - ) : ( - <>{t.treasury.controls?.place_after.replace('{node}', '')} AFTER node {dropHint.targetNode} - )} -
    -
    - {dropHint.position === 'before' ? - t.treasury.controls?.pre_executes : - t.treasury.controls?.awaiting_output} -
    -
    -
    - ) : ( -
    -
    - {t.treasury.controls?.drop_hint} -
    - )} -
    - - )} - -
    - - - {showHistory && ( - <> - setShowHistory(false)} - className="fixed inset-0 bg-black/80 backdrop-blur-md z-[100]" - /> - -
    -

    {t.treasury.history.title}

    - -
    -
    - {isLoadingHistory ? ( -
    -
    -

    {t.treasury.history.loading}

    -
    - ) : history.length === 0 ? ( -
    -

    {t.treasury.history.empty}

    -
    - ) : history.map((strat, i) => ( - - ))} -
    - - - )} - -
    - ); -} - -export default function StrategyBuilderPro() { - const { t } = useLanguage(); - - return ( - // w-full, no w-screen: la página vive dentro de AppLayout, que ya resta - // el sidebar de 256px; 100vw empujaba los botones de la derecha fuera - // de la pantalla. La altura deja aire para el TestnetBanner (no es - // fixed) y para la barra superior en móvil, así la tarjeta de abajo y - // los controles de zoom no quedan cortados. - // 9-nov-2026: AppLayout ya baja la barra de mercado (pt-9) y el body baja el - // aviso de red, así que el espaciador h-9 de aquí sobraba y dejaba un hueco. - // La altura resta barra (2.25rem), aviso (--banner-h) y, en móvil, la barra - // superior del layout (3.75rem). -
    - - {/* Preview banner - mainnet is invite-only, not unlocked by a plan */} -
    -
    - - - {t.strategy_builder.upgrade_banner.preview} - -
    - - {t.strategy_builder.upgrade_banner.upgrade} - - -
    - -
    - - - - - {/* Bottom fade + upgrade card - blocks "run in production" affordance */} -
    -
    -
    - - - {t.strategy_builder.deploy_gate.title} - - - {t.strategy_builder.deploy_gate.plan} - - -
    -
    -
    -
    - ); +// Archivado el 30-nov-2026 (decidido por Giovanny): el Strategy Builder de Tesorería. Redirige a /treasury, la página de archivo. +export default function Page() { + redirect("/treasury"); } diff --git a/apps/web/app/(app)/treasury/layout.tsx b/apps/web/app/(app)/treasury/layout.tsx index 6782da21..bf9e23e2 100644 --- a/apps/web/app/(app)/treasury/layout.tsx +++ b/apps/web/app/(app)/treasury/layout.tsx @@ -2,8 +2,8 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/treasury", - title: "Treasury Node", - description: "Moves your own DeFindex vault's idle funds (USDC or CETES) into its Blend strategy and back when the yield crosses the thresholds you set. On mainnet, invite-only.", + title: "Treasury and Payouts (discontinued)", + description: "Treasury and Payouts were tested only with the team's own funds and discontinued on 30 Nov 2026.", }); export default function TreasuryLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/treasury/page.tsx b/apps/web/app/(app)/treasury/page.tsx index e5595f52..19a6575b 100644 --- a/apps/web/app/(app)/treasury/page.tsx +++ b/apps/web/app/(app)/treasury/page.tsx @@ -1,331 +1,32 @@ -/** Nirium Treasury - página del nodo de tesorería. - * 8-nov-2026: "Cómo funciona" describe el rebalanceador real (rendimiento medido - * on-chain contra los umbrales del dueño, firma del agente dentro de la bóveda). - * Se quitó la sección cross-border (Treasury no mueve dinero entre países) y la - * tasa fija de CETES (el agente no la usa). **/ +/** /treasury - 30-nov-2026 (decidido por Giovanny): Tesorería y Payouts se descontinuaron. + * Solo se probaron con fondos del equipo (Payouts nunca corrió en mainnet), así que esta + * página no habla de "tu bóveda" ni de retiros: lo dice una vez y manda a lo que sí existe. + * /treasury/vault sigue accesible por URL para cerrar las bóvedas de prueba, sin links. **/ 'use client'; import Link from "next/link"; -import { - Bot, TrendingUp, Coins, ArrowRight, ChevronRight, - Sparkles, Activity, Zap, BarChart3, RefreshCw, AlertTriangle, - CheckCircle2 -} from "lucide-react"; -import { Button } from "@/components/ui/Button"; +import { ArrowRight } from "lucide-react"; import { useLanguage } from "@/context/LanguageContext"; -import { ComplianceBanner } from "@/components/ui/ComplianceBanner"; -import TreasuryPlainTerms from "@/components/home/TreasuryPlainTerms"; -export default function TreasuryPage() { - const { t, language } = useLanguage(); +export default function TreasuryDiscontinuedPage() { + const { language } = useLanguage(); const lang = (en: string, es: string) => (language === "es" ? es : en); return (
    - {/* HERO */} -
    -
    -
    -
    -
    - - {t.treasury_page.hero.badge} -
    -
    - - {t.treasury_page.hero.invite_badge} -
    -
    - -

    - {t.treasury_page.hero.title} -

    -

    - {t.treasury_page.hero.subtitle} -

    -

    - {t.treasury_page.hero.invite_note}{" "} - - {t.treasury_page.hero.request_access} - -

    -
    -
    - -
    - +
    +

    + {lang("Treasury and Payouts were discontinued", "Tesorería y Payouts se descontinuaron")} +

    +

    + {lang( + "They were tested only with the team's own funds and were discontinued on 30 Nov 2026, so Nirium can focus on receipts that tie a payment to the document behind it.", + "Solo se probaron con fondos del propio equipo y se descontinuaron el 30-nov-2026, para que Nirium se enfoque en recibos que ligan un pago con el documento que lo respalda.")} +

    + + {lang("Verify a receipt", "Verifica un recibo")} +
    - - {/* HOW THE AGENT WORKS */} -
    -
    -

    - {t.treasury_page.how_it_works.title} -

    - -
    - {[ - { - step: '01', - icon: BarChart3, - title: t.treasury_page.how_it_works.step1.title, - body: t.treasury_page.how_it_works.step1.body, - }, - { - step: '02', - icon: Bot, - title: t.treasury_page.how_it_works.step2.title, - body: t.treasury_page.how_it_works.step2.body, - }, - { - step: '03', - icon: RefreshCw, - title: t.treasury_page.how_it_works.step3.title, - body: t.treasury_page.how_it_works.step3.body, - }, - { - step: '04', - icon: Zap, - title: t.treasury_page.how_it_works.step4.title, - body: t.treasury_page.how_it_works.step4.body, - }, - { - step: '05', - icon: Activity, - title: t.treasury_page.how_it_works.step5.title, - body: t.treasury_page.how_it_works.step5.body, - }, - ].map((item) => ( -
    -
    -
    - -
    -
    -
    -
    - {item.step} -

    {item.title}

    -
    -

    {item.body}

    -
    -
    - ))} -
    -
    -
    - - {/* SUPPORTED ASSETS */} -
    -
    -

    - {t.treasury_page.assets.title} -

    -

    - {t.treasury_page.assets.coming_soon} -

    - -
    - {/* USDC */} -
    -
    -
    -
    - -
    -
    -
    USDC
    -
    {t.treasury_page.assets.usdc.desc}
    -
    -
    -
    - {t.treasury_page.assets.usdc.status} -
    -
    -
    -
    - {t.treasury_page.assets.usdc.yield_label} - {lang("Variable, measured by the vault", "Variable, la mide la bóveda")} -
    -
    - {t.treasury_page.assets.usdc.liquidity_label} - {t.treasury_page.assets.usdc.liquidity_value} -
    -
    - {t.treasury_page.assets.usdc.risk_label} - {t.treasury_page.assets.usdc.risk_value} -
    -
    -
    - - {/* Global Bonds */} -
    -
    -
    -
    - -
    -
    -
    {t.treasury_page.assets.bonds.title}
    -
    {t.treasury_page.assets.bonds.desc}
    -
    -
    -
    - {lang("Variable", "Variable")} -
    -
    -
    -
    - {t.treasury_page.assets.bonds.yield_label} - {lang("Variable, measured by the vault", "Variable, la mide la bóveda")} -
    -
    - {t.treasury_page.assets.bonds.liquidity_label} - {t.treasury_page.assets.bonds.liquidity_value} -
    -
    - {t.treasury_page.assets.bonds.rating_label} - {t.treasury_page.assets.bonds.rating_value} -
    -
    -
    -
    - -
    -
    - - {/* HUMAN VS AGENT PATHS */} -
    -
    -

    - {t.treasury_page.paths.title} -

    - -
    -
    -
    - {t.treasury_page.paths.path1.label} -
    -

    {t.treasury_page.paths.path1.title}

    -

    - {t.treasury_page.paths.path1.desc} -

    -
    -
    - - {t.treasury_page.paths.path1.item1} -
    -
    - - {t.treasury_page.paths.path1.item2} -
    -
    - - {t.treasury_page.paths.path1.item3} -
    -
    -
    - -
    -
    - {t.treasury_page.paths.path2.label} -
    -

    {t.treasury_page.paths.path2.title}

    -

    - {t.treasury_page.paths.path2.desc} -

    -
    -
    - - {t.treasury_page.paths.path2.item1} -
    -
    - - {t.treasury_page.paths.path2.item2} -
    -
    - - {t.treasury_page.paths.path2.item3} -
    -
    -
    -
    -
    -
    - - {/* DEEP LINKS */} -
    -
    -

    - {t.treasury_page.links.title} -

    -
    - {[ - { - label: 'Strategy Builder', - desc: t.treasury_page.links.builder, - href: '/treasury/builder', - }, - { - label: lang('Security', 'Seguridad'), - desc: t.treasury_page.links.security, - href: '/security', - }, - { - label: 'Audit Trail', - desc: t.treasury_page.links.compliance, - href: '/compliance', - }, - ].map((link) => ( - -
    {link.label}
    -
    {link.desc}
    -
    - {t.treasury_page.links.view} - -
    - - ))} -
    -
    -
    - - {/* CTA */} - - -
    -
    -

    - {t.treasury_page.cta.title} -

    -

    - {t.treasury_page.cta.subtitle} -

    -
    - - - - - - -
    -
    -
    ); } diff --git a/apps/web/app/(app)/treasury/vault/layout.tsx b/apps/web/app/(app)/treasury/vault/layout.tsx index 64251651..c4a36cee 100644 --- a/apps/web/app/(app)/treasury/vault/layout.tsx +++ b/apps/web/app/(app)/treasury/vault/layout.tsx @@ -2,8 +2,8 @@ import { pageMetadata } from "@/lib/pageMetadata"; export const metadata = pageMetadata({ path: "/treasury/vault", - title: "Treasury Vault Console", - description: "Deploy a DeFindex vault you own. Nirium only takes the RebalanceManager role: it moves funds between strategies inside your vault and nothing else.", + title: "Treasury (discontinued)", + description: "Treasury was tested only with the team's own funds and discontinued on 30 Nov 2026.", }); export default function TreasuryVaultLayout({ children }: { children: React.ReactNode }) { diff --git a/apps/web/app/(app)/treasury/vault/page.tsx b/apps/web/app/(app)/treasury/vault/page.tsx index c1f5378b..46359639 100644 --- a/apps/web/app/(app)/treasury/vault/page.tsx +++ b/apps/web/app/(app)/treasury/vault/page.tsx @@ -148,10 +148,13 @@ export default function TreasuryVaultConsole() { const [acknowledged, setAcknowledged] = useState(false); // En mainnet el dueño decide a quién nombra encargado; el nodo no lo // rellena. No es que no podamos -el firmante existe y corre- es que el - // rebalanceo autónomo con dinero de terceros es invite-only mientras cierra - // la revisión legal, y rellenar el campo prometería un servicio que hoy no + // rebalanceo autónomo con dinero de terceros es invite-only mientras no haya + // una opinión legal por escrito, y rellenar el campo prometería un servicio que hoy no // se presta. const nodeFillsRole = network !== 'mainnet'; + // 30-nov-2026 (decidido por Giovanny): Tesorería archivada. En todas las redes + // esta página solo sirve para salir: revisar, retirar y quitarle el rol a Nirium. + const exitOnly = true; // Bóvedas desplegadas desde ESTE navegador. No es un índice on-chain: el // factory no permite listar por manager sin recorrer las ~200 existentes. @@ -296,7 +299,7 @@ export default function TreasuryVaultConsole() { }; const deposit = async () => { - if (network === 'mainnet') { setError(lang('On mainnet, depositing from this page is invite-only until we have a written legal opinion.', 'En mainnet, depositar desde esta página es solo por invitación hasta tener una opinión legal por escrito.')); return; } + if (exitOnly) { setError(lang('Treasury is archived: depositing from this page is off. You can still check and withdraw.', 'Tesorería está archivada: depositar desde esta página está apagado. Todavía puedes revisar y retirar.')); return; } if (!vault?.vault) return; const stroops = toStroops(amount); if (!stroops) { setError(lang('Enter a positive amount.', 'Escribe un monto positivo.')); return; } @@ -387,7 +390,7 @@ export default function TreasuryVaultConsole() { }, [network]); const deploy = async () => { - if (network === 'mainnet') { setError(lang('On mainnet, deploying a vault from this page is invite-only until we have a written legal opinion.', 'En mainnet, desplegar una bóveda desde esta página es solo por invitación hasta tener una opinión legal por escrito.')); return; } + if (exitOnly) { setError(lang('Treasury is archived: deploying a vault from this page is off.', 'Tesorería está archivada: desplegar una bóveda desde esta página está apagado.')); return; } if (!isConnected || !address) { await connect(); return; } setError(null); setDeployed(null); try { @@ -560,14 +563,21 @@ export default function TreasuryVaultConsole() { }`}>{network}

    - {network === 'mainnet' + {exitOnly ? lang( - 'Check or withdraw from a DeFindex vault you own. On mainnet, deploying and depositing here are invite-only. Nirium takes only the RebalanceManager role - it can move funds between the strategies inside your vault, and nothing else.', - 'Revisa o retira de una bóveda de DeFindex que es tuya. En mainnet, desplegar y depositar aquí es solo por invitación. Nirium toma únicamente el rol de RebalanceManager: puede mover fondos entre las estrategias de tu bóveda, y nada más.') + 'Treasury was discontinued on 30 Nov 2026. This page only checks a vault and withdraws from it.', + 'Tesorería se descontinuó el 30-nov-2026. Esta página solo revisa una bóveda y retira de ella.') + : network === 'mainnet' + ? lang( + 'Check or withdraw from a DeFindex vault you own. On mainnet, deploying and depositing here are paused. Nirium takes only the RebalanceManager role - it can move funds between the strategies inside your vault, and nothing else.', + 'Revisa o retira de una bóveda de DeFindex que es tuya. En mainnet, desplegar y depositar aquí está en pausa. Nirium toma únicamente el rol de RebalanceManager: puede mover fondos entre las estrategias de tu bóveda, y nada más.') : lang( 'Deploy a DeFindex vault that you own. Nirium takes only the RebalanceManager role - it can move funds between the strategies inside your vault, and nothing else.', 'Despliega una bóveda de DeFindex que tú posees. Nirium toma únicamente el rol de RebalanceManager: puede mover fondos entre las estrategias de tu bóveda, y nada más.')}

    +

    + {lang('Discontinued', 'Descontinuada')} +

    {/* Lo que el rol NO puede hacer, servido por el propio nodo. */} @@ -603,18 +613,32 @@ export default function TreasuryVaultConsole() { )} {/* Desplegar. 16-nov-2026 (decidido por Giovanny): en mainnet, desplegar y - fondear desde este sitio es solo por invitación, igual que Payouts, hasta + fondear desde este sitio está en pausa, igual que Payouts, hasta tener una opinión legal por escrito. Retirar de una bóveda propia sigue abierto siempre (política de jurisdicciones). Testnet sin cambios. */} - {network === 'mainnet' ? ( + {exitOnly ? ( +
    +

    + {lang('Discontinued', 'Descontinuada')} +

    +

    + {lang( + 'Treasury was tested only with the team\'s own funds and discontinued on 30 Nov 2026.', + 'Tesorería solo se probó con fondos del propio equipo y se descontinuó el 30-nov-2026.')} +

    + + {lang('More →', 'Más →')} + +
    + ) : network === 'mainnet' ? (

    - {lang('Mainnet · invite-only', 'Mainnet · solo por invitación')} + {lang('Mainnet · paused', 'Mainnet · en pausa')}

    {lang( - 'On mainnet, deploying and funding a vault from this page is invite-only until we have a written legal opinion, the same as Payouts and autonomous rebalancing. On testnet everything stays open: switch to TEST in the menu to try it. If you already own a vault, you can always check it and withdraw below.', - 'En mainnet, desplegar y fondear una bóveda desde esta página es solo por invitación hasta tener una opinión legal por escrito, igual que Payouts y el rebalanceo autónomo. En testnet todo sigue abierto: cambia a TEST en el menú para probarlo. Si ya tienes una bóveda, siempre puedes revisarla y retirar abajo.')} + 'On mainnet, deploying and funding a vault from this page is paused until we have a written legal opinion, as are Payouts and autonomous rebalancing. On testnet everything stays open: switch to TEST in the menu to try it. If you already own a vault, you can always check it and withdraw below.', + 'En mainnet, desplegar y fondear una bóveda desde esta página está en pausa hasta tener una opinión legal por escrito, igual que Payouts y el rebalanceo autónomo. En testnet todo sigue abierto: cambia a TEST en el menú para probarlo. Si ya tienes una bóveda, siempre puedes revisarla y retirar abajo.')}

    {lang( - 'This vault is yours end to end: name an address you control as RebalanceManager. Nirium\u2019s autonomous rebalancing on mainnet is invite-only until we have a written legal opinion - when it opens, you hand the role over with set_rebalance_manager, and you can take it back the same way.', - 'Esta b\u00f3veda es tuya de punta a punta: pon una direcci\u00f3n tuya como RebalanceManager. El rebalanceo aut\u00f3nomo de Nirium en mainnet es solo por invitaci\u00f3n hasta tener una opini\u00f3n legal por escrito - cuando abra, le entregas el rol con set_rebalance_manager, y te lo puedes quedar de vuelta igual.')} + 'This vault is yours end to end: name an address you control as RebalanceManager. Nirium\u2019s autonomous rebalancing on mainnet is paused until we have a written legal opinion - when it opens, you hand the role over with set_rebalance_manager, and you can take it back the same way.', + 'Esta b\u00f3veda es tuya de punta a punta: pon una direcci\u00f3n tuya como RebalanceManager. El rebalanceo aut\u00f3nomo de Nirium en mainnet est\u00e1 en pausa hasta tener una opini\u00f3n legal por escrito - cuando abra, le entregas el rol con set_rebalance_manager, y te lo puedes quedar de vuelta igual.')} {" "}

    - {network === 'mainnet' ? lang('Check your vault or withdraw', 'Revisa tu bóveda o retira') : lang('2 · Verify, deposit and rebalance', '2 · Verifica, deposita y rebalancea')} + {exitOnly || network === 'mainnet' ? lang('Check your vault or withdraw', 'Revisa tu bóveda o retira') : lang('2 · Verify, deposit and rebalance', '2 · Verifica, deposita y rebalancea')}

    setLookup(e.target.value)} spellCheck={false} @@ -821,7 +845,20 @@ export default function TreasuryVaultConsole() { La misma puerta sirve para quitárnoslo: si el nodo pudiera nombrarse a sí mismo, "puedes botarnos" dejaría de ser cierto. */} - {info?.role?.address + {exitOnly && address + && vault.roles.manager === address + && vault.roles.rebalanceManager !== address && ( + + )} + {!exitOnly && info?.role?.address && vault.roles.manager === address && vault.roles.rebalanceManager !== info.role.address && (
    - {network === 'mainnet' && vault?.autonomousRebalancing !== 'not-managed-by-nirium' && ( + {!exitOnly && network === 'mainnet' && vault?.autonomousRebalancing !== 'not-managed-by-nirium' && (
    {vault?.autonomousRebalancing === 'enabled' ? lang( - 'Autonomous rebalancing is on for this vault. Nirium’s signer decides on its own every 10 minutes - there is no button here because if you could trigger it, it would not be autonomous.', - 'El rebalanceo autónomo está encendido para esta bóveda. El firmante de Nirium decide por su cuenta cada 10 minutos - aquí no hay botón porque si pudieras dispararlo tú, no sería autónomo.') + 'Autonomous rebalancing is on for this vault. Nirium’s signer decides on its own every 10 minutes - there is no button here because if you could trigger it, it would not be autonomous. The rebalancer has been paused on mainnet since 27 Nov 2026, so for now it makes no decisions.', + 'El rebalanceo autónomo está encendido para esta bóveda. El firmante de Nirium decide por su cuenta cada 10 minutos - aquí no hay botón porque si pudieras dispararlo tú, no sería autónomo. El rebalanceador está en pausa en mainnet desde el 27-nov-2026, así que por ahora no toma decisiones.') : <> {lang( - 'This vault names Nirium as rebalance manager, but autonomous rebalancing is not enabled for it - being named is not the same as being enabled. On mainnet it is invite-only until we have a written legal opinion, and enabling a vault takes a commit to the repository, with author and date.', - 'Esta bóveda nombra a Nirium como rebalance manager, pero el rebalanceo autónomo no está habilitado para ella - nombrarnos no es lo mismo que habilitarla. En mainnet es invite-only hasta tener una opinión legal por escrito, y habilitar una bóveda requiere un commit al repositorio, con autor y fecha.')} + 'This vault names Nirium as rebalance manager, but autonomous rebalancing is not enabled for it - being named is not the same as being enabled. On mainnet it is paused until we have a written legal opinion, and enabling a vault takes a commit to the repository, with author and date.', + 'Esta bóveda nombra a Nirium como rebalance manager, pero el rebalanceo autónomo no está habilitado para ella - nombrarnos no es lo mismo que habilitarla. En mainnet está en pausa hasta tener una opinión legal por escrito, y habilitar una bóveda requiere un commit al repositorio, con autor y fecha.')} {" "} - {network === 'mainnet' + {exitOnly ? lang( - 'Withdraw moves your tokens from the vault back to your wallet, and you sign it. Depositing from this page on mainnet is invite-only until we have a written legal opinion.', - 'Retirar mueve tus tokens de la bóveda de regreso a tu wallet, y lo firmas tú. Depositar desde esta página en mainnet es solo por invitación hasta tener una opinión legal por escrito.') + 'Withdraw moves your tokens from the vault back to your wallet, and you sign it. Taking the rebalance role back removes Nirium from your vault; you sign that too.', + 'Retirar mueve tus tokens de la bóveda de regreso a tu wallet, y lo firmas tú. Recuperar el rol de rebalanceo saca a Nirium de tu bóveda; eso también lo firmas tú.') + : network === 'mainnet' + ? lang( + 'Withdraw moves your tokens from the vault back to your wallet, and you sign it. Depositing from this page on mainnet is paused until we have a written legal opinion.', + 'Retirar mueve tus tokens de la bóveda de regreso a tu wallet, y lo firmas tú. Depositar desde esta página en mainnet está en pausa hasta tener una opinión legal por escrito.') : lang( 'Deposit moves your tokens into the vault. Invest and Unwind (to the vault) are signed by the agent with its own key - and neither can send anything outside the vault.', 'Depositar mueve tus tokens a la bóveda. Invertir y Sacar de la estrategia los firma el agente con su propia llave - y ninguno puede mandar nada fuera de la bóveda.')} @@ -1013,15 +1054,19 @@ export default function TreasuryVaultConsole() {

    {/* Antes decía "no se dispara desde aquí" también en testnet, donde sí están los botones Invertir / Sacar de la estrategia. */} - {network === 'mainnet' + {exitOnly + ? lang( + 'Nobody rebalances vaults from this site anymore: the mainnet rebalancer is stopped and the testnet demo is off.', + 'Ya nadie rebalancea bóvedas desde este sitio: el rebalanceador de mainnet está detenido y la demo de testnet está apagada.') + : network === 'mainnet' ? lang( 'On mainnet, rebalancing is not triggered from here. It is called by the RebalanceManager - the agent, with its own key - and it can only move funds between the strategies already inside your vault.', 'En mainnet el rebalanceo no se dispara desde aquí. Lo llama el RebalanceManager - el agente, con su propia llave - y solo puede mover fondos entre las estrategias que ya están dentro de tu bóveda.') : lang( - 'On testnet you can ask the agent to Invest or Unwind with the buttons above, to see it work. It signs with its own key and can only move funds between the vault and its strategy. On mainnet there is no button: the agent decides on its own, only on vaults where autonomous rebalancing is switched on, which on mainnet is invite-only.', - 'En testnet puedes pedirle al agente Invertir o Sacar de la estrategia con los botones de arriba, para verlo funcionar. Firma con su propia llave y solo puede mover fondos entre la bóveda y su estrategia. En mainnet no hay botón: el agente decide solo, únicamente en bóvedas donde el rebalanceo autónomo está encendido, y en mainnet eso es por invitación.')}{' '} + 'On testnet you can ask the agent to Invest or Unwind with the buttons above, to see it work. It signs with its own key and can only move funds between the vault and its strategy. On mainnet there is no button: the agent decides on its own, only on vaults where autonomous rebalancing is switched on, which on mainnet is paused.', + 'En testnet puedes pedirle al agente Invertir o Sacar de la estrategia con los botones de arriba, para verlo funcionar. Firma con su propia llave y solo puede mover fondos entre la bóveda y su estrategia. En mainnet no hay botón: el agente decide solo, únicamente en bóvedas donde el rebalanceo autónomo está encendido, y en mainnet eso está en pausa.')}{' '} - {lang('How the node works', 'Cómo funciona el nodo')} + {lang('More', 'Más')}

    diff --git a/apps/web/app/(app)/verify/page.tsx b/apps/web/app/(app)/verify/page.tsx index af7f7896..e012dfa9 100644 --- a/apps/web/app/(app)/verify/page.tsx +++ b/apps/web/app/(app)/verify/page.tsx @@ -13,7 +13,7 @@ import { import { useLanguage } from '@/context/LanguageContext'; import { extractCid, checkRecordIntegrity, declaredNetwork, explorerTxUrl, explorerAccountUrl, checkSignerAccount, - rawGatewayUrl, formatAnchoredAtUtc, + rawGatewayUrl, formatAnchoredAtUtc, hashRecord, type AnchoredDoc, type RecordCheck, type SignerAccount, } from '@/lib/auditVerify'; import { receiptCid } from '@/lib/receiptCid'; @@ -55,7 +55,7 @@ const EXAMPLE_GROUPS: { id: ExampleGroup; items: { label: ExampleLabel; cid: str ] }, ]; -type Phase = 'idle' | 'searching' | 'found' | 'error_invalid' | 'error_not_found' | 'error_not_audit_doc' | 'error_generic' | 'error_cid_mismatch'; +type Phase = 'idle' | 'searching' | 'found' | 'other_chain' | 'error_invalid' | 'error_not_found' | 'error_not_audit_doc' | 'error_generic' | 'error_cid_mismatch'; // 'match': el CIDv0 recalculado en el navegador es el CID pedido. 'unsupported': no se pudo // recalcular aquí (CIDv1, o más de un bloque de 256 KiB); se remite a la CLI. type CidCheck = 'match' | 'unsupported'; @@ -63,6 +63,22 @@ type AttestationState = 'checking' | 'valid' | 'invalid' | 'none' | 'error'; const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms)); +// Receipts and transactions from the other chains Nirium runs on are checked on that chain's own page, +// nirium.xyz/solana or nirium.xyz/avalanche, with that chain's verifier. +type OtherChain = { chain: 'solana' | 'avalanche'; q: string }; +const OTHER_CHAIN_NAME = { solana: 'Solana', avalanche: 'Avalanche' } as const; +function chainOfNetwork(network: unknown): OtherChain['chain'] | null { + if (typeof network !== 'string') return null; + if (network.startsWith('solana:')) return 'solana'; + if (network === 'eip155:43114' || network === 'eip155:43113') return 'avalanche'; + return null; +} +function chainOfInput(raw: string): OtherChain['chain'] | null { + if (/^0x[0-9a-fA-F]{64}$/.test(raw)) return 'avalanche'; // an EVM transaction hash + if (/^[1-9A-HJ-NP-Za-km-z]{86,88}$/.test(raw)) return 'solana'; // a Solana transaction signature + return null; +} + function VerifyContent() { const { t, language } = useLanguage(); const tv = t.verifyAudit; @@ -78,6 +94,7 @@ function VerifyContent() { const [cidCheck, setCidCheck] = useState(null); const [attestation, setAttestation] = useState('none'); const [signerAccount, setSignerAccount] = useState('unknown'); + const [otherChain, setOtherChain] = useState(null); const [copiedField, setCopiedField] = useState(null); // Comparar un anclaje de solo hash con la evidencia original (9-nov-2026). // El archivo se lee y se hashea EN EL NAVEGADOR (crypto.subtle); nunca se sube. @@ -153,6 +170,12 @@ function VerifyContent() { setPhase('error_not_audit_doc'); return; } + const other = chainOfNetwork(data?.network ?? data?.record?.payment?.network ?? data?.record?.intent?.network); + if (other) { + setOtherChain({ chain: other, q: targetCid }); + setPhase('other_chain'); + return; + } if (!data || typeof data.content_sha256 !== 'string') { setPhase('error_not_audit_doc'); return; @@ -210,6 +233,13 @@ function VerifyContent() { }; const startLookup = (raw: string) => { + setOtherChain(null); + const inputChain = chainOfInput(raw.trim()); + if (inputChain) { + setOtherChain({ chain: inputChain, q: raw.trim() }); + setPhase('other_chain'); + return; + } const extracted = extractCid(raw); if (!extracted) { setPhase('error_invalid'); @@ -271,6 +301,52 @@ function VerifyContent() { // null = el documento no declara red: se dice, no se asume testnet. const network = declaredNetwork(doc?.network); + + const examples = ( + + ); return (
    @@ -333,49 +409,13 @@ function VerifyContent() {
    -
    -

    - {tv.example_intro}{' '} - - {tv.example_anchor_link} - - {' '}{tv.example_guide_suffix} -

    -
    - {EXAMPLE_GROUPS.map((group) => ( -
    -

    {tv.example_groups[group.id].title}

    -
    - {group.items.map((ex) => ( - - ))} -
    -

    {tv.example_groups[group.id].note}

    - {group.items.some((ex) => ex.href) && ( -

    - {group.items.filter((ex) => ex.href).map((ex, i) => ( - - {i > 0 && ' · '} - - {ex.label === 'notice' ? tv.example_notice_link : `${tv.example_code_prefix} ${tv.example_labels[ex.label]}`} - - - ))} -

    - )} -
    - ))} -
    -
    +

    + {language === 'es' + ? '¿Un recibo de Solana o Avalanche? Pégalo aquí y te mandamos a la página de esa red.' + : 'A receipt from Solana or Avalanche? Paste it here and we send you to that chain\'s page.'} +

    + + {phase === 'idle' && examples}
    @@ -397,6 +437,31 @@ function VerifyContent() { )} + {phase === 'other_chain' && otherChain && ( + + +

    + {language === 'es' + ? `Esto es de ${OTHER_CHAIN_NAME[otherChain.chain]}. Se comprueba en la página de esa red, con su propio verificador, en tu navegador.` + : `This is from ${OTHER_CHAIN_NAME[otherChain.chain]}. It is checked on that chain's page, with its own verifier, in your browser.`} +

    + + {language === 'es' ? `Comprobar en nirium.xyz/${otherChain.chain}` : `Check it on nirium.xyz/${otherChain.chain}`} + + + + {language === 'es' ? 'Qué funciona en cada red' : 'What works on each chain'} + +
    + )} + {(phase === 'error_invalid' || phase === 'error_not_found' || phase === 'error_not_audit_doc' || phase === 'error_generic' || phase === 'error_cid_mismatch') && ( {phase === 'error_not_found' && ( -

    {tv.result.keep_copy_note.replace('', extractCid(cidInput) ?? '')}

    +

    {tv.result.keep_copy_note.replace('', extractCid(cidInput) ?? '')}

    )} {phase !== 'error_invalid' && (
    )} @@ -482,7 +547,7 @@ function VerifyContent() { ? 'Si tienes la evidencia original, elígela aquí. Tu navegador calcula su SHA-256 y lo compara con el hash del recibo. El archivo no sale de tu computadora: no se sube a Nirium ni a ningún otro lado.' : 'If you have the original evidence, pick it here. Your browser computes its SHA-256 and compares it with the receipt’s hash. The file never leaves your computer: it is not uploaded to Nirium or anywhere else.'}

    -

    {tv.result.keep_copy_note.replace('', cid)}

    +

    {tv.result.keep_copy_note.replace('', cid)}

    )} @@ -625,17 +696,23 @@ function VerifyContent() {
    {tv.result.attested_by} {signerAccount === 'missing' ? ( - {doc.agent.key} + {doc.agent.key} ) : ( - {doc.agent.key} + {doc.agent.key} )}
    + {doc.agent.id && ( +
    + {tv.result.agent_label} + {doc.agent.id} +
    + )} {signerAccount === 'missing' && (

    {tv.result.signer_no_account}

    )} @@ -657,7 +734,7 @@ function VerifyContent() { )}
    {(attestation === 'valid' || attestation === 'invalid') && ( -

    {tv.result.attestation_server_note.replace('', cid)}

    +

    {tv.result.attestation_server_note.replace('', cid)}

    )}
    ) : ( @@ -675,6 +752,9 @@ function VerifyContent() { )} + {/* After a lookup the result stays right under the input, and the examples move below it. */} + {phase !== 'idle' &&
    {examples}
    } + {/* What a receipt proves vs. what Stellar already proves */} +
    {label}
    -
    {children}
    +
    {children}
    ); } function MonoCopyValue({ value, onCopy, copied }: { value: string; onCopy: () => void; copied: boolean }) { return ( -
    +
    {value}