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
feat(irl-sdk): Money Drops + World Lines in @three-ws/irl v0.2.0
fudjiaeb7aced88248
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ddfbf96c6..65a883f86 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,10 @@Public history for [three.ws](https://three.ws), newest first. New pages come from `added` dates in data/pages.json; everything else is curated in data/changelog.json. Also available as [JSON](https://three.ws/changelog.json) and [RSS](https://three.ws/changelog.xml), live at [three.ws/changelog](https://three.ws/changelog).+## 2026-07-09++- **Agents can now hunt money drops and complete IRL quests from code** — The @three-ws/irl SDK (v0.2.0) now covers the whole IRL surface, not just pins. New functions let any script or agent discover real-money drops near where it checks in, claim them with a proof-of-presence fix (a real on-chain release to its own wallet), place self- or agent-funded drops and bounties, and run the full World Lines quest loop — find nearby quests, take the challenge at the spot, and earn the agent-signed proof-of-presence collectible, plus verify anyone's proof independently. Fully typed, zero dependencies, verified against the live API. (`/irl`) `[sdk, feature]`+## 2026-07-08- **Blockchain TVL by Chain** (`/chains`) — A leaderboard of every blockchain by total value locked, with each chain's dominance share of on-chain DeFi. Live from DeFiLlama — see where liquidity actually sits across L1s and L2s.diff --git a/data/changelog.json b/data/changelog.jsonindex d027e11f4..4966d8f19 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -12506,6 +12506,16 @@"improvement"],"link": "/animations"+ },+ {+ "date": "2026-07-09",+ "title": "Agents can now hunt money drops and complete IRL quests from code",+ "summary": "The @three-ws/irl SDK (v0.2.0) now covers the whole IRL surface, not just pins. New functions let any script or agent discover real-money drops near where it checks in, claim them with a proof-of-presence fix (a real on-chain release to its own wallet), place self- or agent-funded drops and bounties, and run the full World Lines quest loop — find nearby quests, take the challenge at the spot, and earn the agent-signed proof-of-presence collectible, plus verify anyone's proof independently. Fully typed, zero dependencies, verified against the live API.",+ "tags": [+ "sdk",+ "feature"+ ],+ "link": "/irl"}]}diff --git a/packages/irl/README.md b/packages/irl/README.mdindex 1a4b87876..997747fc0 100644--- a/packages/irl/README.md+++ b/packages/irl/README.md@@ -17,6 +17,8 @@<a href="#install">Install</a> ·<a href="#quick-start">Quick start</a> ·<a href="#api">API</a> ·+ <a href="#money-drops">Money Drops</a> ·+ <a href="#world-lines">World Lines</a> ·<a href="#how-it-works">How it works</a> ·<a href="https://three.ws/irl">three.ws</a></p>@@ -29,11 +31,13 @@> short-lived proof-of-presence token from your live fix, and read back only the> agents within a tight radius of where you actually stand. It wraps the public> `/api/irl/*` endpoints: presence minting, GPS pin placement, the geofenced-> nearby feed, and the real-world interaction log. Presence is the contract —-> there is no browseable map, no roster, no "query any point on earth." You see-> what's around you, because you're there. It pairs with-> [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) (make the-> avatar) and [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)+> nearby feed, the real-world interaction log, **[Money Drops](#money-drops)**+> (real SOL / USDC / $THREE escrowed at a spot, claimable only by walking up)+> and **[World Lines](#world-lines)** (agent-signed proof-of-presence AR+> quests). Presence is the contract — there is no browseable map, no roster, no+> "query any point on earth." You see what's around you, because you're there.+> It pairs with [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge)+> (make the avatar) and [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)> (render it where you placed it).## Why@@ -41,7 +45,7 @@Hand-rolling "agents in the real world" looks easy until you hit the privacymath. A naive `GET /pins?lat=&lng=` is a location-harvest API: anyone scripts agrid sweep and reconstructs every placement on earth. three.ws IRL closes that-hole structurally, and this SDK gives you the whole flow as four functions:+hole structurally, and this SDK gives you the whole flow as plain functions:- **Presence is proven, not claimed.** Before you can read nearby agents youmint a fix token from your *real* geolocation. The server only answers for the@@ -215,6 +219,140 @@ per signature.deviceToken })` sets defaults for the module (base origin defaults to`https://three.ws`).+## Money Drops++Real value, escrowed at a real-world spot. A drop holds SOL, USDC, or $THREE in+a fresh per-drop escrow wallet, funded on-chain by its creator; anyone who+physically walks up — proven by the same fix token every IRL read enforces —+claims a real on-chain release to their own wallet. Unclaimed funds auto-refund+the creator on expiry. Wraps `/api/irl/drops`.++Find and claim a drop where you stand:++```js+import { checkIn, nearbyDrops, claimDrop } from '@three-ws/irl';++const fix = await checkIn();+const drops = await nearbyDrops(fix); // presence-gated, like every IRL read++for (const d of drops) {+ console.log(d.title, `${d.amount} ${d.asset}`, `${d.distanceM}m away`, `${d.claimsLeft} left`);+}++const { signature, explorerUrl } = await claimDrop({+ dropId: drops[0].id,+ presence: fix, // co-location is always verified+ wallet: 'YourSo1anaWa11etAddress…', // the release lands HERE, on-chain+ answer: drops[0].quizQuestion ? 'my answer' : undefined,+});+console.log('claimed:', explorerUrl);+```++Place one (two funding paths):++```js+import { checkIn, createDrop, fundDrop } from '@three-ws/irl';++const fix = await checkIn();++// 1) Self-funded: create → send funds to the escrow → confirm the transfer.+const { drop, escrowAddress, fundAmount } = await createDrop({+ lat: fix.lat, lng: fix.lng,+ asset: 'USDC', amount: 5, maxClaims: 5, claimRule: 'each-once',+ title: 'Coffee on me', radiusM: 30,+});+// …transfer `fundAmount` USDC to `escrowAddress` from your own wallet, then:+await fundDrop({ dropId: drop.id, signature: 'your-transfer-signature' });++// 2) Agent bounty (signed-in owner): the agent's custodial wallet funds it+// server-side under its spend limits — returned already active.+const bounty = await createDrop({+ agentId: 'your-agent-id', kind: 'bounty', asset: 'SOL', amount: 0.1,+ lat: fix.lat, lng: fix.lng, bountyCondition: 'quiz',+ quizQuestion: 'What is the only coin?', quizAnswer: '$THREE',+});+console.log(bounty.funded, bounty.fundingTx);+```++| Function | Wraps | Notes |+|---|---|---|+| `nearbyDrops(presence, { radius? })` | `GET /api/irl/drops?lat=&lng=` | Fix-gated; radius clamped 10–80 m. |+| `getDrop(id)` | `GET /api/irl/drops/:id` | Location coarsened to ~110 m for non-owners (`coarse: true`). |+| `myDrops()` | `GET /api/irl/drops?mine=1` | `{ drops, claims }` — your creations + claim receipts. |+| `createDrop(input)` | `POST /api/irl/drops` | Returns the escrow to fund, or `funded: true` for agent bounties. |+| `fundDrop({ dropId, signature })` | `POST /:id/fund` | Confirms your transfer on-chain; `{ pending: true }` while confirming. |+| `claimDrop({ dropId, presence, wallet, answer? })` | `POST /:id/claim` | Presence always verified; releases real funds to `wallet`. |+| `cancelDrop(id)` | `POST /:id/cancel` | Owner-only; sweeps a real refund, idempotent. |++Claim errors are typed like everything else: `fix_required` (stand there and+re-`checkIn()`), `out_of_range` (the drop's radius, with `distance_m` in+`detail`), `wrong_answer` / `condition_unmet` (bounty), `already_claimed`,+`exhausted`, `expired`.++## World Lines++Agent-placed proof-of-presence AR quests. A World Line anchors a quest to a pin+you own; to complete it, a person must physically travel there, prove+co-location, and finish the interaction (tap, quiz, or spoken passphrase). On+success the **agent's own wallet signs an ed25519 proof-of-presence** —+independently verifiable by anyone, ownable as a collectible — without a+precise coordinate ever entering the proof. Wraps `/api/irl/world-lines`.++The walk-up completion loop:++```js+import { checkIn, nearbyWorldLines, challengeWorldLine, completeWorldLine } from '@three-ws/irl';++const fix = await checkIn();+const quests = await nearbyWorldLines(fix, { radius: 400 }); // "≈200 m north"+const quest = quests.find((q) => !q.completedByMe);++// At the spot: the challenge issues a single-use nonce and reveals the full+// spec (you are proven co-located).+const ch = await challengeWorldLine({ worldLineId: quest.id, presence: fix });++const { proof, collectible } = await completeWorldLine({+ worldLineId: quest.id,+ nonce: ch.nonce,+ presence: fix,+ answer: ch.challenge.kind === 'quiz' ? 0 : undefined, // your chosen index+});+console.log('agent-signed proof:', proof.signature, '→', proof.verifyUrl);+```++Place a quest on your pin (signed-in — pass `apiKey` to `createIrl`):++```js+import { createIrl } from '@three-ws/irl';++const irl = createIrl({ apiKey: process.env.THREE_WS_SESSION });+const { worldLine } = await irl.createWorldLine({+ pinId: 'your-pin-id', // the anchor — a pin you own+ title: 'Meet the courier',+ prompt: 'Find me by the fountain and answer one question.',+ challenge: { kind: 'quiz', question: 'What coin?', choices: ['$THREE', 'fiat'], answer: 0 },+ rewardRef: 'Courier badge',+ lifetimeDays: 30,+});+```++| Function | Wraps | Notes |+|---|---|---|+| `nearbyWorldLines(presence, { radius? })` | `GET /world-lines/nearby` | Fix-gated; default 250 m, max 600 m; distance coarsened to 10 m. |+| `browseWorldLines({ region?, difficulty? })` | `GET /world-lines/browse` | Public + coordinate-free: region roll-up, or one region's quests. |+| `getWorldLine(id, { presence? })` | `GET /world-lines/:id` | Full challenge spec only when proven co-located. |+| `createWorldLine(input)` | `POST /world-lines` | Auth required; the agent's wallet signs every proof. |+| `myWorldLines()` | `GET /world-lines/mine` | Your quests + a coarse completion heatmap. |+| `myCollectibles()` | `GET /world-lines/collectibles` | The proofs you've earned (session or device token). |+| `challengeWorldLine({ worldLineId, presence })` | `POST /world-lines/challenge` | Single-use nonce; `alreadyCompleted` short-circuits. |+| `completeWorldLine({ worldLineId, nonce, presence, answer?, phrase? })` | `POST /world-lines/complete` | The proof ceremony → signed collectible. |+| `verifyProof(proofId)` | `GET /world-lines/verify/:id` | Public re-check of the agent signature. |++The proof's canonical signed message carries only the quest id, a ~1.1 km+coarse cell, the nonce, and a salted hash of the completer — never a+coordinate, never a raw device token. `verifyProof()` re-runs the exact ed25519+check anyone could do offline against `signerPubkey`.+## How it worksPresence is the gate on every read. You can never query a point you aren't at:diff --git a/packages/irl/package.json b/packages/irl/package.jsonindex 1992514fa..13aa3c2bc 100644--- a/packages/irl/package.json+++ b/packages/irl/package.json@@ -1,7 +1,7 @@{"name": "@three-ws/irl",- "version": "0.1.0",- "description": "Geofenced, real-world presence for agents and avatars — check in at a GPS spot with a proof-of-presence fix, discover who's nearby, and log real encounters. The three.ws IRL client.",+ "version": "0.2.0",+ "description": "Geofenced, real-world presence for agents and avatars — check in at a GPS spot with a proof-of-presence fix, discover who's nearby, log real encounters, claim real-money drops, and complete agent-signed proof-of-presence quests. The three.ws IRL client.","type": "module","main": "./src/index.js","module": "./src/index.js",@@ -33,6 +33,10 @@"agents","avatar","presence",+ "geocache",+ "bounty",+ "quests",+ "solana","three.ws"],"author": "nirholas <[email protected]>",diff --git a/packages/irl/src/drops.js b/packages/irl/src/drops.jsnew file mode 100644index 000000000..686a38834--- /dev/null+++ b/packages/irl/src/drops.js@@ -0,0 +1,279 @@+// IRL Money Drops & Bounties — the SDK twin of /api/irl/drops. Real value+// escrowed at a real-world spot: create a drop, fund its fresh escrow wallet+// on-chain, and anyone who physically walks up (proven by the same fix token+// the nearby read enforces) claims a release to their own wallet.++import { ThreeWsError } from './http.js';+import { presenceFix, fixHeader, prune, normalizeEnum, requireId } from './shared.js';++const DROP_KINDS = ['drop', 'bounty'];+const DROP_ASSETS = ['SOL', 'USDC', 'THREE'];+const CLAIM_RULES = ['first', 'each-once', 'quiz'];+const BOUNTY_CONDITIONS = ['presence', 'quiz', 'chat'];++// Base58 shape of a Solana address — the claim wallet is validated before any+// network round-trip so a typo fails fast, not at the release step.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++/**+ * Build the drops slice of the IRL client. `request` is the bound HTTP core and+ * `deviceHeader` merges the caller's anonymous device token into headers.+ */+export function createDropsApi({ request, deviceHeader }) {+ /**+ * Live drops within the radius of where you checked in. Wraps+ * `GET /api/irl/drops?lat=&lng=&radius=` with the presence token in the+ * `x-irl-fix` header — like every IRL location read, you only see drops+ * where you physically stand. Radius is clamped server-side to 10–80 m.+ */+ async function nearbyDrops(presence, opts = {}) {+ const { lat, lng, token } = presenceFix(presence, 'nearbyDrops()');+ const radius = opts.radius;+ if (radius !== undefined && !Number.isFinite(radius)) {+ throw new ThreeWsError('nearbyDrops() radius must be a finite number of metres.', { code: 'invalid_input' });+ }+ const res = await request('/api/irl/drops', {+ query: { lat, lng, radius },+ headers: deviceHeader(opts, fixHeader(token, opts.headers)),+ signal: opts.signal,+ });+ return (res?.drops || []).map(shapeDrop);+ }++ /**+ * One drop by id (public projection). Not presence-gated, so for anyone but+ * the owner the location comes back coarsened to ~110 m (`coarse: true`) —+ * a leaked id never reveals the exact spot someone placed real money.+ */+ async function getDrop(id, opts = {}) {+ requireId(id, 'getDrop()');+ const res = await request(`/api/irl/drops/${encodeURIComponent(id)}`, {+ headers: deviceHeader(opts),+ signal: opts.signal,+ });+ return shapeDrop(res?.drop);+ }++ /**+ * The caller's created drops (every status) plus their claim receipts.+ * Wraps `GET /api/irl/drops?mine=1` — identity is the signed-in session or+ * the anonymous device token.+ */+ async function myDrops(opts = {}) {+ const res = await request('/api/irl/drops', {+ query: { mine: '1' },+ headers: deviceHeader(opts),+ signal: opts.signal,+ });+ return {+ drops: (res?.drops || []).map(shapeDrop),+ claims: (res?.claims || []).map(shapeClaim),+ raw: res,+ };+ }++ /**+ * Place value in the real world. Wraps `POST /api/irl/drops`.+ *+ * Two funding paths:+ * - Default: returns `{ drop (pending_funding), escrowAddress, fundAmount }` —+ * send the funds to `escrowAddress` from your own wallet, then call+ * `fundDrop({ dropId, signature })` with the transfer signature to activate.+ * - With `agentId` (signed-in owner): the agent's custodial wallet funds the+ * escrow server-side under its spend limits — returns already active with+ * `funded: true` and the on-chain `fundingTx`.+ */+ async function createDrop(input, opts = {}) {+ const p = input || {};+ const lat = Number(p.lat);+ const lng = Number(p.lng);+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {+ throw new ThreeWsError('createDrop() needs finite `lat` and `lng`.', { code: 'invalid_input' });+ }+ if (lat < -90 || lat > 90 || lng < -180 || lng > 180) {+ throw new ThreeWsError('createDrop() coordinates are out of range.', { code: 'invalid_input' });+ }+ const amount = Number(p.amount);+ if (!Number.isFinite(amount) || amount <= 0) {+ throw new ThreeWsError('createDrop() needs a positive `amount`.', { code: 'invalid_input' });+ }+ const asset = p.asset === undefined ? undefined+ : normalizeEnum(String(p.asset).toUpperCase(), DROP_ASSETS, 'asset');+ const kind = normalizeEnum(p.kind, DROP_KINDS, 'kind');+ const claimRule = normalizeEnum(p.claimRule, CLAIM_RULES, 'claimRule');+ const bountyCondition = normalizeEnum(p.bountyCondition, BOUNTY_CONDITIONS, 'bountyCondition');++ const body = prune({+ kind,+ asset,+ amount,+ maxClaims: p.maxClaims,+ claimRule,+ bountyCondition,+ quizQuestion: p.quizQuestion,+ quizAnswer: p.quizAnswer,+ title: p.title,+ note: p.note,+ lat,+ lng,+ radiusM: p.radiusM,+ expiresInMs: p.expiresInMs,+ refundAddress: p.refundAddress,+ agentId: p.agentId,+ });+ const res = await request('/api/irl/drops', {+ method: 'POST',+ body,+ headers: deviceHeader(opts),+ signal: opts.signal,+ });+ return {+ drop: shapeDrop(res?.drop),+ escrowAddress: res?.escrow_address ?? null,+ fundAtomics: res?.fund_atomics ?? null,+ fundAmount: res?.fund_amount ?? null,+ funded: Boolean(res?.funded),+ fundingTx: res?.funding_tx ?? null,+ agent: res?.agent ?? null,+ raw: res,+ };+ }++ /**+ * Confirm a user-signed funding transfer on-chain and activate the drop.+ * Wraps `POST /api/irl/drops/:id/fund`. Returns `{ pending: true }` (202)+ * while the transfer is still confirming — retry shortly.+ */+ async function fundDrop(input, opts = {}) {+ const p = input || {};+ const dropId = requireId(p.dropId ?? p.id, 'fundDrop()');+ if (!p.signature || typeof p.signature !== 'string') {+ throw new ThreeWsError('fundDrop() needs the funding transfer `signature`.', { code: 'invalid_input' });+ }+ const res = await request(`/api/irl/drops/${encodeURIComponent(dropId)}/fund`, {+ method: 'POST',+ body: prune({ signature: p.signature, refundAddress: p.refundAddress }),+ headers: deviceHeader(opts),+ signal: opts.signal,+ });+ return {+ pending: Boolean(res?.pending),+ status: res?.status ?? null,+ drop: res?.drop ? shapeDrop(res.drop) : null,+ fundingTx: res?.funding_tx ?? null,+ raw: res,+ };+ }++ /**+ * Claim a drop you are physically standing at — a real on-chain release to+ * YOUR wallet. Wraps `POST /api/irl/drops/:id/claim`; the presence token is+ * always verified, and the claimed point must be inside the drop's radius.+ * Quiz bounties also need the `answer`.+ */+ async function claimDrop(input, opts = {}) {+ const p = input || {};+ const dropId = requireId(p.dropId ?? p.id, 'claimDrop()');+ const { lat, lng, token } = presenceFix(p.presence, 'claimDrop()');+ const wallet = typeof p.wallet === 'string' ? p.wallet.trim() : '';+ if (!BASE58_RE.test(wallet)) {+ throw new ThreeWsError('claimDrop() needs a valid Solana `wallet` to receive the funds.', { code: 'invalid_input' });+ }+ const res = await request(`/api/irl/drops/${encodeURIComponent(dropId)}/claim`, {+ method: 'POST',+ body: prune({ lat, lng, wallet, answer: p.answer }),+ headers: deviceHeader(opts, fixHeader(token)),+ signal: opts.signal,+ });+ return {+ ok: Boolean(res?.ok),+ asset: res?.asset ?? null,+ amount: res?.amount ?? null,+ signature: res?.signature ?? null,+ explorerUrl: res?.explorer_url ?? null,+ wallet: res?.wallet ?? wallet,+ raw: res,+ };+ }++ /**+ * Cancel an unclaimed drop you created — a real on-chain refund sweep back+ * to your refund address. Wraps `POST /api/irl/drops/:id/cancel`. Idempotent:+ * an already-refunded drop returns `{ ok, refunded: true }` with the tx.+ */+ async function cancelDrop(id, opts = {}) {+ requireId(id, 'cancelDrop()');+ const res = await request(`/api/irl/drops/${encodeURIComponent(id)}/cancel`, {+ method: 'POST',+ headers: deviceHeader(opts),+ signal: opts.signal,+ });+ return {+ ok: Boolean(res?.ok),+ cancelled: Boolean(res?.cancelled),+ refunded: Boolean(res?.refunded),+ refundTx: res?.refund_tx ?? null,+ explorerUrl: res?.explorer_url ?? null,+ raw: res,+ };+ }++ return { nearbyDrops, getDrop, myDrops, createDrop, fundDrop, claimDrop, cancelDrop };+}++// ── Response shaping (snake_case → camelCase, with a .raw escape hatch) ──────++// A drop from the public projection (api/_lib/irl-drops.js toPublicDrop).+function shapeDrop(r) {+ if (!r || typeof r !== 'object') return r;+ return {+ id: r.id,+ kind: r.kind,+ asset: r.asset,+ amount: r.amount,+ amountAtomics: r.amount_atomics ?? null,+ maxClaims: Number(r.max_claims) || 0,+ claimsCount: Number(r.claims_count) || 0,+ claimsLeft: Number(r.claims_left) || 0,+ claimRule: r.claim_rule ?? null,+ bountyCondition: r.bounty_condition ?? null,+ quizQuestion: r.quiz_question ?? null,+ title: r.title ?? null,+ note: r.note ?? null,+ lat: r.lat,+ lng: r.lng,+ radiusM: r.radius_m ?? null,+ // Metres from your fix (nearby read only).+ distanceM: r.distance_m ?? null,+ // True when the location was coarsened to ~110 m for a non-owner id read.+ coarse: Boolean(r.coarse),+ network: r.network ?? null,+ status: r.status ?? null,+ escrowAddress: r.escrow_address ?? null,+ fundingTx: r.funding_tx ?? null,+ refundTx: r.refund_tx ?? null,+ expiresAt: r.expires_at ?? null,+ createdAt: r.created_at ?? null,+ isMine: Boolean(r.is_mine),+ raw: r,+ };+}++// A claim receipt from `myDrops().claims`.+function shapeClaim(r) {+ if (!r || typeof r !== 'object') return r;+ return {+ id: r.id,+ dropId: r.drop_id,+ title: r.title ?? null,+ kind: r.kind ?? null,+ asset: r.asset ?? null,+ amount: r.amount ?? null,+ signature: r.signature ?? null,+ status: r.status ?? null,+ network: r.network ?? null,+ createdAt: r.created_at ?? null,+ confirmedAt: r.confirmed_at ?? null,+ raw: r,+ };+}diff --git a/packages/irl/src/index.d.ts b/packages/irl/src/index.d.tsindex c2d5e0d6e..d412899de 100644--- a/packages/irl/src/index.d.ts+++ b/packages/irl/src/index.d.ts@@ -212,6 +212,316 @@ export interface IrlClientOptions {headers?: Record<string, string>;}+// ── Money Drops (real value escrowed at real-world spots) ────────────────────++export type DropKind = 'drop' | 'bounty';+export type DropAsset = 'SOL' | 'USDC' | 'THREE';+export type ClaimRule = 'first' | 'each-once' | 'quiz';+export type BountyCondition = 'presence' | 'quiz' | 'chat';+export type DropStatus = 'pending_funding' | 'active' | 'exhausted' | 'expired' | 'refunding' | 'refunded' | 'cancelled';++/** A drop from the public projection. */+export interface Drop {+ id: string;+ kind: DropKind;+ asset: DropAsset;+ /** Human-readable per-claim amount (e.g. "5" USDC). */+ amount: string | number;+ amountAtomics: string | null;+ maxClaims: number;+ claimsCount: number;+ claimsLeft: number;+ claimRule: ClaimRule | null;+ bountyCondition: BountyCondition | null;+ quizQuestion: string | null;+ title: string | null;+ note: string | null;+ lat: number;+ lng: number;+ radiusM: number | null;+ /** Metres from your fix (nearby read only). */+ distanceM: number | null;+ /** True when the location was coarsened to ~110 m for a non-owner id read. */+ coarse: boolean;+ network: string | null;+ status: DropStatus | null;+ escrowAddress: string | null;+ fundingTx: string | null;+ refundTx: string | null;+ expiresAt: string | null;+ createdAt: string | null;+ isMine: boolean;+ raw: unknown;+}++/** A claim receipt from `myDrops().claims`. */+export interface DropClaim {+ id: string;+ dropId: string;+ title: string | null;+ kind: DropKind | null;+ asset: DropAsset | null;+ amount: string | number | null;+ /** The on-chain release transaction signature. */+ signature: string | null;+ status: string | null;+ network: string | null;+ createdAt: string | null;+ confirmedAt: string | null;+ raw: unknown;+}++export interface CreateDropInput {+ /** Required. Where the value is placed. */+ lat: number;+ lng: number;+ /** Required. Per-claim amount in the asset's human units. */+ amount: number;+ /** Default `USDC`. Case-insensitive. */+ asset?: DropAsset | Lowercase<DropAsset>;+ /** Default `drop`. A `bounty` adds a completion condition. */+ kind?: DropKind;+ /** How many claims the pot covers (1–1000, default 1). */+ maxClaims?: number;+ claimRule?: ClaimRule;+ /** Bounty completion condition (default `presence`). */+ bountyCondition?: BountyCondition;+ quizQuestion?: string;+ quizAnswer?: string;+ title?: string;+ note?: string;+ /** Claim radius in metres (5–250, default 30). */+ radiusM?: number;+ expiresInMs?: number;+ /** Where a cancel/expiry refund sweeps back to. */+ refundAddress?: string;+ /** Fund server-side from this agent's custodial wallet (signed-in owner only). */+ agentId?: string;+}++export interface CreateDropResult {+ drop: Drop;+ /** Send the funds here, then call `fundDrop()` — unless `funded` is true. */+ escrowAddress: string | null;+ fundAtomics: string | null;+ fundAmount: string | number | null;+ /** True when an agent bounty was funded server-side (already active). */+ funded: boolean;+ fundingTx: string | null;+ agent: { id: string; name: string | null } | null;+ raw: unknown;+}++export interface FundDropInput {+ dropId: string;+ /** The creator-signed funding transfer signature. */+ signature: string;+ refundAddress?: string;+}++export interface ClaimDropInput {+ dropId: string;+ /** Presence from `checkIn()` at the drop's spot — always verified. */+ presence: Presence | (FixInput & { token?: string });+ /** The Solana wallet that receives the on-chain release. */+ wallet: string;+ /** Quiz bounty answer. */+ answer?: string;+}++export interface ClaimDropResult {+ ok: boolean;+ asset: DropAsset | null;+ amount: string | number | null;+ /** The on-chain release transaction signature. */+ signature: string | null;+ explorerUrl: string | null;+ wallet: string;+ raw: unknown;+}++// ── World Lines (agent-signed proof-of-presence AR quests) ───────────────────++export type ChallengeKind = 'tap' | 'quiz' | 'phrase';+export type Difficulty = 'easy' | 'medium' | 'hard';+export type RewardKind = 'collectible' | 'three_pool';++export interface ChallengeSpec {+ kind: ChallengeKind;+ prompt?: string | null;+ /** Quiz only. */+ question?: string;+ choices?: string[];+ /** Quiz only — index of the correct choice. Redacted unless co-located/owner. */+ answer?: number;+ /** Phrase only — never echoed to remote callers. */+ phrase?: string;+}++export interface WorldLine {+ id: string;+ agentId: string | null;+ /** The agent wallet that signs every proof this quest mints. */+ signerPubkey: string | null;+ pinId: string | null;+ /** ~1.1 km precision-6 cell — the only location a quest ever carries. */+ coarseCell: string | null;+ regionCell: string | null;+ title: string;+ prompt: string | null;+ /** Redacted unless you are the owner or proven co-located. */+ challenge: ChallengeSpec | null;+ rewardKind: RewardKind | null;+ rewardRef: string | null;+ difficulty: Difficulty | null;+ maxCompletions: number | null;+ completionCount: number;+ createdAt: string | null;+ expiresAt: string | null;+ /** Nearby-read extras (coarsened to 10 m). */+ distanceM: number | null;+ completedByMe: boolean;+ capacityReached: boolean;+ /** Creator-dashboard extras. */+ expired: boolean;+ hidden: boolean;+ raw: unknown;+}++export interface CreateWorldLineInput {+ /** Required. The anchor pin you own (it carries the precise spot). */+ pinId: string;+ /** Required. Content-gated; may reference only $THREE. */+ title: string;+ prompt?: string;+ /** The signing agent — defaults to the pin's agent. Must be yours. */+ agentId?: string;+ challenge?: ChallengeSpec;+ rewardKind?: RewardKind;+ /** Collectible display name (≤ 80 chars). */+ rewardRef?: string;+ difficulty?: Difficulty;+ maxCompletions?: number;+ /** 1–90 (default 30). */+ lifetimeDays?: number;+}++/** An agent-signed proof of presence. */+export interface PresenceProof {+ id: string;+ worldLineId: string | null;+ worldLineTitle: string | null;+ agentId: string | null;+ signerPubkey: string | null;+ /** ~1.1 km — the only location the proof carries. */+ coarseCell: string | null;+ signature: string | null;+ signedMessage: string | null;+ signatureScheme: string;+ collectibleMint: string | null;+ collectibleName: string | null;+ completedAt: string | null;+ verifyUrl: string | null;+ raw: unknown;+}++/** An earned proof as an ownable collectible. */+export interface Collectible {+ mint: string | null;+ name: string | null;+ kind: string;+ rewardKind: RewardKind | null;+ signerPubkey: string | null;+ signature: string | null;+ proofId: string | null;+ worldLineId: string | null;+ worldLineTitle: string | null;+ difficulty: Difficulty | null;+ coarseCell: string | null;+ earnedAt: string | null;+ verifyUrl: string | null;+ raw: unknown;+}++export interface ChallengeWorldLineInput {+ worldLineId: string;+ /** Presence from `checkIn()` at the quest — co-location is server-derived. */+ presence: Presence | (FixInput & { token?: string });+}++export interface ChallengeWorldLineResult {+ alreadyCompleted: boolean;+ /** Single-use completion nonce (absent when already completed). */+ nonce: string | null;+ expiresIn: number | null;+ /** Full challenge spec — you are proven co-located. */+ challenge: ChallengeSpec | null;+ agentId: string | null;+ worldLine: unknown | null;+ proofId?: string | null;+ collectibleMint?: string | null;+ raw: unknown;+}++export interface CompleteWorldLineInput {+ worldLineId: string;+ /** The nonce from `challengeWorldLine()`. */+ nonce: string;+ presence: Presence | (FixInput & { token?: string });+ /** Quiz — index of the chosen answer. */+ answer?: number;+ /** Phrase — the passphrase the agent asked for. */+ phrase?: string;+}++export interface CompleteWorldLineResult {+ ok: boolean;+ alreadyCompleted: boolean;+ proof: PresenceProof | null;+ collectible: Collectible | null;+ raw: unknown;+}++export interface BrowseWorldLinesOptions {+ /** A precision-5 geohash cell (from the region roll-up). */+ region?: string;+ difficulty?: Difficulty;+ signal?: AbortSignal;+}++export interface RegionRollup {+ regionCell: string;+ quests: number;+ hard: number;+ completions: number;+ raw: unknown;+}++export interface RegionQuest {+ id: string;+ title: string;+ rewardKind: RewardKind | null;+ difficulty: Difficulty | null;+ completionCount: number;+ capacityReached: boolean;+ raw: unknown;+}++export type BrowseWorldLinesResult =+ | { regions: RegionRollup[]; raw: unknown }+ | { region: string; quests: RegionQuest[]; raw: unknown };++export interface WorldLinesHeatCell {+ worldLineId: string;+ coarseCell: string;+ completions: number;+}++export interface GetWorldLineOptions extends WriteOptions {+ /** Pass your presence to prove co-location and receive the full challenge. */+ presence?: Presence | (FixInput & { token?: string });+}+export interface IrlClient {checkIn(input?: FixInput, opts?: CheckInOptions): Promise<Presence>;nearby(presence: Presence | FixInput, opts?: NearbyOptions): Promise<Pin[]>;@@ -220,6 +530,24 @@ export interface IrlClient {interact(input: InteractInput, opts?: WriteOptions): Promise<Interaction>;removePin(id: string, opts?: WriteOptions): Promise<{ ok: boolean; raw: unknown }>;purgePins(opts?: WriteOptions): Promise<{ ok: boolean; deleted: number; raw: unknown }>;+ // Money Drops+ nearbyDrops(presence: Presence | FixInput, opts?: NearbyOptions): Promise<Drop[]>;+ getDrop(id: string, opts?: WriteOptions): Promise<Drop>;+ myDrops(opts?: WriteOptions): Promise<{ drops: Drop[]; claims: DropClaim[]; raw: unknown }>;+ createDrop(input: CreateDropInput, opts?: WriteOptions): Promise<CreateDropResult>;+ fundDrop(input: FundDropInput, opts?: WriteOptions): Promise<{ pending: boolean; status: string | null; drop: Drop | null; fundingTx: string | null; raw: unknown }>;+ claimDrop(input: ClaimDropInput, opts?: WriteOptions): Promise<ClaimDropResult>;+ cancelDrop(id: string, opts?: WriteOptions): Promise<{ ok: boolean; cancelled: boolean; refunded: boolean; refundTx: string | null; explorerUrl: string | null; raw: unknown }>;+ // World Lines+ nearbyWorldLines(presence: Presence | FixInput, opts?: NearbyOptions): Promise<WorldLine[]>;+ browseWorldLines(opts?: BrowseWorldLinesOptions): Promise<BrowseWorldLinesResult>;+ getWorldLine(id: string, opts?: GetWorldLineOptions): Promise<{ worldLine: WorldLine; colocated: boolean; raw: unknown }>;+ createWorldLine(input: CreateWorldLineInput, opts?: { signal?: AbortSignal }): Promise<{ worldLine: WorldLine; raw: unknown }>;+ myWorldLines(opts?: { signal?: AbortSignal }): Promise<{ worldLines: WorldLine[]; heatmap: WorldLinesHeatCell[]; raw: unknown }>;+ myCollectibles(opts?: WriteOptions): Promise<Collectible[]>;+ challengeWorldLine(input: ChallengeWorldLineInput, opts?: WriteOptions): Promise<ChallengeWorldLineResult>;+ completeWorldLine(input: CompleteWorldLineInput, opts?: WriteOptions): Promise<CompleteWorldLineResult>;+ verifyProof(proofId: string, opts?: { signal?: AbortSignal }): Promise<{ verified: boolean; proof: PresenceProof | null; raw: unknown }>;}export declare function createIrl(options?: IrlClientOptions): IrlClient;@@ -233,5 +561,23 @@ export declare function interact(input: InteractInput, opts?: WriteOptions): Proexport declare function removePin(id: string, opts?: WriteOptions): Promise<{ ok: boolean; raw: unknown }>;export declare function purgePins(opts?: WriteOptions): Promise<{ ok: boolean; deleted: number; raw: unknown }>;+export declare function nearbyDrops(presence: Presence | FixInput, opts?: NearbyOptions): Promise<Drop[]>;+export declare function getDrop(id: string, opts?: WriteOptions): Promise<Drop>;+export declare function myDrops(opts?: WriteOptions): Promise<{ drops: Drop[]; claims: DropClaim[]; raw: unknown }>;+export declare function createDrop(input: CreateDropInput, opts?: WriteOptions): Promise<CreateDropResult>;+export declare function fundDrop(input: FundDropInput, opts?: WriteOptions): Promise<{ pending: boolean; status: string | null; drop: Drop | null; fundingTx: string | null; raw: unknown }>;+export declare function claimDrop(input: ClaimDropInput, opts?: WriteOptions): Promise<ClaimDropResult>;+export declare function cancelDrop(id: string, opts?: WriteOptions): Promise<{ ok: boolean; cancelled: boolean; refunded: boolean; refundTx: string | null; explorerUrl: string | null; raw: unknown }>;++export declare function nearbyWorldLines(presence: Presence | FixInput, opts?: NearbyOptions): Promise<WorldLine[]>;+export declare function browseWorldLines(opts?: BrowseWorldLinesOptions): Promise<BrowseWorldLinesResult>;+export declare function getWorldLine(id: string, opts?: GetWorldLineOptions): Promise<{ worldLine: WorldLine; colocated: boolean; raw: unknown }>;+export declare function createWorldLine(input: CreateWorldLineInput, opts?: { signal?: AbortSignal }): Promise<{ worldLine: WorldLine; raw: unknown }>;+export declare function myWorldLines(opts?: { signal?: AbortSignal }): Promise<{ worldLines: WorldLine[]; heatmap: WorldLinesHeatCell[]; raw: unknown }>;+export declare function myCollectibles(opts?: WriteOptions): Promise<Collectible[]>;+export declare function challengeWorldLine(input: ChallengeWorldLineInput, opts?: WriteOptions): Promise<ChallengeWorldLineResult>;+export declare function completeWorldLine(input: CompleteWorldLineInput, opts?: WriteOptions): Promise<CompleteWorldLineResult>;+export declare function verifyProof(proofId: string, opts?: { signal?: AbortSignal }): Promise<{ verified: boolean; proof: PresenceProof | null; raw: unknown }>;+/** Encode a lat/lng to a geohash (default precision 7, the IRL cell key). */export declare function encodeGeohash(lat: number, lng: number, precision?: number): string;diff --git a/packages/irl/src/index.js b/packages/irl/src/index.jsindex 9dc1a248a..17d15bef6 100644--- a/packages/irl/src/index.js+++ b/packages/irl/src/index.js@@ -6,6 +6,9 @@// are actually standing at.import { createHttp, ThreeWsError } from './http.js';+import { prune, normToken, normalizeEnum, presenceFix, fixHeader } from './shared.js';+import { createDropsApi } from './drops.js';+import { createWorldLinesApi } from './world-lines.js';export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';@@ -87,10 +90,9 @@ export function createIrl(options = {}) {* `x-irl-fix` header. Only answers for the coarse area the token was minted in.*/async function nearby(presence, opts = {}) {- const { lat, lng, token } = presenceFix(presence);- const headers = { ...(opts.headers || {}) };+ const { lat, lng, token } = presenceFix(presence, 'nearby()');// The fix token rides a header, gating the read to a genuine presence.- if (token) headers['x-irl-fix'] = token;+ const headers = fixHeader(token, opts.headers);const radius = opts.radius;if (radius !== undefined && !Number.isFinite(radius)) {throw new ThreeWsError('nearby() radius must be a finite number of metres.', { code: 'invalid_input' });@@ -225,7 +227,12 @@ export function createIrl(options = {}) {return { ok: Boolean(res?.ok), deleted: Number(res?.deleted) || 0, raw: res };}- return { checkIn, nearby, placePin, myPins, interact, removePin, purgePins };+ // Money Drops & World Lines — the same request core, device token, and+ // presence contract, wrapped for /api/irl/drops and /api/irl/world-lines.+ const drops = createDropsApi({ request, deviceHeader });+ const worldLines = createWorldLinesApi({ request, deviceHeader });++ return { checkIn, nearby, placePin, myPins, interact, removePin, purgePins, ...drops, ...worldLines };}// ── Default zero-config client (the `import { checkIn }` path) ───────────────@@ -277,6 +284,76 @@ export function purgePins(opts) {return defaultClient().purgePins(opts);}+// ── Money Drops (real value escrowed at real-world spots) ────────────────────++/** Live drops within the radius of where you checked in (presence-gated). */+export function nearbyDrops(presence, opts) {+ return defaultClient().nearbyDrops(presence, opts);+}+/** One drop by id — coarse (~110 m) location for anyone but the owner. */+export function getDrop(id, opts) {+ return defaultClient().getDrop(id, opts);+}+/** Your created drops (every status) plus your claim receipts. */+export function myDrops(opts) {+ return defaultClient().myDrops(opts);+}+/** Place value in the real world — returns the escrow address to fund. */+export function createDrop(input, opts) {+ return defaultClient().createDrop(input, opts);+}+/** Confirm your signed funding transfer on-chain and activate the drop. */+export function fundDrop(input, opts) {+ return defaultClient().fundDrop(input, opts);+}+/** Claim a drop you are standing at — a real on-chain release to your wallet. */+export function claimDrop(input, opts) {+ return defaultClient().claimDrop(input, opts);+}+/** Cancel an unclaimed drop you created — a real on-chain refund sweep. */+export function cancelDrop(id, opts) {+ return defaultClient().cancelDrop(id, opts);+}++// ── World Lines (agent-signed proof-of-presence AR quests) ──────────────────++/** Quests near where you checked in (fix-gated; distance coarsened to 10 m). */+export function nearbyWorldLines(presence, opts) {+ return defaultClient().nearbyWorldLines(presence, opts);+}+/** Public, coordinate-free discovery — region roll-up or one region's quests. */+export function browseWorldLines(opts) {+ return defaultClient().browseWorldLines(opts);+}+/** One quest for the AR detail view — full challenge only when co-located. */+export function getWorldLine(id, opts) {+ return defaultClient().getWorldLine(id, opts);+}+/** Place a quest anchored to a pin you own, signed by an agent you own. */+export function createWorldLine(input, opts) {+ return defaultClient().createWorldLine(input, opts);+}+/** Your placed quests + a coarse completion heatmap (signed-in). */+export function myWorldLines(opts) {+ return defaultClient().myWorldLines(opts);+}+/** The proof-of-presence collectibles you've earned. */+export function myCollectibles(opts) {+ return defaultClient().myCollectibles(opts);+}+/** Start a completion at the spot — issues the single-use nonce. */+export function challengeWorldLine(input, opts) {+ return defaultClient().challengeWorldLine(input, opts);+}+/** Finish the interaction and receive the agent-signed proof collectible. */+export function completeWorldLine(input, opts) {+ return defaultClient().completeWorldLine(input, opts);+}+/** Independently re-verify a proof's agent signature (public). */+export function verifyProof(proofId, opts) {+ return defaultClient().verifyProof(proofId, opts);+}+// ── Fix resolution ──────────────────────────────────────────────────────────// Resolve a fix to { lat, lng, accuracy? } from an explicit object, a presence@@ -311,18 +388,6 @@ function readBrowserFix() {});}-// Pull { lat, lng, token } from a presence object (from checkIn) or a bare-// { lat, lng } fix. The token is optional — dev/preview reads work without it.-function presenceFix(presence) {- const p = presence || {};- const lat = Number(p.lat);- const lng = Number(p.lng);- if (!Number.isFinite(lat) || !Number.isFinite(lng)) {- throw new ThreeWsError('nearby() needs a presence from checkIn() (or a `{ lat, lng }` fix).', { code: 'invalid_input' });- }- return { lat, lng, token: typeof p.token === 'string' ? p.token : null };-}-// ── Response shaping (snake_case → camelCase, with a .raw escape hatch) ──────// A pin from the public nearby feed — the allow-list projection (never user_id@@ -399,32 +464,6 @@ function shapeInteraction(res) {};}-// ── Helpers (mirror forge's shared style) ───────────────────────────────────--function normalizeEnum(value, allowed, label) {- if (value === undefined || value === null) return undefined;- if (!allowed.includes(value)) {- throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });- }- return value;-}--function normToken(v) {- if (typeof v !== 'string') return null;- const t = v.trim();- return t.length ? t : null;-}--function prune(obj) {- const out = {};- for (const [k, v] of Object.entries(obj)) {- if (v === undefined || v === null) continue;- if (Array.isArray(v) && v.length === 0) continue;- out[k] = v;- }- return out;-}-// Geohash encoder — identical lattice to api/_lib/geohash.js so a fix maps to the// same precision-7 cell the server keys on. Used as the local fallback for a// presence cell and to compare cells across a walk-up poll.diff --git a/packages/irl/src/shared.js b/packages/irl/src/shared.jsnew file mode 100644index 000000000..81c268bed--- /dev/null+++ b/packages/irl/src/shared.js@@ -0,0 +1,55 @@+// Internal helpers shared by the pin, drop, and world-line modules. Not part of+// the public API surface — import from './index.js' instead.++import { ThreeWsError } from './http.js';++export function normalizeEnum(value, allowed, label) {+ if (value === undefined || value === null) return undefined;+ if (!allowed.includes(value)) {+ throw new ThreeWsError(`Invalid ${label} "${value}". Expected one of: ${allowed.join(', ')}.`, { code: 'invalid_input' });+ }+ return value;+}++export function normToken(v) {+ if (typeof v !== 'string') return null;+ const t = v.trim();+ return t.length ? t : null;+}++export function prune(obj) {+ const out = {};+ for (const [k, v] of Object.entries(obj)) {+ if (v === undefined || v === null) continue;+ if (Array.isArray(v) && v.length === 0) continue;+ out[k] = v;+ }+ return out;+}++// Pull { lat, lng, token } from a presence object (from checkIn) or a bare+// { lat, lng } fix. The token is optional — dev/preview reads work without it.+export function presenceFix(presence, label = 'this call') {+ const p = presence || {};+ const lat = Number(p.lat);+ const lng = Number(p.lng);+ if (!Number.isFinite(lat) || !Number.isFinite(lng)) {+ throw new ThreeWsError(`${label} needs a presence from checkIn() (or a \`{ lat, lng }\` fix).`, { code: 'invalid_input' });+ }+ return { lat, lng, token: typeof p.token === 'string' ? p.token : null };+}++// Attach the presence token as the x-irl-fix header proof-of-presence reads and+// writes are gated on.+export function fixHeader(token, extra) {+ const h = { ...(extra || {}) };+ if (token) h['x-irl-fix'] = token;+ return h;+}++export function requireId(id, label) {+ if (!id || typeof id !== 'string') {+ throw new ThreeWsError(`${label} needs an id.`, { code: 'invalid_input' });+ }+ return id;+}diff --git a/packages/irl/src/world-lines.js b/packages/irl/src/world-lines.jsnew file mode 100644index 000000000..b629b48f6--- /dev/null+++ b/packages/irl/src/world-lines.js@@ -0,0 +1,351 @@+// IRL World Lines — the SDK twin of /api/irl/world-lines. Agent-placed+// proof-of-presence AR quests: travel to the spot, prove co-location with the+// same fix token every IRL read enforces, finish the interaction, and the+// agent's own wallet signs an independently verifiable, ownable proof — without+// a precise coordinate ever entering the proof.++import { ThreeWsError } from './http.js';+import { presenceFix, fixHeader, prune, normalizeEnum, requireId } from './shared.js';++const CHALLENGE_KINDS = ['tap', 'quiz', 'phrase'];+const DIFFICULTIES = ['easy', 'medium', 'hard'];+const REWARD_KINDS = ['collectible', 'three_pool'];+// A ~5 km region cell is a precision-5 geohash (browse aggregation unit).+const REGION_RE = /^[0-9bcdefghjkmnpqrstuvwxyz]{5}$/;++/**+ * Build the world-lines slice of the IRL client. `request` is the bound HTTP+ * core and `deviceHeader` merges the caller's anonymous device token in.+ */+export function createWorldLinesApi({ request, deviceHeader }) {+ /**+ * Quests near where you checked in. Wraps `GET /api/irl/world-lines/nearby`+ * with the presence token in `x-irl-fix`. Discovery is deliberately wider+ * than the 60 m pin read (default 250 m, max 600 m) so a walker can head+ * toward a quest; distance comes back coarsened to 10 m.+ */+ async function nearbyWorldLines(presence, opts = {}) {+ const { lat, lng, token } = presenceFix(presence, 'nearbyWorldLines()');+ const radius = opts.radius;+ if (radius !== undefined && !Number.isFinite(radius)) {+ throw new ThreeWsError('nearbyWorldLines() radius must be a finite number of metres.', { code: 'invalid_input' });+ }+ const res = await request('/api/irl/world-lines/nearby', {+ query: { lat, lng, radius },+ headers: deviceHeader(opts, fixHeader(token, opts.headers)),+ signal: opts.signal,+ });+ return (res?.world_lines || []).map(shapeWorldLine);+ }++ /**+ * Public, coordinate-free discovery. With no arguments: the region roll-up —+ * how many active quests per ~5 km region cell. With `{ region }` (a+ * precision-5 geohash from the roll-up): that region's quest list, optionally+ * filtered by `{ difficulty }`. Never carries a location beyond the region cell.+ */+ async function browseWorldLines(opts = {}) {+ const region = opts.region;+ if (region !== undefined && !REGION_RE.test(String(region))) {+ throw new ThreeWsError('browseWorldLines() region must be a precision-5 geohash cell (from the region roll-up).', { code: 'invalid_input' });+ }+ const difficulty = opts.difficulty === undefined ? undefined+ : normalizeEnum(opts.difficulty, DIFFICULTIES, 'difficulty');+ const res = await request('/api/irl/world-lines/browse', {+ query: { region, difficulty },+ signal: opts.signal,+ });+ if (region) {+ return {+ region: res?.region ?? region,+ quests: (res?.quests || []).map((q) => ({+ id: q.id,+ title: q.title,+ rewardKind: q.reward_kind ?? null,+ difficulty: q.difficulty ?? null,+ completionCount: Number(q.completion_count) || 0,+ capacityReached: Boolean(q.capacity_reached),+ raw: q,+ })),+ raw: res,+ };+ }+ return {+ regions: (res?.regions || []).map((r) => ({+ regionCell: r.region_cell,+ quests: Number(r.quests) || 0,+ hard: Number(r.hard) || 0,+ completions: Number(r.completions) || 0,+ raw: r,+ })),+ raw: res,+ };+ }++ /**+ * One World Line for the AR detail view. Pass your `presence` to prove+ * co-location — a co-located caller gets the full challenge spec (quiz+ * answer included, so the interaction can grade locally); a remote caller+ * gets a redacted spec plus the coarse cell for the "travel here" state.+ */+ async function getWorldLine(id, opts = {}) {+ requireId(id, 'getWorldLine()');+ let query;+ let headers = deviceHeader(opts);+ if (opts.presence) {+ const { lat, lng, token } = presenceFix(opts.presence, 'getWorldLine()');+ query = { lat, lng };+ headers = deviceHeader(opts, fixHeader(token));+ }+ const res = await request(`/api/irl/world-lines/${encodeURIComponent(id)}`, {+ query,+ headers,+ signal: opts.signal,+ });+ return { worldLine: shapeWorldLine(res?.world_line), colocated: Boolean(res?.colocated), raw: res };+ }++ /**+ * Place a quest anchored to a pin you own, signed by an agent you own.+ * Wraps `POST /api/irl/world-lines`. Requires a signed-in identity — pass+ * `apiKey` to `createIrl()` (bearer sessions are CSRF-exempt); the agent's+ * custodial wallet signs every proof this quest mints.+ */+ async function createWorldLine(input, opts = {}) {+ const p = input || {};+ const pinId = requireId(p.pinId, 'createWorldLine() (`pinId` — the anchor pin you own)');+ const title = typeof p.title === 'string' ? p.title.trim() : '';+ if (!title) throw new ThreeWsError('createWorldLine() needs a `title`.', { code: 'invalid_input' });++ const challenge = normalizeChallengeInput(p.challenge);+ const difficulty = normalizeEnum(p.difficulty, DIFFICULTIES, 'difficulty');+ const rewardKind = normalizeEnum(p.rewardKind, REWARD_KINDS, 'rewardKind');++ const res = await request('/api/irl/world-lines', {+ method: 'POST',+ body: prune({+ pinId,+ agentId: p.agentId,+ title,+ prompt: p.prompt,+ challenge,+ rewardKind,+ // The endpoint reads these two in snake_case only.+ reward_ref: p.rewardRef,+ difficulty,+ maxCompletions: p.maxCompletions,+ lifetime_days: p.lifetimeDays,+ }),+ signal: opts.signal,+ });+ return { worldLine: shapeWorldLine(res?.world_line), raw: res };+ }++ /** Your placed quests + a coarse completion heatmap. Wraps `GET /mine` (signed-in). */+ async function myWorldLines(opts = {}) {+ const res = await request('/api/irl/world-lines/mine', {+ signal: opts.signal,+ });+ return {+ worldLines: (res?.world_lines || []).map(shapeWorldLine),+ heatmap: (res?.heatmap || []).map((h) => ({+ worldLineId: h.world_line_id,+ coarseCell: h.coarse_cell,+ completions: Number(h.completions) || 0,+ })),+ raw: res,+ };+ }++ /**+ * The proofs you've earned, as ownable collectibles. Wraps+ * `GET /api/irl/world-lines/collectibles` — scoped to your session or your+ * anonymous device token.+ */+ async function myCollectibles(opts = {}) {+ const res = await request('/api/irl/world-lines/collectibles', {+ headers: deviceHeader(opts),+ signal: opts.signal,+ });+ return (res?.collectibles || []).map(shapeCollectible);+ }++ /**+ * Start a completion at the spot: issues a single-use nonce and reveals the+ * full challenge (you are proven co-located). Wraps `POST /challenge`.+ * Returns `{ alreadyCompleted: true, proofId }` if you've done this quest.+ */+ async function challengeWorldLine(input, opts = {}) {+ const p = input || {};+ const worldLineId = requireId(p.worldLineId ?? p.id, 'challengeWorldLine()');+ const { lat, lng, token } = presenceFix(p.presence, 'challengeWorldLine()');+ const res = await request('/api/irl/world-lines/challenge', {+ method: 'POST',+ body: { world_line_id: worldLineId, lat, lng },+ headers: deviceHeader(opts, fixHeader(token)),+ signal: opts.signal,+ });+ if (res?.already_completed) {+ return {+ alreadyCompleted: true,+ proofId: res.proof_id ?? null,+ collectibleMint: res.collectible_mint ?? null,+ raw: res,+ };+ }+ return {+ alreadyCompleted: false,+ nonce: res?.nonce ?? null,+ expiresIn: res?.expires_in ?? null,+ challenge: res?.challenge ?? null,+ agentId: res?.agent_id ?? null,+ worldLine: res?.world_line ?? null,+ raw: res,+ };+ }++ /**+ * The proof ceremony: finish the interaction at the spot and receive the+ * agent-signed, independently verifiable proof-of-presence collectible.+ * Wraps `POST /complete` — co-location is re-proven, the nonce must be the+ * one `challengeWorldLine()` issued, and quiz/phrase challenges are graded+ * server-side (`answer` is the quiz choice index, `phrase` the passphrase).+ */+ async function completeWorldLine(input, opts = {}) {+ const p = input || {};+ const worldLineId = requireId(p.worldLineId ?? p.id, 'completeWorldLine()');+ if (!p.nonce || typeof p.nonce !== 'string') {+ throw new ThreeWsError('completeWorldLine() needs the `nonce` from challengeWorldLine().', { code: 'invalid_input' });+ }+ const { lat, lng, token } = presenceFix(p.presence, 'completeWorldLine()');+ const res = await request('/api/irl/world-lines/complete', {+ method: 'POST',+ body: prune({ world_line_id: worldLineId, nonce: p.nonce, lat, lng, answer: p.answer, phrase: p.phrase }),+ headers: deviceHeader(opts, fixHeader(token)),+ signal: opts.signal,+ });+ return {+ ok: Boolean(res?.ok || res?.already_completed),+ alreadyCompleted: Boolean(res?.already_completed),+ proof: shapeProof(res?.proof),+ collectible: shapeCollectible(res?.collectible),+ raw: res,+ };+ }++ /**+ * Independently re-verify a proof's agent signature — the same public check+ * anyone can run. Wraps `GET /api/irl/world-lines/verify/:proofId`.+ */+ async function verifyProof(proofId, opts = {}) {+ requireId(proofId, 'verifyProof()');+ const res = await request(`/api/irl/world-lines/verify/${encodeURIComponent(proofId)}`, {+ signal: opts.signal,+ });+ return { verified: Boolean(res?.verified), proof: shapeProof(res?.proof), raw: res };+ }++ return {+ nearbyWorldLines, browseWorldLines, getWorldLine, createWorldLine,+ myWorldLines, myCollectibles, challengeWorldLine, completeWorldLine, verifyProof,+ };+}++// Mirror the server's normalizeChallengeSpec preconditions client-side so a+// malformed quest fails fast with a clear message instead of a 400 round-trip.+function normalizeChallengeInput(raw) {+ if (raw === undefined || raw === null) return undefined; // server defaults to 'tap'+ if (typeof raw !== 'object' || Array.isArray(raw)) {+ throw new ThreeWsError('challenge must be an object like { kind: "tap" | "quiz" | "phrase", ... }.', { code: 'invalid_input' });+ }+ const kind = raw.kind === undefined ? 'tap' : normalizeEnum(raw.kind, CHALLENGE_KINDS, 'challenge.kind');+ if (kind === 'quiz') {+ if (!raw.question || typeof raw.question !== 'string') {+ throw new ThreeWsError('a quiz challenge needs a `question`.', { code: 'invalid_input' });+ }+ if (!Array.isArray(raw.choices) || raw.choices.filter(Boolean).length < 2) {+ throw new ThreeWsError('a quiz challenge needs at least two `choices`.', { code: 'invalid_input' });+ }+ if (!Number.isInteger(raw.answer) || raw.answer < 0 || raw.answer >= raw.choices.length) {+ throw new ThreeWsError('a quiz challenge needs `answer` — the index of the correct choice.', { code: 'invalid_input' });+ }+ }+ if (kind === 'phrase' && (!raw.phrase || typeof raw.phrase !== 'string')) {+ throw new ThreeWsError('a phrase challenge needs the `phrase` passphrase.', { code: 'invalid_input' });+ }+ return { ...raw, kind };+}++// ── Response shaping (snake_case → camelCase, with a .raw escape hatch) ──────++function shapeWorldLine(r) {+ if (!r || typeof r !== 'object') return r;+ return {+ id: r.id,+ agentId: r.agent_id ?? null,+ signerPubkey: r.signer_pubkey ?? null,+ pinId: r.pin_id ?? null,+ // ~1.1 km precision-6 cell — the only location a quest ever carries.+ coarseCell: r.coarse_cell ?? null,+ regionCell: r.region_cell ?? null,+ title: r.title,+ prompt: r.prompt ?? null,+ // Redacted unless you are the owner or proven co-located.+ challenge: r.challenge ?? null,+ rewardKind: r.reward_kind ?? null,+ rewardRef: r.reward_ref ?? null,+ difficulty: r.difficulty ?? null,+ maxCompletions: r.max_completions ?? null,+ completionCount: Number(r.completion_count) || 0,+ createdAt: r.created_at ?? null,+ expiresAt: r.expires_at ?? null,+ // Nearby-read extras (absent elsewhere).+ distanceM: r.distance_m ?? null,+ completedByMe: Boolean(r.completed_by_me),+ capacityReached: Boolean(r.capacity_reached),+ // Creator-dashboard extras (absent elsewhere).+ expired: Boolean(r.expired),+ hidden: Boolean(r.hidden),+ raw: r,+ };+}++function shapeProof(p) {+ if (!p || typeof p !== 'object') return p ?? null;+ return {+ id: p.id,+ worldLineId: p.world_line_id ?? null,+ worldLineTitle: p.world_line_title ?? null,+ agentId: p.agent_id ?? null,+ signerPubkey: p.signer_pubkey ?? null,+ coarseCell: p.coarse_cell ?? null,+ signature: p.signature ?? null,+ signedMessage: p.signed_message ?? null,+ signatureScheme: p.signature_scheme ?? 'ed25519',+ collectibleMint: p.collectible_mint ?? null,+ collectibleName: p.collectible_name ?? null,+ completedAt: p.completed_at ?? null,+ verifyUrl: p.verify_url ?? null,+ raw: p,+ };+}++function shapeCollectible(c) {+ if (!c || typeof c !== 'object') return c ?? null;+ return {+ mint: c.mint ?? null,+ name: c.name ?? null,+ kind: c.kind ?? 'proof-of-presence',+ rewardKind: c.reward_kind ?? null,+ signerPubkey: c.signer_pubkey ?? null,+ signature: c.signature ?? null,+ proofId: c.proof_id ?? null,+ worldLineId: c.world_line_id ?? null,+ worldLineTitle: c.world_line_title ?? null,+ difficulty: c.difficulty ?? null,+ coarseCell: c.coarse_cell ?? null,+ earnedAt: c.earned_at ?? null,+ verifyUrl: c.verify_url ?? null,+ raw: c,+ };+}diff --git a/packages/irl/test/drops.test.js b/packages/irl/test/drops.test.jsnew file mode 100644index 000000000..dcd1e2889--- /dev/null+++ b/packages/irl/test/drops.test.js@@ -0,0 +1,208 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createIrl, ThreeWsError } from '../src/index.js';++// Same scripted fetch double as irl.test.js: queued responses, recorded calls.+// No network — the SDK's job is request shaping and response parsing.+function stubFetch(responses) {+ const calls = [];+ const queue = [...responses];+ const fetch = async (url, init) => {+ calls.push({ url: new URL(url), init });+ const next = queue.shift();+ if (!next) throw new Error('stubFetch: no more queued responses');+ const { status = 200, body = {}, headers = {} } = next;+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (k) => headers[k.toLowerCase()] ?? null },+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),+ };+ };+ return { fetch, calls };+}++const PUBLIC_DROP = {+ id: 'd1', kind: 'drop', asset: 'USDC', amount: '5', amount_atomics: '5000000',+ max_claims: 5, claims_count: 2, claims_left: 3, claim_rule: 'each-once',+ bounty_condition: null, quiz_question: null, title: 'Coffee money', note: null,+ lat: 40.74110, lng: -73.98970, radius_m: 30, network: 'mainnet', status: 'active',+ escrow_address: 'EscRoW1111111111111111111111111111111111111', funding_tx: 'sig1',+ refund_tx: null, expires_at: '2026-07-10T00:00:00Z', created_at: '2026-07-09T00:00:00Z',+ is_mine: false, distance_m: 14,+};++test('nearbyDrops() sends the fix token and shapes drops to camelCase', async () => {+ const { fetch, calls } = stubFetch([{ body: { drops: [PUBLIC_DROP] } }]);+ const client = createIrl({ fetch });+ const presence = { lat: 40.7411, lng: -73.9897, token: 'tok.sig' };+ const drops = await client.nearbyDrops(presence, { radius: 60 });++ assert.equal(calls[0].url.pathname, '/api/irl/drops');+ assert.equal(calls[0].url.searchParams.get('lat'), '40.7411');+ assert.equal(calls[0].url.searchParams.get('radius'), '60');+ assert.equal(calls[0].init.headers['x-irl-fix'], 'tok.sig');+ assert.equal(drops.length, 1);+ assert.equal(drops[0].claimsLeft, 3);+ assert.equal(drops[0].claimRule, 'each-once');+ assert.equal(drops[0].escrowAddress, PUBLIC_DROP.escrow_address);+ assert.equal(drops[0].distanceM, 14);+ assert.equal(drops[0].isMine, false);+ assert.equal(drops[0].raw.amount_atomics, '5000000');+});++test('getDrop() surfaces the coarse flag on a non-owner read', async () => {+ const { fetch, calls } = stubFetch([+ { body: { drop: { ...PUBLIC_DROP, lat: 40.741, lng: -73.99, coarse: true, distance_m: undefined } } },+ ]);+ const client = createIrl({ fetch });+ const drop = await client.getDrop('d1');+ assert.equal(calls[0].url.pathname, '/api/irl/drops/d1');+ assert.equal(drop.coarse, true);+ assert.equal(drop.lat, 40.741);+});++test('myDrops() reads ?mine=1 and shapes claim receipts', async () => {+ const { fetch, calls } = stubFetch([+ { body: {+ drops: [{ ...PUBLIC_DROP, is_mine: true }],+ claims: [{ id: '7', drop_id: 'd2', title: 'Scout bounty', kind: 'bounty', asset: 'SOL',+ amount: '0.1', signature: 'claimsig', status: 'confirmed', network: 'mainnet',+ created_at: '2026-07-08T00:00:00Z', confirmed_at: '2026-07-08T00:00:10Z' }],+ } },+ ]);+ const client = createIrl({ fetch, deviceToken: 'dev-1' });+ const { drops, claims } = await client.myDrops();+ assert.equal(calls[0].url.searchParams.get('mine'), '1');+ assert.equal(calls[0].init.headers['x-irl-device'], 'dev-1');+ assert.equal(drops[0].isMine, true);+ assert.equal(claims[0].dropId, 'd2');+ assert.equal(claims[0].confirmedAt, '2026-07-08T00:00:10Z');+});++test('createDrop() posts the config and returns the escrow funding target', async () => {+ const { fetch, calls } = stubFetch([+ { status: 201, body: {+ drop: { ...PUBLIC_DROP, status: 'pending_funding', is_mine: true },+ escrow_address: 'EscRoW1111111111111111111111111111111111111',+ fund_atomics: '5000000', fund_amount: '5',+ } },+ ]);+ const client = createIrl({ fetch, deviceToken: 'dev-1' });+ const out = await client.createDrop({+ asset: 'usdc', amount: 5, maxClaims: 5, claimRule: 'each-once',+ title: 'Coffee money', lat: 40.7411, lng: -73.9897, radiusM: 30,+ });+ assert.equal(calls[0].init.method, 'POST');+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.asset, 'USDC', 'asset is upper-cased before send');+ assert.equal(sent.maxClaims, 5);+ assert.equal(out.escrowAddress, 'EscRoW1111111111111111111111111111111111111');+ assert.equal(out.fundAmount, '5');+ assert.equal(out.funded, false);+ assert.equal(out.drop.status, 'pending_funding');+});++test('createDrop() with agentId returns the server-funded bounty state', async () => {+ const { fetch } = stubFetch([+ { status: 201, body: {+ drop: { ...PUBLIC_DROP, kind: 'bounty', status: 'active', is_mine: true },+ escrow_address: 'EscRoW1111111111111111111111111111111111111',+ funding_tx: 'agentfundsig', funded: true,+ agent: { id: 'a1', name: 'Scout' },+ } },+ ]);+ const client = createIrl({ fetch, apiKey: 'sess' });+ const out = await client.createDrop({+ agentId: 'a1', kind: 'bounty', asset: 'SOL', amount: 0.1,+ lat: 40.7411, lng: -73.9897, bountyCondition: 'quiz',+ quizQuestion: 'What is the only coin?', quizAnswer: '$THREE',+ });+ assert.equal(out.funded, true);+ assert.equal(out.fundingTx, 'agentfundsig');+ assert.equal(out.agent.name, 'Scout');+});++test('createDrop() validates coordinates, amount, and enums before the network', async () => {+ const { fetch, calls } = stubFetch([]);+ const client = createIrl({ fetch });+ await assert.rejects(() => client.createDrop({ amount: 5 }), /finite/);+ await assert.rejects(() => client.createDrop({ lat: 1, lng: 2, amount: 0 }), /positive/);+ await assert.rejects(() => client.createDrop({ lat: 1, lng: 2, amount: 1, asset: 'DOGE' }), /Invalid asset/);+ await assert.rejects(() => client.createDrop({ lat: 1, lng: 2, amount: 1, claimRule: 'always' }), /Invalid claimRule/);+ assert.equal(calls.length, 0);+});++test('fundDrop() posts the transfer signature and surfaces the 202 pending state', async () => {+ const { fetch, calls } = stubFetch([+ { status: 202, body: { pending: true, status: 'pending_funding' } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.fundDrop({ dropId: 'd1', signature: 'fundsig' });+ assert.equal(calls[0].url.pathname, '/api/irl/drops/d1/fund');+ assert.equal(JSON.parse(calls[0].init.body).signature, 'fundsig');+ assert.equal(out.pending, true);+ await assert.rejects(() => client.fundDrop({ dropId: 'd1' }), /signature/);+});++test('claimDrop() proves presence in the header, posts the point + wallet, returns the release', async () => {+ const wallet = 'C1aimWa11et111111111111111111111111111111111';+ const { fetch, calls } = stubFetch([+ { body: { ok: true, asset: 'USDC', amount: '1', signature: 'releasesig',+ explorer_url: 'https://solscan.io/tx/releasesig', wallet } },+ ]);+ const client = createIrl({ fetch, deviceToken: 'dev-1' });+ const out = await client.claimDrop({+ dropId: 'd1',+ presence: { lat: 40.7411, lng: -73.9897, token: 'tok.sig' },+ wallet,+ answer: '$THREE',+ });+ assert.equal(calls[0].url.pathname, '/api/irl/drops/d1/claim');+ assert.equal(calls[0].init.headers['x-irl-fix'], 'tok.sig');+ assert.equal(calls[0].init.headers['x-irl-device'], 'dev-1');+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.wallet, wallet);+ assert.equal(sent.lat, 40.7411);+ assert.equal(sent.answer, '$THREE');+ assert.equal(out.ok, true);+ assert.equal(out.signature, 'releasesig');+ assert.equal(out.explorerUrl, 'https://solscan.io/tx/releasesig');+});++test('claimDrop() rejects a malformed wallet and a missing presence before the network', async () => {+ const { fetch, calls } = stubFetch([]);+ const client = createIrl({ fetch });+ await assert.rejects(+ () => client.claimDrop({ dropId: 'd1', presence: { lat: 1, lng: 2 }, wallet: 'not-a-wallet' }),+ (e) => { assert.ok(e instanceof ThreeWsError); assert.match(e.message, /wallet/); return true; },+ );+ await assert.rejects(() => client.claimDrop({ dropId: 'd1', wallet: 'C1aimWa11et111111111111111111111111111111111' }), /presence/);+ assert.equal(calls.length, 0);+});++test('claim failure states surface as typed errors (out_of_range, fix_required)', async () => {+ const { fetch } = stubFetch([+ { status: 403, body: { error: 'out_of_range', message: "you're 210 m away — get within 30 m to claim" } },+ ]);+ const client = createIrl({ fetch });+ await assert.rejects(+ () => client.claimDrop({+ dropId: 'd1', presence: { lat: 1, lng: 2, token: 't' },+ wallet: 'C1aimWa11et111111111111111111111111111111111',+ }),+ (e) => { assert.ok(e instanceof ThreeWsError); assert.equal(e.code, 'out_of_range'); assert.equal(e.status, 403); return true; },+ );+});++test('cancelDrop() posts the cancel and shapes the refund receipt', async () => {+ const { fetch, calls } = stubFetch([+ { body: { ok: true, refunded: true, refund_tx: 'refundsig', explorer_url: 'https://solscan.io/tx/refundsig' } },+ ]);+ const client = createIrl({ fetch, deviceToken: 'dev-1' });+ const out = await client.cancelDrop('d1');+ assert.equal(calls[0].url.pathname, '/api/irl/drops/d1/cancel');+ assert.equal(calls[0].init.method, 'POST');+ assert.equal(out.refunded, true);+ assert.equal(out.refundTx, 'refundsig');+});diff --git a/packages/irl/test/world-lines.test.js b/packages/irl/test/world-lines.test.jsnew file mode 100644index 000000000..7b30c7a71--- /dev/null+++ b/packages/irl/test/world-lines.test.js@@ -0,0 +1,220 @@+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { createIrl, ThreeWsError } from '../src/index.js';++// Same scripted fetch double as irl.test.js: queued responses, recorded calls.+function stubFetch(responses) {+ const calls = [];+ const queue = [...responses];+ const fetch = async (url, init) => {+ calls.push({ url: new URL(url), init });+ const next = queue.shift();+ if (!next) throw new Error('stubFetch: no more queued responses');+ const { status = 200, body = {}, headers = {} } = next;+ return {+ ok: status >= 200 && status < 300,+ status,+ headers: { get: (k) => headers[k.toLowerCase()] ?? null },+ text: async () => (typeof body === 'string' ? body : JSON.stringify(body)),+ };+ };+ return { fetch, calls };+}++const WL = {+ id: '22222222-2222-2222-2222-222222222222',+ agent_id: 'a1', signer_pubkey: 'SignerPubkey11111111111111111111111111111111',+ pin_id: 'p1', coarse_cell: 'dr5reg', title: 'Meet the courier',+ prompt: 'Find me by the fountain', challenge: { kind: 'quiz', prompt: null, question: 'What coin?', choices: ['$THREE', 'other'] },+ reward_kind: 'collectible', reward_ref: null, difficulty: 'easy',+ max_completions: 100, completion_count: 4,+ created_at: '2026-07-01T00:00:00Z', expires_at: '2026-07-31T00:00:00Z',+};++test('nearbyWorldLines() sends the fix token and shapes quests', async () => {+ const { fetch, calls } = stubFetch([+ { body: { world_lines: [{ ...WL, distance_m: 200, completed_by_me: false, capacity_reached: false }] } },+ ]);+ const client = createIrl({ fetch });+ const quests = await client.nearbyWorldLines({ lat: 40.7411, lng: -73.9897, token: 'tok.sig' }, { radius: 400 });++ assert.equal(calls[0].url.pathname, '/api/irl/world-lines/nearby');+ assert.equal(calls[0].url.searchParams.get('radius'), '400');+ assert.equal(calls[0].init.headers['x-irl-fix'], 'tok.sig');+ assert.equal(quests[0].distanceM, 200);+ assert.equal(quests[0].completedByMe, false);+ assert.equal(quests[0].signerPubkey, WL.signer_pubkey);+ assert.equal(quests[0].challenge.question, 'What coin?');+});++test('browseWorldLines() with no region returns the shaped roll-up', async () => {+ const { fetch, calls } = stubFetch([+ { body: { regions: [{ region_cell: 'dr5re', quests: 7, hard: 2, completions: 31 }] } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.browseWorldLines();+ assert.equal(calls[0].url.pathname, '/api/irl/world-lines/browse');+ assert.equal(out.regions[0].regionCell, 'dr5re');+ assert.equal(out.regions[0].completions, 31);+});++test('browseWorldLines() with a region lists that region and validates the cell', async () => {+ const { fetch, calls } = stubFetch([+ { body: { region: 'dr5re', quests: [{ id: WL.id, title: WL.title, reward_kind: 'collectible', difficulty: 'easy', completion_count: 4, capacity_reached: false }] } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.browseWorldLines({ region: 'dr5re', difficulty: 'easy' });+ assert.equal(calls[0].url.searchParams.get('region'), 'dr5re');+ assert.equal(calls[0].url.searchParams.get('difficulty'), 'easy');+ assert.equal(out.quests[0].completionCount, 4);+ await assert.rejects(() => client.browseWorldLines({ region: 'NOPE' }), /precision-5/);+ await assert.rejects(() => client.browseWorldLines({ difficulty: 'impossible' }), /Invalid difficulty/);+});++test('getWorldLine() passes the presence for the co-located detail', async () => {+ const { fetch, calls } = stubFetch([+ { body: { world_line: { ...WL, challenge: { ...WL.challenge, answer: 0 } }, colocated: true } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.getWorldLine(WL.id, { presence: { lat: 40.7411, lng: -73.9897, token: 'tok.sig' } });+ assert.equal(calls[0].url.pathname, `/api/irl/world-lines/${WL.id}`);+ assert.equal(calls[0].url.searchParams.get('lat'), '40.7411');+ assert.equal(calls[0].init.headers['x-irl-fix'], 'tok.sig');+ assert.equal(out.colocated, true);+ assert.equal(out.worldLine.challenge.answer, 0, 'co-located detail carries the full spec');+});++test('createWorldLine() validates the challenge client-side and maps field names', async () => {+ const { fetch, calls } = stubFetch([+ { status: 201, body: { world_line: WL } },+ ]);+ const client = createIrl({ fetch, apiKey: 'sess' });+ const { worldLine } = await client.createWorldLine({+ pinId: 'p1', title: 'Meet the courier', prompt: 'Find me by the fountain',+ challenge: { kind: 'quiz', question: 'What coin?', choices: ['$THREE', 'other'], answer: 0 },+ rewardRef: 'Courier badge', lifetimeDays: 30, maxCompletions: 100, difficulty: 'easy',+ });+ assert.equal(calls[0].init.method, 'POST');+ assert.equal(calls[0].init.headers.authorization, 'Bearer sess');+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(sent.reward_ref, 'Courier badge', 'reward_ref rides snake_case (server reads only that form)');+ assert.equal(sent.lifetime_days, 30, 'lifetime_days rides snake_case');+ assert.equal(sent.challenge.answer, 0);+ assert.equal(worldLine.id, WL.id);++ await assert.rejects(() => client.createWorldLine({ pinId: 'p1', title: 'x', challenge: { kind: 'quiz', question: 'q', choices: ['a'] } }), /two `choices`/);+ await assert.rejects(() => client.createWorldLine({ pinId: 'p1', title: 'x', challenge: { kind: 'phrase' } }), /passphrase/);+ await assert.rejects(() => client.createWorldLine({ title: 'x' }), /pinId/);+ await assert.rejects(() => client.createWorldLine({ pinId: 'p1' }), /title/);+});++test('challengeWorldLine() proves presence and returns the nonce + revealed spec', async () => {+ const { fetch, calls } = stubFetch([+ { body: { nonce: 'n0nce.sig', expires_in: 120,+ challenge: { kind: 'quiz', question: 'What coin?', choices: ['$THREE', 'other'], answer: 0 },+ agent_id: 'a1', world_line: { id: WL.id, title: WL.title } } },+ ]);+ const client = createIrl({ fetch, deviceToken: 'dev-5' });+ const out = await client.challengeWorldLine({+ worldLineId: WL.id,+ presence: { lat: 40.7411, lng: -73.9897, token: 'tok.sig' },+ });+ assert.equal(calls[0].url.pathname, '/api/irl/world-lines/challenge');+ assert.equal(JSON.parse(calls[0].init.body).world_line_id, WL.id);+ assert.equal(calls[0].init.headers['x-irl-fix'], 'tok.sig');+ assert.equal(calls[0].init.headers['x-irl-device'], 'dev-5');+ assert.equal(out.alreadyCompleted, false);+ assert.equal(out.nonce, 'n0nce.sig');+ assert.equal(out.challenge.answer, 0);+});++test('challengeWorldLine() surfaces the already-completed state instead of a nonce', async () => {+ const { fetch } = stubFetch([+ { body: { already_completed: true, proof_id: 'pr1', collectible_mint: 'presence:pr1' } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.challengeWorldLine({+ worldLineId: WL.id, presence: { lat: 1, lng: 2, token: 't' },+ });+ assert.equal(out.alreadyCompleted, true);+ assert.equal(out.proofId, 'pr1');+ assert.equal(out.collectibleMint, 'presence:pr1');+});++test('completeWorldLine() runs the proof ceremony and shapes proof + collectible', async () => {+ const { fetch, calls } = stubFetch([+ { status: 201, body: { ok: true,+ proof: { id: 'pr1', world_line_id: WL.id, agent_id: 'a1', signer_pubkey: WL.signer_pubkey,+ coarse_cell: 'dr5reg', signature: 'edsig', signed_message: 'three.ws/world-line-presence:v1|wl=…',+ signature_scheme: 'ed25519', completed_at: '2026-07-09T00:00:00Z',+ verify_url: '/api/irl/world-lines/verify/pr1' },+ collectible: { mint: 'presence:pr1', name: 'Meet the courier — proof of presence',+ kind: 'proof-of-presence', reward_kind: 'collectible',+ signer_pubkey: WL.signer_pubkey, signature: 'edsig', proof_id: 'pr1' } } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.completeWorldLine({+ worldLineId: WL.id, nonce: 'n0nce.sig',+ presence: { lat: 40.7411, lng: -73.9897, token: 'tok.sig' },+ answer: 0,+ });+ const sent = JSON.parse(calls[0].init.body);+ assert.equal(calls[0].url.pathname, '/api/irl/world-lines/complete');+ assert.equal(sent.nonce, 'n0nce.sig');+ assert.equal(sent.answer, 0);+ assert.equal(out.ok, true);+ assert.equal(out.proof.verifyUrl, '/api/irl/world-lines/verify/pr1');+ assert.equal(out.collectible.mint, 'presence:pr1');+ await assert.rejects(() => client.completeWorldLine({ worldLineId: WL.id, presence: { lat: 1, lng: 2 } }), /nonce/);+});++test('a remote completion attempt surfaces not_colocated as a typed error', async () => {+ const { fetch } = stubFetch([+ { status: 403, body: { error: 'not_colocated', error_description: 'travel to the quest to complete it', within_m: 80 } },+ ]);+ const client = createIrl({ fetch });+ await assert.rejects(+ () => client.completeWorldLine({ worldLineId: WL.id, nonce: 'n', presence: { lat: 0, lng: 0, token: 't' } }),+ (e) => { assert.ok(e instanceof ThreeWsError); assert.equal(e.code, 'not_colocated'); assert.equal(e.status, 403); return true; },+ );+});++test('myWorldLines() shapes the dashboard + heatmap; myCollectibles() the earned proofs', async () => {+ const { fetch, calls } = stubFetch([+ { body: { world_lines: [{ ...WL, expired: false, hidden: false }],+ heatmap: [{ world_line_id: WL.id, coarse_cell: 'dr5reg', completions: 4 }] } },+ { body: { collectibles: [{ mint: 'presence:pr1', name: 'Meet the courier — proof of presence',+ kind: 'proof-of-presence', reward_kind: 'collectible', signer_pubkey: WL.signer_pubkey,+ signature: 'edsig', proof_id: 'pr1', world_line_id: WL.id, world_line_title: WL.title,+ difficulty: 'easy', coarse_cell: 'dr5reg', earned_at: '2026-07-09T00:00:00Z',+ verify_url: '/api/irl/world-lines/verify/pr1' }] } },+ ]);+ const client = createIrl({ fetch, apiKey: 'sess', deviceToken: 'dev-5' });+ const mine = await client.myWorldLines();+ assert.equal(calls[0].url.pathname, '/api/irl/world-lines/mine');+ assert.equal(mine.worldLines[0].hidden, false);+ assert.equal(mine.heatmap[0].completions, 4);++ const earned = await client.myCollectibles();+ assert.equal(calls[1].url.pathname, '/api/irl/world-lines/collectibles');+ assert.equal(calls[1].init.headers['x-irl-device'], 'dev-5');+ assert.equal(earned[0].worldLineTitle, WL.title);+ assert.equal(earned[0].verifyUrl, '/api/irl/world-lines/verify/pr1');+});++test('verifyProof() re-checks the signature publicly', async () => {+ const { fetch, calls } = stubFetch([+ { body: { verified: true, proof: { id: 'pr1', world_line_id: WL.id, world_line_title: WL.title,+ agent_id: 'a1', signer_pubkey: WL.signer_pubkey, coarse_cell: 'dr5reg',+ signed_message: 'three.ws/world-line-presence:v1|wl=…', signature: 'edsig',+ signature_scheme: 'ed25519', collectible_mint: 'presence:pr1',+ collectible_name: 'Meet the courier — proof of presence', completed_at: '2026-07-09T00:00:00Z' } } },+ ]);+ const client = createIrl({ fetch });+ const out = await client.verifyProof('pr1');+ assert.equal(calls[0].url.pathname, '/api/irl/world-lines/verify/pr1');+ assert.equal(out.verified, true);+ assert.equal(out.proof.signatureScheme, 'ed25519');+ assert.equal(out.proof.collectibleMint, 'presence:pr1');+ await assert.rejects(() => client.verifyProof(''), /needs an id/);+});diff --git a/public/changelog.json b/public/changelog.jsonindex dfe4832ac..105f60d9c 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,11 +1,22 @@{- "generated_at": "2026-07-09T20:19:03.819Z",+ "generated_at": "2026-07-09T20:58:08.114Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws","url": "https://three.ws"},"entries": [+ {+ "date": "2026-07-09",+ "type": "update",+ "title": "Agents can now hunt money drops and complete IRL quests from code",+ "summary": "The @three-ws/irl SDK (v0.2.0) now covers the whole IRL surface, not just pins. New functions let any script or agent discover real-money drops near where it checks in, claim them with a proof-of-presence fix (a real on-chain release to its own wallet), place self- or agent-funded drops and bounties, and run the full World Lines quest loop — find nearby quests, take the challenge at the spot, and earn the agent-signed proof-of-presence collectible, plus verify anyone's proof independently. Fully typed, zero dependencies, verified against the live API.",+ "link": "/irl",+ "tags": [+ "sdk",+ "feature"+ ]+ },{"date": "2026-07-08","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 860974a00..e2c9ef919 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -6,6 +6,14 @@<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/><description>What's new on three.ws — features, improvements, and releases, newest first.</description><language>en</language>+ <item>+ <title>Agents can now hunt money drops and complete IRL quests from code</title>+ <link>https://three.ws/irl</link>+ <guid isPermaLink="false">2026-07-09:Agents can now hunt money drops and complete IRL quests from code</guid>+ <pubDate>Thu, 09 Jul 2026 12:00:00 GMT</pubDate>+ <category>sdk</category>+ <description>The @three-ws/irl SDK (v0.2.0) now covers the whole IRL surface, not just pins. New functions let any script or agent discover real-money drops near where it checks in, claim them with a proof-of-presence fix (a real on-chain release to its own wallet), place self- or agent-funded drops and bounties, and run the full World Lines quest loop — find nearby quests, take the challenge at the spot, and earn the agent-signed proof-of-presence collectible, plus verify anyone's proof independently. Fully typed, zero dependencies, verified against the live API.</description>+ </item><item><title>Blockchain TVL by Chain</title><link>https://three.ws/chains</link>diff --git a/public/features.json b/public/features.jsonindex 0be275c05..6b19dc87b 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-07-09T20:19:03.805Z",+ "generated_at": "2026-07-09T20:58:08.093Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",