Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(reputation): let only the staker withdraw a reputation-market position, proven by a wallet signature
nirholasa5e249ddef25
diff --git a/api/_lib/reputation-market.js b/api/_lib/reputation-market.jsindex 38a81e056..b47b82fdf 100644--- a/api/_lib/reputation-market.js+++ b/api/_lib/reputation-market.js@@ -20,6 +20,8 @@*/import { Keypair, PublicKey, SystemProgram, Transaction, TransactionInstruction } from '@solana/web3.js';+import { ed25519 } from '@noble/curves/ed25519.js';+import bs58 from 'bs58';import { sql } from './db.js';import { solanaConnection } from './solana/connection.js';@@ -39,6 +41,7 @@ import {realizedApr,clampSettlement,toBigInt,+ unstakeProofMessage,} from '../../src/shared/reputation-staking.js';export { MARKET_TAG, MIN_STAKE_LAMPORTS };@@ -478,6 +481,44 @@ export async function escrowSurplus({ network, env = process.env }) {return { balance, principal, rentFloor, surplus: surplus > 0n ? surplus : 0n };}+/** How long a signed unstake proof stays valid, either side of the server clock. */+export const UNSTAKE_PROOF_TTL_MS = 5 * 60_000;++export { unstakeProofMessage };++/**+ * Spec rule 1: only the staker who opened a position may withdraw it. The+ * payout always goes to the staker, but an open endpoint still let anyone+ * force-close every position backing a rival agent (collapsing its rank and+ * ending the stakers' accrual), or time a close for when the surplus is thin.+ *+ * @param {{ position: { network: string, signature: string, staker: string }, proof: { issued_at?: number|string, signature?: string }|null, now?: number }} args+ * @throws {MarketError}+ */+export function verifyUnstakeProof({ position, proof, now = Date.now() }) {+ const issuedAt = Number(proof?.issued_at);+ if (!proof?.signature || !Number.isSafeInteger(issuedAt)) {+ throw new MarketError('proof_required', 'Sign the unstake message with the wallet that opened this position.', 401);+ }+ if (Math.abs(now - issuedAt) > UNSTAKE_PROOF_TTL_MS) {+ throw new MarketError('proof_expired', 'The signed unstake message is too old. Sign it again.', 401);+ }+ const message = unstakeProofMessage({ network: position.network, stakeSignature: position.signature, issuedAt });+ let ok = false;+ try {+ ok = ed25519.verify(+ bs58.decode(String(proof.signature)),+ new TextEncoder().encode(message),+ new PublicKey(position.staker).toBytes(),+ );+ } catch {+ ok = false;+ }+ if (!ok) {+ throw new MarketError('not_staker', 'Only the wallet that opened this position can withdraw it.', 403);+ }+}+/*** Settle a position: pay principal plus accrued earnings back to the staker* recorded on-chain, write a `threews.unstake.v1` memo in the same transaction,@@ -487,12 +528,13 @@ export async function escrowSurplus({ network, env = process.env }) {* paying twice; a `settling` position is claimed by whichever caller flipped it,* so a crashed withdrawal is retried rather than double-paid.*/-export async function withdrawPosition({ signature, network, env = process.env }) {+export async function withdrawPosition({ signature, network, proof, env = process.env }) {const cfg = marketConfig(network, env);assertWritable(cfg);const position = await getPosition({ signature, network: cfg.network });if (!position) throw new MarketError('unknown_position', `No indexed position for ${signature}.`, 404);+ verifyUnstakeProof({ position, proof });if (position.status === 'closed') {const settlement = await getSettlement(position.signature);diff --git a/api/reputation/market-withdraw.js b/api/reputation/market-withdraw.jsindex fd14633f1..819c5e588 100644--- a/api/reputation/market-withdraw.js+++ b/api/reputation/market-withdraw.js@@ -1,5 +1,5 @@/**- * POST /api/reputation/market-withdraw { signature, network }+ * POST /api/reputation/market-withdraw { signature, network, proof: { issued_at, signature } }** Settle a reputation-market position: return the staker's principal in full* plus whatever their conviction earned from the agent's attested action@@ -7,9 +7,11 @@* on-chain.** The payout always goes to the staker recorded in the stake transaction, never- * to the caller, so this endpoint is safe to leave open: the worst an attacker- * can do by calling it for someone else's position is pay that person their own- * money. Mainnet stays owner-gated (specs/REPUTATION_STAKING_MARKET.md §1).+ * to the caller. That alone is not enough: an open endpoint let anyone close+ * every position backing a rival agent. So the caller proves they ARE the+ * staker by signing `threews.unstake.v1:<network>:<stake sig>:<issued_at ms>`+ * with that wallet (`proof: { issued_at, signature }`, base58 signature), the+ * spec's rule 1. Mainnet stays owner-gated (specs/REPUTATION_STAKING_MARKET.md §1).*/import { cors, json, method, wrap, rateLimited, error, readJson } from '../_lib/http.js';@@ -35,7 +37,8 @@ export default wrap(async (req, res) => {}try {- const result = await withdrawPosition({ signature, network });+ const proof = body?.proof && typeof body.proof === 'object' ? body.proof : null;+ const result = await withdrawPosition({ signature, network, proof });return json(res, 200, {ok: true,status: result.status,diff --git a/docs/reputation-staking-market.md b/docs/reputation-staking-market.mdindex c065bf367..e0ce3bc5d 100644--- a/docs/reputation-staking-market.md+++ b/docs/reputation-staking-market.md@@ -113,12 +113,18 @@ quotes is auditable against the spec, epoch by epoch.## Withdraw-There is no lockup. Withdraw any time:+There is no lockup. Withdraw any time. Only the wallet that opened a position+can withdraw it: sign the text+`threews.unstake.v1:<network>:<stake signature>:<issued_at>` with that wallet+(`issued_at` is the current time in milliseconds; the server accepts it for 5+minutes) and send the base58 signature as `proof`. The+[/reputation/market](/reputation/market) page does this for you with one+wallet prompt and no fee.```bashcurl -X POST https://three.ws/api/reputation/market-withdraw \-H 'content-type: application/json' \- -d '{"signature": "<stake signature>", "network": "devnet"}'+ -d '{"signature": "<stake signature>", "network": "devnet", "proof": {"issued_at": 1760000000000, "signature": "<base58 wallet signature>"}}'```The market escrow signs one settlement transaction paying principal plus@@ -213,11 +219,12 @@ proof confirms over HTTP polling and works untouched.| `/api/reputation/market?network=devnet` | GET | Agents ranked by net staked conviction, epoch weight, realized yield. || `/api/reputation/market-positions?staker=<wallet>&network=devnet` | GET | Every position a wallet holds, with pending earnings. || `/api/reputation/market-stake` | POST | Index a stake transaction. Body: `{ signature, network }`. |-| `/api/reputation/market-withdraw` | POST | Settle a position. Body: `{ signature, network }`. |+| `/api/reputation/market-withdraw` | POST | Settle a position. Body: `{ signature, network, proof }`, where `proof` is the staker's signed unstake message. |Failure codes (`market_not_configured`, `mainnet_gated`, `tx_not_found`,`not_a_market_stake`, `stake_below_minimum`, `unknown_position`,-`already_closed`, `escrow_unsigned`) are pinned in spec §9.+`already_closed`, `escrow_unsigned`, `proof_required`, `proof_expired`,+`not_staker`) are pinned in spec §9.## Relateddiff --git a/public/reputation/market/market.js b/public/reputation/market/market.jsindex 4d0a8b541..3726955f3 100644--- a/public/reputation/market/market.js+++ b/public/reputation/market/market.js@@ -434,12 +434,18 @@ async function submitRecord(event) {async function withdraw(signature, button) {button.disabled = true;const original = button.textContent;- button.textContent = 'Settling…';+ button.textContent = 'Sign in wallet…';try {+ // Only the staker may withdraw (spec rule 1): the wallet that opened the+ // position signs a short, fee-free message proving it.+ const wallet = await connectWallet();+ const { signUnstakeProof } = await import('../../src/solana-stake.js');+ const proof = await signUnstakeProof({ wallet, network: state.network, stakeSignature: signature });+ button.textContent = 'Settling…';const body = await api('/api/reputation/market-withdraw', {method: 'POST',headers: { 'content-type': 'application/json' },- body: JSON.stringify({ signature, network: state.network }),+ body: JSON.stringify({ signature, network: state.network, proof }),});const s = body.settlement;const paid = BigInt(s.principal_lamports) + BigInt(s.earnings_lamports);diff --git a/specs/REPUTATION_STAKING_MARKET.md b/specs/REPUTATION_STAKING_MARKET.mdindex f41a44e64..7e331c5a0 100644--- a/specs/REPUTATION_STAKING_MARKET.md+++ b/specs/REPUTATION_STAKING_MARKET.md@@ -288,7 +288,7 @@ against `getTransaction(signature)` alone.| `/api/reputation/market` | GET | none | Agents ranked by net staked conviction, with epoch weight and realized yield. || `/api/reputation/market-positions` | GET | none (`staker` query param) | Every position a wallet holds, with pending earnings. || `/api/reputation/market-stake` | POST | none | Record a stake transaction the staker already broadcast. Body: `{ signature, network }`. Verification is a chain read; the caller cannot assert a principal. |-| `/api/reputation/market-withdraw` | POST | none | Settle a position. Body: `{ signature, network }`. The payout goes to the staker recorded on-chain, so an attacker calling this for someone else's position only causes that person to be paid. |+| `/api/reputation/market-withdraw` | POST | staker signature | Settle a position. Body: `{ signature, network, proof: { issued_at, signature } }`. `proof.signature` is the staker wallet's base58 ed25519 signature over `threews.unstake.v1:<network>:<stake signature>:<issued_at>` (`issued_at` in milliseconds, accepted within 5 minutes of the server clock), which enforces rule 1. The payout still goes only to the staker recorded on-chain. |Every write refuses on `mainnet` unless the owner gate in §1 is open, with`code: "mainnet_gated"`.@@ -303,6 +303,9 @@ Every write refuses on `mainnet` unless the owner gate in §1 is open, with| `not_a_market_stake` | 400 | Memo missing, wrong kind, wrong `market`, or wrong `escrow`. || `stake_below_minimum` | 400 | Escrow delta below `MIN_STAKE_LAMPORTS`. || `unknown_position` | 404 | No indexed position for that signature. |+| `proof_required` | 401 | Withdrawal sent without a staker `proof`. |+| `proof_expired` | 401 | The proof's `issued_at` is more than 5 minutes from the server clock. |+| `not_staker` | 403 | The proof is not a valid signature by the position's staker. || `already_closed` | 200 | Idempotent: returns the original settlement. || `escrow_unsigned` | 503 | Escrow secret key not configured, so no payout can be signed. |diff --git a/src/shared/reputation-staking.js b/src/shared/reputation-staking.jsindex 79b1d7e6f..0e50ad387 100644--- a/src/shared/reputation-staking.js+++ b/src/shared/reputation-staking.js@@ -40,6 +40,18 @@ export const MIN_STAKE_LAMPORTS = 1_000_000n;/** The market envelope tag that separates a market stake from a bare conviction memo. */export const MARKET_TAG = 'rsm.v1';+/**+ * The exact text a staker signs with their wallet to withdraw a position.+ * Bound to the network and the stake signature so one proof cannot settle a+ * different position, and to a millisecond timestamp the server holds to a+ * few minutes, so a captured proof goes stale. Shared so the page that signs+ * and the server that verifies can never drift apart.+ */+export function unstakeProofMessage({ network, stakeSignature, issuedAt }) {+ const net = network === 'mainnet' ? 'mainnet' : 'devnet';+ return `threews.unstake.v1:${net}:${stakeSignature}:${issuedAt}`;+}+/** Weight each attested action contributes to an agent's epoch `work`. */export const WORK_WEIGHTS = Object.freeze({taskAccepted: 1.0,diff --git a/src/solana-stake.js b/src/solana-stake.jsindex f90547bb1..013f6fa52 100644--- a/src/solana-stake.js+++ b/src/solana-stake.js@@ -13,6 +13,8 @@ import {Transaction,TransactionInstruction,} from '@solana/web3.js';+import bs58 from 'bs58';+import { unstakeProofMessage } from './shared/reputation-staking.js';const MEMO_PROGRAM_ID = new PublicKey('MemoSq4gqABAXKb96qnH8TysNcWxMyWCqXgDLGmfcHr');export const MIN_STAKE_LAMPORTS = 1_000_000n; // 0.001 SOL@@ -164,3 +166,25 @@ export async function stakeOnMarket({ agentAsset, escrow, lamports, score, netwoawait conn.confirmTransaction({ signature: sig, blockhash, lastValidBlockHeight }, 'confirmed');return sig;}++/**+ * Prove to /api/reputation/market-withdraw that the connected wallet is the+ * staker of a position: sign the shared unstake message (no transaction, no+ * fee) and return the `proof` body field the endpoint verifies.+ *+ * @param {object} opts+ * @param {object} opts.wallet Solana wallet adapter (publicKey + signMessage)+ * @param {'mainnet'|'devnet'} opts.network+ * @param {string} opts.stakeSignature the position id (its stake transaction signature)+ * @returns {Promise<{ issued_at: number, signature: string }>}+ */+export async function signUnstakeProof({ wallet, network, stakeSignature }) {+ if (!wallet?.publicKey || typeof wallet.signMessage !== 'function') {+ throw new Error('This wallet cannot sign messages. Use Phantom, Backpack, or Solflare.');+ }+ const issuedAt = Date.now();+ const message = unstakeProofMessage({ network, stakeSignature, issuedAt });+ const out = await wallet.signMessage(new TextEncoder().encode(message), 'utf8');+ const bytes = out?.signature ?? out;+ return { issued_at: issuedAt, signature: bs58.encode(bytes) };+}