Skip to content

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.

feat(payments): add /recurring, the page that manages every recurring schedule

nirholas4ed4e7650e91
diff --git a/data/pages.json b/data/pages.json
index ec07c4d23..d8d23f2f4 100644
--- a/data/pages.json
+++ b/data/pages.json
@@ -1552,11 +1552,19 @@
{
"path": "/strategy-lab",
"title": "Strategy Lab",
- "description": "Build DCA and subscription strategies that trade on-chain on your behalf.",
+ "description": "Write a pump.fun trading strategy as data, backtest it against real on-chain history, then run it live through your agent's wallet.",
"priority": 0.7,
"changefreq": "weekly",
"added": "2026-05-15"
},
+ {
+ "path": "/recurring",
+ "title": "Recurring Payments",
+ "description": "Create, pause, resume and cancel recurring on-chain USDC payments and DCA schedules, see every charge each one has settled, and watch what is being paid into your own agents.",
+ "priority": 0.7,
+ "changefreq": "weekly",
+ "added": "2026-08-13"
+ },
{
"path": "/strategies",
"title": "Strategy Objects",
diff --git a/public/recurring.html b/public/recurring.html
new file mode 100644
index 000000000..314b0a603
--- /dev/null
+++ b/public/recurring.html
@@ -0,0 +1,289 @@
+<!doctype html>
+<html lang="en">
+<head>
+ <script>/* three.ws theme boot: no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8">
+ <title>Recurring payments · three.ws</title>
+ <meta name="viewport" content="width=device-width, initial-scale=1">
+ <meta name="theme-color" content="#0b0b0b">
+ <link rel="stylesheet" href="/nav.css">
+ <style>
+ :root {
+ --bg: #0b0b0b; --bg-2: #111111; --panel: #161616; --panel-2: #1d1d1d;
+ --border: #272727; --border-strong: #343434;
+ --text: #f0f2f8; --muted: #8a90a8; --muted-2: #6b7088;
+ --blue: #60a5fa; --green: #4ade80; --red: #f87171; --amber: #f59e0b; --purple: #a78bfa;
+ --mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;
+ --ok-bg: color-mix(in srgb, var(--green) 14%, transparent);
+ --warn-bg: color-mix(in srgb, var(--amber) 16%, transparent);
+ --bad-bg: color-mix(in srgb, var(--red) 15%, transparent);
+ --info-bg: color-mix(in srgb, var(--blue) 13%, transparent);
+ --shadow: 0 18px 48px rgba(0,0,0,.45);
+ }
+ html[data-theme='light'] {
+ --bg: #fafafa; --bg-2: #ffffff; --panel: #ffffff; --panel-2: #f4f4f5;
+ --border: #e5e7eb; --border-strong: #d4d4d8;
+ --text: #18181b; --muted: #52525b; --muted-2: #71717a;
+ --blue: #2563eb; --green: #16a34a; --red: #dc2626; --amber: #b45309; --purple: #7c3aed;
+ --shadow: 0 18px 48px rgba(0,0,0,.18);
+ }
+ * { box-sizing: border-box; }
+ html, body { margin: 0; padding: 0; background: var(--bg); color: var(--text); }
+ body {
+ font: 14px/1.55 -apple-system, BlinkMacSystemFont, "Inter", "Segoe UI", Roboto, sans-serif;
+ -webkit-font-smoothing: antialiased; min-height: 100vh;
+ }
+ a { color: var(--blue); text-decoration: none; }
+ a:hover { text-decoration: underline; }
+ code, .mono { font-family: var(--mono); }
+ .wrap { max-width: 1120px; margin: 0 auto; padding: 0 24px 4rem; }
+ @media (max-width: 720px) { .wrap { padding: 0 16px 3rem; } }
+ :focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; border-radius: 6px; }
+
+ /* ── Hero ─────────────────────────────────────────────── */
+ .hero { padding: 34px 0 8px; }
+ .eyebrow { display: inline-flex; align-items: center; gap: 8px; font-size: 11px; letter-spacing: .14em; text-transform: uppercase; color: var(--purple); font-weight: 600; margin-bottom: 10px; }
+ .eyebrow .pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--purple); box-shadow: 0 0 0 0 rgba(167,139,250,.6); animation: pulse 2.4s infinite; }
+ @keyframes pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(167,139,250,.6); } 50% { box-shadow: 0 0 0 6px rgba(167,139,250,0); } }
+ @media (prefers-reduced-motion: reduce) { .eyebrow .pulse { animation: none; } }
+ .hero h1 { font-size: 30px; line-height: 1.12; margin: 0 0 8px; letter-spacing: -.02em; }
+ .hero p.lead { color: var(--muted); margin: 0; font-size: 14.5px; max-width: 720px; }
+
+ h2 { font-size: 11px; margin: 0 0 .7rem; color: var(--muted); text-transform: uppercase; letter-spacing: .1em; font-weight: 600; }
+ .muted { color: var(--muted); }
+
+ /* ── Tabs ─────────────────────────────────────────────── */
+ .tabs { display: flex; gap: 4px; margin: 22px 0 16px; border-bottom: 1px solid var(--border); }
+ .tab {
+ appearance: none; background: none; border: 0; border-bottom: 2px solid transparent;
+ color: var(--muted); font: inherit; font-weight: 600; padding: .6rem .9rem; cursor: pointer;
+ transition: color .14s, border-color .14s;
+ }
+ .tab:hover { color: var(--text); }
+ .tab[aria-selected='true'] { color: var(--text); border-bottom-color: var(--purple); }
+ .tab .count { font-family: var(--mono); font-size: 11px; color: var(--muted-2); margin-left: 6px; }
+
+ /* ── Panels + stats ───────────────────────────────────── */
+ .panel { border: 1px solid var(--border); border-radius: 14px; padding: 1rem 1.1rem; background: var(--panel); }
+ .panel + .panel { margin-top: 1rem; }
+ .stats { display: grid; grid-template-columns: repeat(4, minmax(0,1fr)); gap: .7rem; margin-bottom: 1rem; }
+ @media (max-width: 860px) { .stats { grid-template-columns: repeat(2, minmax(0,1fr)); } }
+ .stat { border: 1px solid var(--border); border-radius: 12px; padding: .8rem .9rem; background: var(--panel); }
+ .stat .k { font-size: 10.5px; letter-spacing: .1em; text-transform: uppercase; color: var(--muted-2); }
+ .stat .v { font-family: var(--mono); font-size: 20px; margin-top: 4px; letter-spacing: -.02em; }
+ .stat .v small { font-size: 12px; color: var(--muted); }
+
+ /* ── Schedule cards ───────────────────────────────────── */
+ .cards { display: flex; flex-direction: column; gap: .7rem; }
+ .card {
+ border: 1px solid var(--border); border-radius: 13px; background: var(--panel);
+ padding: .9rem 1rem; transition: border-color .14s, transform .14s;
+ }
+ .card:hover { border-color: var(--border-strong); }
+ .card-top { display: flex; align-items: flex-start; justify-content: space-between; gap: 1rem; flex-wrap: wrap; }
+ .card-title { font-weight: 600; font-size: 15px; display: flex; align-items: center; gap: .5rem; flex-wrap: wrap; }
+ .card-sub { color: var(--muted); font-size: 12.5px; margin-top: 3px; }
+ .amount { font-family: var(--mono); font-size: 17px; letter-spacing: -.02em; white-space: nowrap; }
+ .amount small { color: var(--muted); font-size: 11.5px; }
+
+ .meta { display: flex; flex-wrap: wrap; gap: .35rem 1.3rem; margin-top: .75rem; font-size: 12.5px; }
+ .meta div { display: flex; gap: .4rem; }
+ .meta .mk { color: var(--muted-2); }
+ .meta .mv { font-family: var(--mono); }
+
+ .pill {
+ display: inline-flex; align-items: center; gap: 5px; font-size: 11px; font-weight: 600;
+ padding: 2px 8px; border-radius: 999px; border: 1px solid transparent; letter-spacing: .02em;
+ }
+ .pill.ok { background: var(--ok-bg); color: var(--green); border-color: color-mix(in srgb, var(--green) 35%, transparent); }
+ .pill.warn { background: var(--warn-bg); color: var(--amber); border-color: color-mix(in srgb, var(--amber) 35%, transparent); }
+ .pill.bad { background: var(--bad-bg); color: var(--red); border-color: color-mix(in srgb, var(--red) 35%, transparent); }
+ .pill.info { background: var(--info-bg); color: var(--blue); border-color: color-mix(in srgb, var(--blue) 35%, transparent); }
+ .pill.dim { background: var(--panel-2); color: var(--muted); border-color: var(--border); }
+
+ .notice { margin-top: .75rem; border-radius: 10px; padding: .6rem .75rem; font-size: 12.5px; line-height: 1.5; }
+ .notice.warn { background: var(--warn-bg); color: var(--text); border: 1px solid color-mix(in srgb, var(--amber) 30%, transparent); }
+ .notice.bad { background: var(--bad-bg); color: var(--text); border: 1px solid color-mix(in srgb, var(--red) 30%, transparent); }
+ .notice strong { color: var(--amber); }
+ .notice.bad strong { color: var(--red); }
+
+ .actions { display: flex; gap: .45rem; margin-top: .8rem; flex-wrap: wrap; }
+
+ button, .btn {
+ appearance: none; font: inherit; font-size: 12.5px; font-weight: 600; cursor: pointer;
+ border: 1px solid var(--border-strong); background: var(--panel-2); color: var(--text);
+ padding: .42rem .8rem; border-radius: 9px; transition: background .13s, border-color .13s, transform .08s, opacity .13s;
+ }
+ button:hover:not(:disabled), .btn:hover { background: var(--panel); border-color: var(--blue); text-decoration: none; }
+ button:active:not(:disabled) { transform: translateY(1px); }
+ button:disabled { opacity: .45; cursor: not-allowed; }
+ button.primary { background: var(--blue); border-color: var(--blue); color: #04101f; }
+ button.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--blue); }
+ button.danger { color: var(--red); }
+ button.danger:hover:not(:disabled) { border-color: var(--red); }
+
+ /* ── Charge history ───────────────────────────────────── */
+ .history { margin-top: .85rem; border-top: 1px solid var(--border); padding-top: .7rem; }
+ table { width: 100%; border-collapse: collapse; font-size: 12.5px; }
+ th { text-align: left; font-weight: 600; color: var(--muted-2); font-size: 10.5px; text-transform: uppercase; letter-spacing: .08em; padding: .3rem .5rem .45rem 0; }
+ td { padding: .35rem .5rem .35rem 0; border-top: 1px solid var(--border); font-family: var(--mono); vertical-align: top; }
+ td.reason { font-family: inherit; color: var(--muted); }
+ .scroll-x { overflow-x: auto; }
+
+ /* ── Forms ────────────────────────────────────────────── */
+ .form-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: .8rem; }
+ label { display: block; font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--muted-2); font-weight: 600; margin-bottom: .3rem; }
+ select, input[type='number'] {
+ width: 100%; font: inherit; font-size: 13px; background: var(--bg-2); color: var(--text);
+ border: 1px solid var(--border-strong); border-radius: 9px; padding: .45rem .6rem;
+ transition: border-color .13s;
+ }
+ select:hover, input[type='number']:hover { border-color: var(--blue); }
+ .field-note { font-size: 11.5px; color: var(--muted-2); margin-top: .35rem; }
+
+ /* ── Empty / error / loading states ───────────────────── */
+ .state { text-align: center; padding: 2.4rem 1.2rem; border: 1px dashed var(--border-strong); border-radius: 14px; background: var(--panel); }
+ .state .icon { font-size: 26px; opacity: .8; }
+ .state h3 { margin: .6rem 0 .35rem; font-size: 15px; }
+ .state p { color: var(--muted); margin: 0 auto; max-width: 460px; font-size: 13px; line-height: 1.6; }
+ .state .actions { justify-content: center; }
+ .skel { display: block; border-radius: 9px; background: linear-gradient(90deg, var(--panel) 25%, var(--panel-2) 37%, var(--panel) 63%); background-size: 400% 100%; animation: shimmer 1.3s ease-in-out infinite; }
+ @keyframes shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
+ @media (prefers-reduced-motion: reduce) { .skel { animation: none; } }
+ .skel-card { height: 108px; margin-bottom: .7rem; }
+
+ /* ── Modal ────────────────────────────────────────────── */
+ .modal-backdrop { position: fixed; inset: 0; background: rgba(0,0,0,.62); display: flex; align-items: center; justify-content: center; padding: 1.2rem; z-index: 120; opacity: 0; pointer-events: none; transition: opacity .15s; }
+ .modal-backdrop.open { opacity: 1; pointer-events: auto; }
+ .modal { background: var(--panel); border: 1px solid var(--border-strong); border-radius: 14px; width: 100%; max-width: 440px; padding: 1.25rem 1.35rem; box-shadow: var(--shadow); transform: translateY(8px) scale(.985); transition: transform .15s; }
+ .modal-backdrop.open .modal { transform: none; }
+ .modal h3 { margin: 0 0 .5rem; font-size: 1.05rem; }
+ .modal p { margin: 0 0 .65rem; color: var(--muted); line-height: 1.55; font-size: 13px; }
+ .modal .modal-actions { display: flex; gap: .5rem; justify-content: flex-end; margin-top: 1.1rem; }
+
+ /* ── Toast ────────────────────────────────────────────── */
+ #toasts { position: fixed; bottom: 18px; left: 50%; transform: translateX(-50%); z-index: 200; display: flex; flex-direction: column; gap: 8px; align-items: center; pointer-events: none; }
+ .toast { background: var(--panel); border: 1px solid var(--border-strong); color: var(--text); padding: .55rem .9rem; border-radius: 999px; font-size: 12.5px; box-shadow: var(--shadow); opacity: 0; transform: translateY(8px); transition: opacity .18s, transform .18s; max-width: 90vw; }
+ .toast.show { opacity: 1; transform: none; }
+ .toast.bad { border-color: color-mix(in srgb, var(--red) 45%, transparent); }
+ .hidden { display: none !important; }
+ </style>
+
+ <meta name="description" content="Create, pause, resume and cancel recurring on-chain USDC payments and DCA schedules, and see every charge they have ever made.">
+ <link rel="canonical" href="https://three.ws/recurring">
+ <meta property="og:type" content="website">
+ <meta property="og:site_name" content="three.ws">
+ <meta property="og:title" content="Recurring payments · three.ws">
+ <meta property="og:description" content="Create, pause, resume and cancel recurring on-chain USDC payments and DCA schedules, and see every charge they have ever made.">
+ <meta property="og:url" content="https://three.ws/recurring">
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Recurring+payments&amp;d=Recurring+on-chain+payments+and+DCA+schedules%2C+with+every+charge+on+the+record.&amp;p=%2Frecurring">
+ <meta property="og:image:width" content="1200">
+ <meta property="og:image:height" content="630">
+ <meta name="twitter:card" content="summary_large_image">
+ <meta name="twitter:title" content="Recurring payments · three.ws">
+ <meta name="twitter:description" content="Create, pause, resume and cancel recurring on-chain USDC payments and DCA schedules, and see every charge they have ever made.">
+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Recurring+payments&amp;d=Recurring+on-chain+payments+and+DCA+schedules%2C+with+every+charge+on+the+record.&amp;p=%2Frecurring">
+ <meta name="twitter:site" content="@trythreews">
+ <script type="application/ld+json">{"@context":"https://schema.org","@type":"WebPage","name":"Recurring payments","description":"Create, pause, resume and cancel recurring on-chain USDC payments and DCA schedules, and see every charge they have ever made.","url":"https://three.ws/recurring","isPartOf":{"@type":"WebSite","name":"three.ws","url":"https://three.ws"}}</script>
+ <meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1">
+ <meta property="og:locale" content="en_US">
+ <meta property="og:image:alt" content="Recurring payments on three.ws">
+</head>
+<body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="wrap">
+ <div class="hero">
+ <div class="eyebrow"><span class="pulse"></span> Recurring payments</div>
+ <h1>Money that moves on a schedule, with every charge on the record</h1>
+ <p class="lead">
+ A recurring payment pulls a fixed amount of USDC from your wallet on a period you
+ choose, inside a permission you signed once. A DCA schedule does the same and swaps
+ the result into a token. Both run on the hourly crons, both can be paused and resumed
+ without re-signing, and both keep a per-charge ledger you can read here.
+ </p>
+ </div>
+
+ <div class="tabs" role="tablist" aria-label="Recurring payment views">
+ <button class="tab" id="tab-outgoing" role="tab" aria-selected="true" aria-controls="view-outgoing">Outgoing<span class="count" id="count-outgoing"></span></button>
+ <button class="tab" id="tab-incoming" role="tab" aria-selected="false" aria-controls="view-incoming">Incoming<span class="count" id="count-incoming"></span></button>
+ </div>
+
+ <!-- ── Outgoing ─────────────────────────────────────────── -->
+ <section id="view-outgoing" role="tabpanel" aria-labelledby="tab-outgoing">
+ <div id="out-stats" class="stats hidden"></div>
+
+ <div class="panel" id="create-panel">
+ <h2>New recurring payment</h2>
+ <p class="muted" style="margin:0 0 .9rem;font-size:12.5px;">
+ A schedule spends a permission you already signed for one of your agents. Pick the
+ permission, set the amount and how often it should run.
+ </p>
+ <div class="form-grid">
+ <div>
+ <label for="c-agent">Agent</label>
+ <select id="c-agent"><option value="">Loading agents…</option></select>
+ </div>
+ <div>
+ <label for="c-delegation">Signed permission</label>
+ <select id="c-delegation" disabled><option value="">Pick an agent first</option></select>
+ <div class="field-note" id="c-delegation-note"></div>
+ </div>
+ <div>
+ <label for="c-amount">Amount per period (USDC)</label>
+ <input id="c-amount" type="number" min="0.000001" step="0.000001" value="5" inputmode="decimal">
+ </div>
+ <div>
+ <label for="c-period">How often</label>
+ <select id="c-period">
+ <option value="86400">Daily</option>
+ <option value="604800" selected>Weekly</option>
+ <option value="2592000">Every 30 days</option>
+ </select>
+ </div>
+ </div>
+ <div class="actions">
+ <button class="primary" id="c-submit" disabled>Create schedule</button>
+ <a class="btn" id="c-grant-link" href="/docs/permissions">Grant a new permission</a>
+ </div>
+ </div>
+
+ <div id="out-body" style="margin-top:1rem"></div>
+
+ <div class="panel" id="dca-panel" style="margin-top:1rem">
+ <h2>DCA schedules</h2>
+ <div id="dca-body"></div>
+ </div>
+ </section>
+
+ <!-- ── Incoming ─────────────────────────────────────────── -->
+ <section id="view-incoming" role="tabpanel" aria-labelledby="tab-incoming" class="hidden">
+ <div id="in-stats" class="stats hidden"></div>
+ <div id="in-body"></div>
+ </section>
+ </main>
+
+ <div class="modal-backdrop" id="confirm-backdrop" role="dialog" aria-modal="true" aria-labelledby="confirm-title">
+ <div class="modal">
+ <h3 id="confirm-title">Cancel this schedule?</h3>
+ <p id="confirm-body"></p>
+ <p class="muted">Cancelling stops all future charges. It does not revoke the signed permission, and it cannot be undone: starting again means creating a new schedule.</p>
+ <div class="modal-actions">
+ <button id="confirm-no">Keep it</button>
+ <button class="danger" id="confirm-yes">Cancel schedule</button>
+ </div>
+ </div>
+ </div>
+
+ <div id="toasts" aria-live="polite"></div>
+
+ <script type="module" src="/src/recurring.js"></script>
+
+ <div id="footer-container"></div>
+ <script src="/footer.js" defer></script>
+ <script src="/brand.js" defer></script>
+ <!-- Runtime i18n: detects locale, swaps annotated copy, mounts <lang-switcher>. -->
+ <script type="module" src="/i18n.js"></script>
+</body>
+</html>
diff --git a/src/recurring.js b/src/recurring.js
new file mode 100644
index 000000000..172d4f0aa
--- /dev/null
+++ b/src/recurring.js
@@ -0,0 +1,863 @@
+/**
+ * /recurring — the product surface for recurring on-chain payments.
+ *
+ * Two schedule kinds, one lifecycle:
+ * - subscriptions (`/api/agent-subscriptions`) transfer a fixed USDC amount
+ * per period inside a signed ERC-7710 permission.
+ * - DCA strategies (`/api/dca-strategies`) spend the same kind of permission
+ * but swap the result into a token.
+ *
+ * Everything on this page is driven by real API data. The charge and execution
+ * histories come from the ledgers the hourly crons write (subscription_charges
+ * and dca_executions), so a failed period shows the reason the cron recorded
+ * rather than a generic "something went wrong".
+ */
+
+import { apiFetch } from './api.js';
+
+const $ = (id) => document.getElementById(id);
+
+const state = {
+ signedIn: true,
+ agents: [],
+ agentId: '',
+ outgoing: null,
+ incoming: null,
+ dca: null,
+ openHistory: new Set(),
+ busy: new Set(),
+};
+
+const AGENT_KEY = 'recurring:agentId';
+
+// ── Small helpers ───────────────────────────────────────────────────────────
+
+function esc(s) {
+ return String(s ?? '').replace(
+ /[&<>"']/g,
+ (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c],
+ );
+}
+
+function shortAddr(a) {
+ if (!a || a.length < 12) return a || 'unknown';
+ return `${a.slice(0, 6)}…${a.slice(-4)}`;
+}
+
+/** Relative time that stays readable in both directions ("in 3h", "5d ago"). */
+function relTime(iso) {
+ if (!iso) return 'never';
+ const ms = new Date(iso).getTime() - Date.now();
+ if (!Number.isFinite(ms)) return 'unknown';
+ const abs = Math.abs(ms);
+ const units = [
+ [86400000, 'd'],
+ [3600000, 'h'],
+ [60000, 'm'],
+ ];
+ for (const [size, label] of units) {
+ if (abs >= size) {
+ const n = Math.round(abs / size);
+ return ms > 0 ? `in ${n}${label}` : `${n}${label} ago`;
+ }
+ }
+ return ms > 0 ? 'in under a minute' : 'just now';
+}
+
+function absTime(iso) {
+ if (!iso) return '';
+ const d = new Date(iso);
+ return Number.isFinite(d.getTime()) ? d.toLocaleString() : '';
+}
+
+function toast(message, bad = false) {
+ const el = document.createElement('div');
+ el.className = `toast${bad ? ' bad' : ''}`;
+ el.textContent = message;
+ $('toasts').appendChild(el);
+ requestAnimationFrame(() => el.classList.add('show'));
+ setTimeout(() => {
+ el.classList.remove('show');
+ setTimeout(() => el.remove(), 220);
+ }, 3600);
+}
+
+/** Read a JSON body whatever the endpoint's envelope is, without throwing. */
+async function readBody(res) {
+ return res.json().catch(() => ({}));
+}
+
+function statusPill(status) {
+ const map = {
+ active: ['ok', 'Active'],
+ paused: ['warn', 'Paused'],
+ canceled: ['dim', 'Canceled'],
+ cancelled: ['dim', 'Cancelled'],
+ expired: ['bad', 'Expired'],
+ };
+ const [cls, label] = map[status] || ['dim', status || 'unknown'];
+ return `<span class="pill ${cls}">${esc(label)}</span>`;
+}
+
+function chargeStatusPill(status) {
+ const map = {
+ success: ['ok', 'Paid'],
+ failed: ['bad', 'Failed'],
+ aborted: ['warn', 'Stopped'],
+ unknown: ['warn', 'Unverified'],
+ pending: ['dim', 'Pending'],
+ };
+ const [cls, label] = map[status] || ['dim', status || 'unknown'];
+ return `<span class="pill ${cls}">${esc(label)}</span>`;
+}
+
+function stat(k, v, sub) {
+ return `<div class="stat"><div class="k">${esc(k)}</div><div class="v">${esc(v)}${
+ sub ? ` <small>${esc(sub)}</small>` : ''
+ }</div></div>`;
+}
+
+function skeleton(n = 2) {
+ return `<div class="cards">${'<div class="skel skel-card"></div>'.repeat(n)}</div>`;
+}
+
+function emptyState({ icon, title, body, action }) {
+ return `<div class="state">
+ <div class="icon" aria-hidden="true">${icon}</div>
+ <h3>${esc(title)}</h3>
+ <p>${body}</p>
+ ${action ? `<div class="actions">${action}</div>` : ''}
+ </div>`;
+}
+
+function errorState(message, retryAction) {
+ return emptyState({
+ icon: '⚠️',
+ title: 'Could not load your schedules',
+ body: `${esc(message)} Nothing was changed. Try again, and if it keeps failing the API is likely down rather than your schedules.`,
+ action: `<button data-retry="${esc(retryAction)}">Try again</button>`,
+ });
+}
+
+function signedOutState() {
+ return emptyState({
+ icon: '🔐',
+ title: 'Sign in to see your schedules',
+ body: 'Recurring payments spend a permission you signed with your own wallet, so they are only visible to the account that created them.',
+ action: '<a class="btn" href="/login">Sign in</a>',
+ });
+}
+
+// ── Data loading ────────────────────────────────────────────────────────────
+
+async function loadAgents() {
+ const res = await apiFetch('/api/agents', { allowAnonymous: true });
+ if (res.status === 401) {
+ state.signedIn = false;
+ return;
+ }
+ const body = await readBody(res);
+ state.agents = Array.isArray(body.agents) ? body.agents : [];
+ const saved = localStorage.getItem(AGENT_KEY);
+ state.agentId =
+ saved && state.agents.some((a) => a.id === saved) ? saved : (state.agents[0]?.id ?? '');
+}
+
+async function loadOutgoing() {
+ state.outgoing = { loading: true };
+ renderOutgoing();
+ try {
+ const res = await apiFetch('/api/agent-subscriptions', { allowAnonymous: true });
+ if (res.status === 401) {
+ state.signedIn = false;
+ state.outgoing = { loading: false, rows: [], summary: null };
+ } else if (!res.ok) {
+ const body = await readBody(res);
+ state.outgoing = { loading: false, error: body.error_description || `HTTP ${res.status}` };
+ } else {
+ const body = await readBody(res);
+ state.outgoing = { loading: false, rows: body.data || [], summary: body.summary || null };
+ }
+ } catch (err) {
+ state.outgoing = { loading: false, error: err.message || 'network error' };
+ }
+ renderOutgoing();
+}
+
+async function loadIncoming() {
+ state.incoming = { loading: true };
+ renderIncoming();
+ try {
+ const res = await apiFetch('/api/agent-subscriptions?view=incoming', {
+ allowAnonymous: true,
+ });
+ if (res.status === 401) {
+ state.signedIn = false;
+ state.incoming = { loading: false, rows: [], summary: null };
+ } else if (!res.ok) {
+ const body = await readBody(res);
+ state.incoming = { loading: false, error: body.error_description || `HTTP ${res.status}` };
+ } else {
+ const body = await readBody(res);
+ state.incoming = { loading: false, rows: body.data || [], summary: body.summary || null };
+ }
+ } catch (err) {
+ state.incoming = { loading: false, error: err.message || 'network error' };
+ }
+ renderIncoming();
+}
+
+async function loadDca() {
+ if (!state.agentId) {
+ state.dca = { loading: false, rows: [] };
+ renderDca();
+ return;
+ }
+ state.dca = { loading: true };
+ renderDca();
+ try {
+ const res = await apiFetch(
+ `/api/dca-strategies?agent_id=${encodeURIComponent(state.agentId)}`,
+ { allowAnonymous: true },
+ );
+ if (res.status === 401) {
+ state.signedIn = false;
+ state.dca = { loading: false, rows: [] };
+ } else if (!res.ok) {
+ const body = await readBody(res);
+ state.dca = { loading: false, error: body.error_description || `HTTP ${res.status}` };
+ } else {
+ const body = await readBody(res);
+ state.dca = { loading: false, rows: body.data || [] };
+ }
+ } catch (err) {
+ state.dca = { loading: false, error: err.message || 'network error' };
+ }
+ renderDca();
+}
+
+async function loadCharges(id) {
+ const res = await apiFetch(`/api/agent-subscriptions?id=${encodeURIComponent(id)}`, {
+ allowAnonymous: true,
+ });
+ if (!res.ok) throw new Error((await readBody(res)).error_description || `HTTP ${res.status}`);
+ return (await readBody(res)).data;
+}
+
+// ── Rendering ───────────────────────────────────────────────────────────────
+
+function historyTable(charges) {
+ if (!charges?.length) {
+ return '<p class="muted" style="font-size:12.5px;margin:.5rem 0 0">No charge has run yet. The first one fires on the next hourly tick after the due time.</p>';
+ }
+ const rows = charges
+ .map(
+ (c) => `<tr>
+ <td>${esc(absTime(c.charged_at))}</td>
+ <td>${chargeStatusPill(c.status)}</td>
+ <td>${esc(c.amount_display)} <small class="muted">USDC</small></td>
+ <td class="reason">${
+ c.tx_hash
+ ? `<span class="mono">${esc(shortAddr(c.tx_hash))}</span>`
+ : esc(c.error || c.code || '')
+ }</td>
+ </tr>`,
+ )
+ .join('');
+ return `<div class="scroll-x"><table>
+ <thead><tr><th>When</th><th>Result</th><th>Amount</th><th>Transaction or reason</th></tr></thead>
+ <tbody>${rows}</tbody>
+ </table></div>`;
+}
+
+function subscriptionCard(s, { role }) {
+ const open = state.openHistory.has(s.id);
+ const busy = state.busy.has(s.id);
+ const canPause = role === 'payer' && s.status === 'active';
+ const canResume = role === 'payer' && s.status === 'paused';
+ const canCancel = role === 'payer' && s.status !== 'canceled';
+
+ const failureNotice =
+ s.status === 'paused' && s.last_error
+ ? `<div class="notice bad"><strong>Paused:</strong> ${esc(s.last_error)}</div>`
+ : s.status === 'active' && s.last_error
+ ? `<div class="notice warn"><strong>Last run failed:</strong> ${esc(s.last_error)} ${
+ s.retries_left
+ ? `${s.retries_left} more attempt${s.retries_left === 1 ? '' : 's'} before it pauses.`
+ : ''
+ }</div>`
+ : '';
+
+ const counterparty =
+ role === 'creator'
+ ? `<div><span class="mk">from</span><span class="mv">${esc(shortAddr(s.payer_address))}</span></div>`
+ : `<div><span class="mk">to</span><span class="mv">${esc(shortAddr(s.payee_address))}</span></div>`;
+
+ return `<article class="card" data-sub="${esc(s.id)}">
+ <div class="card-top">
+ <div>
+ <div class="card-title">${esc(s.agent_name || 'Untitled agent')} ${statusPill(s.status)}</div>
+ <div class="card-sub">${esc(s.amount_display)} USDC ${esc(s.period_label)}${
+ s.chain_id ? ` on chain ${esc(String(s.chain_id))}` : ''
+ }</div>
+ </div>
+ <div class="amount">${esc(s.charged_total_display)} <small>USDC paid</small></div>
+ </div>
+
+ <div class="meta">
+ <div><span class="mk">next</span><span class="mv">${esc(
+ s.status === 'active' ? relTime(s.next_charge_at) : 'not scheduled',
+ )}</span></div>
+ <div><span class="mk">last</span><span class="mv">${esc(relTime(s.last_charge_at))}</span></div>
+ <div><span class="mk">charges</span><span class="mv">${esc(String(s.charges_total))}</span></div>
+ ${counterparty}
+ <div><span class="mk">permission</span><span class="mv">${esc(s.delegation_status || 'unknown')}</span></div>
+ </div>
+
+ ${failureNotice}
+
+ <div class="actions">
+ <button data-act="history" data-id="${esc(s.id)}" aria-expanded="${open}">${
+ open ? 'Hide charges' : 'View charges'
+ }</button>
+ ${canPause ? `<button data-act="pause" data-id="${esc(s.id)}"${busy ? ' disabled' : ''}>Pause</button>` : ''}
+ ${canResume ? `<button class="primary" data-act="resume" data-id="${esc(s.id)}"${busy ? ' disabled' : ''}>Resume</button>` : ''}
+ ${canCancel ? `<button class="danger" data-act="cancel" data-id="${esc(s.id)}"${busy ? ' disabled' : ''}>Cancel</button>` : ''}
+ </div>
+
+ ${open ? `<div class="history" data-history="${esc(s.id)}">${historyTable(s.charges)}</div>` : ''}
+ </article>`;
+}
+
+function renderOutgoing() {
+ const body = $('out-body');
+ const stats = $('out-stats');
+ const o = state.outgoing;
+
+ if (!state.signedIn) {
+ stats.classList.add('hidden');
+ body.innerHTML = signedOutState();
+ $('count-outgoing').textContent = '';
+ return;
+ }
+ if (!o || o.loading) {
+ stats.classList.add('hidden');
+ body.innerHTML = skeleton(2);
+ return;
+ }
+ if (o.error) {
+ stats.classList.add('hidden');
+ body.innerHTML = errorState(o.error, 'outgoing');
+ return;
+ }
+
+ $('count-outgoing').textContent = o.rows.length ? String(o.rows.length) : '';
+
+ if (o.summary && o.rows.length) {
+ stats.classList.remove('hidden');
+ stats.innerHTML =
+ stat('Active schedules', String(o.summary.active), `of ${o.summary.schedules}`) +
+ stat('Paid so far', o.summary.paid_total_display, 'USDC') +
+ stat('Charges run', String(o.summary.charges_total)) +
+ stat('Next charge', relTime(o.summary.next_charge_at));
+ } else {
+ stats.classList.add('hidden');
+ }
+
+ if (!o.rows.length) {
+ body.innerHTML = emptyState({
+ icon: '🔁',
+ title: 'No recurring payments yet',
+ body: 'Create one above with a permission you have already signed, or grant a new permission on an agent first. Every schedule you create shows up here with its full charge history.',
+ });
+ return;
+ }
+
+ body.innerHTML = `<div class="cards">${o.rows
+ .map((s) => subscriptionCard(s, { role: 'payer' }))
+ .join('')}</div>`;
+}
+
+function renderIncoming() {
+ const body = $('in-body');
+ const stats = $('in-stats');
+ const i = state.incoming;
+
+ if (!state.signedIn) {
+ stats.classList.add('hidden');
+ body.innerHTML = signedOutState();
+ $('count-incoming').textContent = '';
+ return;
+ }
+ if (!i || i.loading) {
+ stats.classList.add('hidden');
+ body.innerHTML = skeleton(2);
+ return;
+ }
+ if (i.error) {
+ stats.classList.add('hidden');
+ body.innerHTML = errorState(i.error, 'incoming');
+ return;
+ }
+
+ $('count-incoming').textContent = i.rows.length ? String(i.rows.length) : '';
+
+ if (i.summary && i.rows.length) {
+ stats.classList.remove('hidden');
+ stats.innerHTML =
+ stat('Paying schedules', String(i.summary.active), `of ${i.summary.schedules}`) +
+ stat('Received', i.summary.received_total_display, 'USDC') +
+ stat('Charges received', String(i.summary.charges_total)) +
+ stat('Next arrival', relTime(i.summary.next_charge_at));
+ } else {
+ stats.classList.add('hidden');
+ }
+
+ if (!i.rows.length) {
+ body.innerHTML = emptyState({
+ icon: '📥',
+ title: 'Nothing is paying into your agents yet',
+ body: 'When a recurring payment is pointed at an agent you own, it appears here with the paying wallet, the amount per period and every charge it has settled.',
+ action: '<a class="btn" href="/agents">Open your agents</a>',
+ });
+ return;
+ }
+
+ body.innerHTML = `<div class="cards">${i.rows
+ .map((s) => subscriptionCard(s, { role: 'creator' }))
+ .join('')}</div>`;
+}
+
+function dcaCard(s) {
+ const busy = state.busy.has(s.id);
+ const last = s.last_execution;
+ const notice =
+ s.status === 'paused' && s.last_error
+ ? `<div class="notice bad"><strong>Paused:</strong> ${esc(s.last_error)}</div>`
+ : s.last_error
+ ? `<div class="notice warn"><strong>Last run:</strong> ${esc(s.last_error)}</div>`
+ : '';
+
+ return `<article class="card" data-dca="${esc(s.id)}">
+ <div class="card-top">
+ <div>
+ <div class="card-title">USDC into ${esc(s.token_out_symbol)} ${statusPill(s.status)}</div>
+ <div class="card-sub">${esc(s.amount_display)} USDC ${esc(s.period_label)} on chain ${esc(
+ String(s.chain_id),
+ )}, ${esc(String(s.slippage_bps))} bps max slippage</div>
+ </div>
+ <div class="amount">${esc(String(s.executions_total ?? 0))} <small>swaps filled</small></div>
+ </div>
+
+ <div class="meta">
+ <div><span class="mk">next</span><span class="mv">${esc(
+ s.status === 'active' ? relTime(s.next_execution_at) : 'not scheduled',
+ )}</span></div>
+ <div><span class="mk">last</span><span class="mv">${esc(relTime(s.last_execution_at))}</span></div>
+ ${
+ last?.tx_hash
+ ? `<div><span class="mk">last tx</span><span class="mv">${esc(shortAddr(last.tx_hash))}</span></div>`
+ : ''
+ }
+ </div>
+
+ ${notice}
+
+ <div class="actions">
+ ${
+ s.status === 'active'
+ ? `<button data-dact="pause" data-id="${esc(s.id)}"${busy ? ' disabled' : ''}>Pause</button>`
+ : ''
+ }
+ ${
+ s.status === 'paused'
+ ? `<button class="primary" data-dact="resume" data-id="${esc(s.id)}"${busy ? ' disabled' : ''}>Resume</button>`
+ : ''
+ }
+ ${
+ s.status !== 'cancelled'
+ ? `<button class="danger" data-dact="cancel" data-id="${esc(s.id)}"${busy ? ' disabled' : ''}>Cancel</button>`
+ : ''
+ }
+ </div>
+ </article>`;
+}
+
+function renderDca() {
+ const body = $('dca-body');
+ const d = state.dca;
+
+ if (!state.signedIn) {
+ body.innerHTML =
+ '<p class="muted" style="font-size:12.5px;margin:0">Sign in to see the DCA schedules on your agents.</p>';
+ return;
+ }
+ if (!state.agentId) {
+ body.innerHTML =
+ '<p class="muted" style="font-size:12.5px;margin:0">Create an agent to run a DCA schedule on it.</p>';
+ return;
+ }
+ if (!d || d.loading) {
+ body.innerHTML = skeleton(1);
+ return;
+ }
+ if (d.error) {
+ body.innerHTML = errorState(d.error, 'dca');
+ return;
+ }
+ if (!d.rows.length) {
+ body.innerHTML = emptyState({
+ icon: '📈',
+ title: 'No DCA schedule on this agent',
+ body: 'A DCA schedule buys a fixed amount of a token on every period out of the same signed permission. Start one from the agent\'s own page, then manage it here.',
+ action: `<a class="btn" href="/agents/${esc(state.agentId)}">Open this agent</a>`,
+ });
+ return;
+ }
+ body.innerHTML = `<div class="cards">${d.rows.map(dcaCard).join('')}</div>`;
+}
+
+// ── Create flow ─────────────────────────────────────────────────────────────
+
+async function loadDelegations() {
+ const sel = $('c-delegation');
+ const note = $('c-delegation-note');
+ const submit = $('c-submit');
+
+ if (!state.agentId) {
+ sel.disabled = true;
+ sel.innerHTML = '<option value="">Pick an agent first</option>';
+ note.textContent = '';
+ submit.disabled = true;
+ return;
+ }
+
+ sel.disabled = true;
+ sel.innerHTML = '<option value="">Loading permissions…</option>';
+ note.textContent = '';
+
+ let delegations = [];
+ try {
+ const res = await apiFetch(
+ `/api/permissions/list?agentId=${encodeURIComponent(state.agentId)}&status=active`,
+ { allowAnonymous: true },
+ );
+ if (res.ok) delegations = (await readBody(res)).delegations || [];
+ } catch {
+ note.textContent = 'Could not load permissions for this agent.';
+ }
+
+ const usable = delegations.filter((d) => !d.expiresAt || new Date(d.expiresAt) > new Date());
+ if (!usable.length) {
+ sel.innerHTML = '<option value="">No active permission on this agent</option>';
+ sel.disabled = true;
+ submit.disabled = true;
+ note.textContent =
+ 'Grant a spending permission on this agent first. A schedule can only spend inside one you signed.';
+ return;
+ }
+
+ sel.innerHTML = usable
+ .map(
+ (d) =>
+ `<option value="${esc(d.id)}">${esc(shortAddr(d.delegator))} on chain ${esc(
+ String(d.chainId),
+ )}, expires ${esc(relTime(d.expiresAt))}</option>`,
+ )
+ .join('');
+ sel.disabled = false;
+ submit.disabled = false;
+ note.textContent = `${usable.length} active permission${usable.length === 1 ? '' : 's'} available.`;
+}
+
+/** USDC has 6 decimals; convert the typed amount to base units without floats. */
+function toBaseUnits(input, decimals = 6) {
+ const raw = String(input ?? '').trim();
+ if (!/^\d*\.?\d*$/.test(raw) || raw === '' || raw === '.') return null;
+ const [whole = '0', frac = ''] = raw.split('.');
+ if (frac.length > decimals) return null;
+ const units = `${whole}${frac.padEnd(decimals, '0')}`.replace(/^0+(?=\d)/, '');
+ return /^\d+$/.test(units) && BigInt(units) > 0n ? units : null;
+}
+
+async function createSchedule() {
+ const submit = $('c-submit');
+ const delegationId = $('c-delegation').value;
+ const amount = toBaseUnits($('c-amount').value);
+ const periodSeconds = Number($('c-period').value);
+
+ if (!state.agentId || !delegationId) return;
+ if (!amount) {
+ toast('Enter an amount above zero with at most 6 decimals.', true);
+ $('c-amount').focus();
+ return;
+ }
+
+ submit.disabled = true;
+ submit.textContent = 'Creating…';
+ try {
+ const res = await apiFetch('/api/agent-subscriptions', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agentId: state.agentId,
+ delegationId,
+ periodSeconds,
+ amountPerPeriod: amount,
+ }),
+ });
+ const body = await readBody(res);
+ if (!res.ok) {
+ toast(body.error_description || `Could not create the schedule (${res.status}).`, true);
+ return;
+ }
+ toast(res.status === 200 ? 'That schedule already exists.' : 'Recurring payment created.');
+ await Promise.all([loadOutgoing(), loadIncoming()]);
+ } catch (err) {
+ toast(err.message || 'Could not reach the API.', true);
+ } finally {
+ submit.disabled = false;
+ submit.textContent = 'Create schedule';
+ }
+}
+
+// ── Lifecycle actions ───────────────────────────────────────────────────────
+
+async function setSubscriptionStatus(id, action) {
+ state.busy.add(id);
+ renderOutgoing();
+ try {
+ const res = await apiFetch(`/api/agent-subscriptions?id=${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ action }),
+ });
+ const body = await readBody(res);
+ if (!res.ok) {
+ toast(body.error_description || `Could not ${action} the schedule.`, true);
+ return;
+ }
+ toast(action === 'pause' ? 'Schedule paused. No charges until you resume.' : 'Schedule resumed.');
+ await Promise.all([loadOutgoing(), loadIncoming()]);
+ } catch (err) {
+ toast(err.message || 'Could not reach the API.', true);
+ } finally {
+ state.busy.delete(id);
+ renderOutgoing();
+ }
+}
+
+async function cancelSubscription(id) {
+ state.busy.add(id);
+ renderOutgoing();
+ try {
+ const res = await apiFetch(`/api/agent-subscriptions?id=${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ });
+ const body = await readBody(res);
+ if (!res.ok) {
+ toast(body.error_description || 'Could not cancel the schedule.', true);
+ return;
+ }
+ toast('Schedule canceled. The signed permission is still yours to revoke separately.');
+ await Promise.all([loadOutgoing(), loadIncoming()]);
+ } catch (err) {
+ toast(err.message || 'Could not reach the API.', true);
+ } finally {
+ state.busy.delete(id);
+ renderOutgoing();
+ }
+}
+
+async function setDcaStatus(id, action) {
+ state.busy.add(id);
+ renderDca();
+ try {
+ const res = await apiFetch(`/api/dca-strategies/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ action }),
+ });
+ const body = await readBody(res);
+ if (!res.ok) {
+ toast(body.error_description || `Could not ${action} the strategy.`, true);
+ return;
+ }
+ toast(action === 'pause' ? 'DCA paused. No swaps until you resume.' : 'DCA resumed.');
+ await loadDca();
+ } catch (err) {
+ toast(err.message || 'Could not reach the API.', true);
+ } finally {
+ state.busy.delete(id);
+ renderDca();
+ }
+}
+
+async function cancelDca(id) {
+ state.busy.add(id);
+ renderDca();
+ try {
+ const res = await apiFetch(`/api/dca-strategies/${encodeURIComponent(id)}`, {
+ method: 'DELETE',
+ });
+ const body = await readBody(res);
+ if (!res.ok) {
+ toast(body.error_description || 'Could not cancel the strategy.', true);
+ return;
+ }
+ toast('DCA strategy canceled.');
+ await loadDca();
+ } catch (err) {
+ toast(err.message || 'Could not reach the API.', true);
+ } finally {
+ state.busy.delete(id);
+ renderDca();
+ }
+}
+
+async function toggleHistory(id) {
+ if (state.openHistory.has(id)) {
+ state.openHistory.delete(id);
+ renderOutgoing();
+ renderIncoming();
+ return;
+ }
+ state.openHistory.add(id);
+ renderOutgoing();
+ renderIncoming();
+
+ try {
+ const detail = await loadCharges(id);
+ for (const bucket of [state.outgoing, state.incoming]) {
+ const row = bucket?.rows?.find((r) => r.id === id);
+ if (row) row.charges = detail.charges;
+ }
+ } catch (err) {
+ toast(err.message || 'Could not load the charge history.', true);
+ }
+ renderOutgoing();
+ renderIncoming();
+}
+
+// ── Confirm modal ───────────────────────────────────────────────────────────
+
+let pendingConfirm = null;
+
+function askConfirm(message, onYes) {
+ pendingConfirm = onYes;
+ $('confirm-body').textContent = message;
+ $('confirm-backdrop').classList.add('open');
+ $('confirm-no').focus();
+}
+
+function closeConfirm() {
+ pendingConfirm = null;
+ $('confirm-backdrop').classList.remove('open');
+}
+
+// ── Wiring ──────────────────────────────────────────────────────────────────
+
+function selectTab(name) {
+ const outgoing = name === 'outgoing';
+ $('tab-outgoing').setAttribute('aria-selected', String(outgoing));
+ $('tab-incoming').setAttribute('aria-selected', String(!outgoing));
+ $('view-outgoing').classList.toggle('hidden', !outgoing);
+ $('view-incoming').classList.toggle('hidden', outgoing);
+ history.replaceState(null, '', outgoing ? location.pathname : `${location.pathname}#incoming`);
+}
+
+function wire() {
+ $('tab-outgoing').addEventListener('click', () => selectTab('outgoing'));
+ $('tab-incoming').addEventListener('click', () => selectTab('incoming'));
+
+ $('c-agent').addEventListener('change', (e) => {
+ state.agentId = e.target.value;
+ localStorage.setItem(AGENT_KEY, state.agentId);
+ $('c-grant-link').href = state.agentId ? `/agents/${state.agentId}` : '/docs/permissions';
+ loadDelegations();
+ loadDca();
+ });
+ $('c-submit').addEventListener('click', createSchedule);
+
+ document.addEventListener('click', (e) => {
+ const retry = e.target.closest('[data-retry]');
+ if (retry) {
+ const which = retry.dataset.retry;
+ if (which === 'outgoing') loadOutgoing();
+ else if (which === 'incoming') loadIncoming();
+ else loadDca();
+ return;
+ }
+
+ const sub = e.target.closest('[data-act]');
+ if (sub) {
+ const { act, id } = sub.dataset;
+ if (act === 'history') toggleHistory(id);
+ else if (act === 'pause' || act === 'resume') setSubscriptionStatus(id, act);
+ else if (act === 'cancel') {
+ askConfirm(
+ 'This stops every future charge on that recurring payment.',
+ () => cancelSubscription(id),
+ );
+ }
+ return;
+ }
+
+ const dca = e.target.closest('[data-dact]');
+ if (dca) {
+ const { dact, id } = dca.dataset;
+ if (dact === 'pause' || dact === 'resume') setDcaStatus(id, dact);
+ else if (dact === 'cancel') {
+ askConfirm('This stops every future swap on that DCA strategy.', () => cancelDca(id));
+ }
+ }
+ });
+
+ $('confirm-no').addEventListener('click', closeConfirm);
+ $('confirm-yes').addEventListener('click', () => {
+ const fn = pendingConfirm;
+ closeConfirm();
+ fn?.();
+ });
+ $('confirm-backdrop').addEventListener('click', (e) => {
+ if (e.target === $('confirm-backdrop')) closeConfirm();
+ });
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && $('confirm-backdrop').classList.contains('open')) closeConfirm();
+ });
+}
+
+async function boot() {
+ wire();
+ if (location.hash === '#incoming') selectTab('incoming');
+
+ await loadAgents();
+
+ const sel = $('c-agent');
+ if (!state.signedIn) {
+ sel.innerHTML = '<option value="">Sign in to load your agents</option>';
+ sel.disabled = true;
+ $('c-submit').disabled = true;
+ } else if (!state.agents.length) {
+ sel.innerHTML = '<option value="">No agents yet</option>';
+ sel.disabled = true;
+ $('c-submit').disabled = true;
+ $('c-delegation-note').innerHTML =
+ 'Create an agent first, then grant it a spending permission.';
+ } else {
+ sel.innerHTML = state.agents
+ .map(
+ (a) =>
+ `<option value="${esc(a.id)}"${a.id === state.agentId ? ' selected' : ''}>${esc(
+ a.name || a.id,
+ )}</option>`,
+ )
+ .join('');
+ $('c-grant-link').href = state.agentId ? `/agents/${state.agentId}` : '/docs/permissions';
+ loadDelegations();
+ }
+
+ await Promise.all([loadOutgoing(), loadIncoming(), loadDca()]);
+}
+
+boot();
diff --git a/vercel.json b/vercel.json
index 94caeb196..839257910 100644
--- a/vercel.json
+++ b/vercel.json
@@ -850,6 +850,10 @@
"src": "/strategy-lab/",
"dest": "/strategy-lab.html"
},
+ {
+ "src": "/recurring/?",
+ "dest": "/recurring.html"
+ },
{
"src": "/pump-visualizer/?",
"dest": "/pump-visualizer.html"
diff --git a/vite.config.js b/vite.config.js
index adaf61dd9..9ce479744 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -1460,6 +1460,8 @@ support: resolve(__dirname, 'pages/support.html'),
'/evm-wallet/': resolve(root, 'public/evm-wallet.html'),
'/strategy-lab': resolve(root, 'public/strategy-lab.html'),
'/strategy-lab/': resolve(root, 'public/strategy-lab.html'),
+ '/recurring': resolve(root, 'public/recurring.html'),
+ '/recurring/': resolve(root, 'public/recurring.html'),
'/sitemap': resolve(root, 'public/sitemap/index.html'),
'/sitemap/': resolve(root, 'public/sitemap/index.html'),
// Guessable aliases — prod 308s these to /sitemap (vercel.json)