402mob-runtime 0.0.0-stage → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +60 -2
- package/THIRD-PARTY-NOTICES.txt +1993 -0
- package/bin/402mob-runtime +2 -0
- package/dist/runtime/cli.js +66408 -0
- package/package.json +28 -4
- package/public/wallet/app.js +377 -0
- package/public/wallet/browser-wallet.js +212 -0
- package/public/wallet/favicon.svg +4 -0
- package/public/wallet/index.html +104 -0
- package/public/wallet/metamask.js +2 -0
- package/public/wallet/style.css +10 -0
package/package.json
CHANGED
|
@@ -1,6 +1,30 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "402mob-runtime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Owner-controlled Base USDC delegation and recoverable buyer/seller workflows",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"homepage": "https://evidence.contact/agent-runtime.md",
|
|
8
|
+
"engines": {
|
|
9
|
+
"node": ">=24.0.0"
|
|
10
|
+
},
|
|
11
|
+
"os": [
|
|
12
|
+
"linux",
|
|
13
|
+
"darwin"
|
|
14
|
+
],
|
|
15
|
+
"bin": {
|
|
16
|
+
"402mob-runtime": "bin/402mob-runtime"
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"bin/",
|
|
20
|
+
"dist/",
|
|
21
|
+
"public/wallet/",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"THIRD-PARTY-NOTICES.txt"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public",
|
|
28
|
+
"registry": "https://registry.npmjs.org/"
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { USDC, BASE_CHAIN, BrowserWallet, FundingJournal, discoverBrowserWallets } from './browser-wallet.js?v=1';
|
|
2
|
+
export { USDC };
|
|
3
|
+
export function localGateway(value) {
|
|
4
|
+
const u = new URL(value);
|
|
5
|
+
if (u.protocol !== 'http:' || !['127.0.0.1', 'localhost'].includes(u.hostname) || !u.port || u.username || u.password || u.pathname !== '/' || u.search || u.hash) throw new Error('local_gateway_required');
|
|
6
|
+
return u.origin;
|
|
7
|
+
}
|
|
8
|
+
export function initialGateway(pageUrl) {
|
|
9
|
+
const page = new URL(pageUrl);
|
|
10
|
+
return page.protocol === 'http:' && ['127.0.0.1', 'localhost'].includes(page.hostname) && page.pathname === '/'
|
|
11
|
+
? localGateway(page.origin) : 'http://127.0.0.1:4032';
|
|
12
|
+
}
|
|
13
|
+
export function formatUSDC(value) {
|
|
14
|
+
if (!/^\d+$/.test(String(value))) throw new Error('invalid_amount');
|
|
15
|
+
const n = BigInt(value), fraction = String(n % 1000000n).padStart(6, '0').replace(/0+$/, '');
|
|
16
|
+
return String(n / 1000000n) + (fraction ? '.' + fraction : '.00');
|
|
17
|
+
}
|
|
18
|
+
export function amount(value) {
|
|
19
|
+
if (!/^(?!0(?:\.0{1,6})?$)(0|[1-9][0-9]{0,5})(\.[0-9]{1,6})?$/.test(value)) throw new Error('invalid_amount');
|
|
20
|
+
const [whole, part = ''] = value.split('.'); return BigInt(whole) * 1000000n + BigInt(part.padEnd(6, '0'));
|
|
21
|
+
}
|
|
22
|
+
export function delegationInput(values, requestId, now = Date.now()) {
|
|
23
|
+
const id = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
24
|
+
if (!id.test(requestId)) throw new Error('invalid_request_id');
|
|
25
|
+
if (typeof values.name !== 'string' || !values.name || values.name.length > 80) throw new Error('invalid_agent_name');
|
|
26
|
+
amount(values.maxTotalUSDC);
|
|
27
|
+
const policy = { name: values.name, maxTotalUSDC: values.maxTotalUSDC };
|
|
28
|
+
for (const key of ['merchantId', 'payee', 'capability', 'maxPerPaymentUSDC', 'expiresAt']) {
|
|
29
|
+
if (values[key] !== undefined && values[key] !== '') policy[key] = values[key];
|
|
30
|
+
}
|
|
31
|
+
if (policy.merchantId !== undefined && !id.test(policy.merchantId)) throw new Error('invalid_merchant_id');
|
|
32
|
+
if (policy.payee !== undefined && (!/^0x[0-9a-f]{40}$/i.test(policy.payee) || /^0x0{40}$/i.test(policy.payee))) throw new Error('invalid_payee');
|
|
33
|
+
if (policy.capability !== undefined && !['text-statistics-v1', 'prepared-artifact-v1'].includes(policy.capability)) throw new Error('unsupported_capability');
|
|
34
|
+
if (policy.maxPerPaymentUSDC !== undefined && amount(policy.maxPerPaymentUSDC) > amount(policy.maxTotalUSDC)) throw new Error('delegation_limit_invalid');
|
|
35
|
+
if (policy.expiresAt !== undefined) {
|
|
36
|
+
const expiry = new Date(policy.expiresAt);
|
|
37
|
+
if (!Number.isFinite(expiry.getTime()) || expiry.getTime() <= now) throw new Error('delegation_expired');
|
|
38
|
+
policy.expiresAt = expiry.toISOString();
|
|
39
|
+
}
|
|
40
|
+
return { requestId, policy };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
if (typeof document !== 'undefined') {
|
|
44
|
+
const $ = id => document.getElementById(id);
|
|
45
|
+
let gateway = 'http://127.0.0.1:4032', session = null, state = null, epoch = 0, pending = null, sent = false, refreshing = null;
|
|
46
|
+
let budgetTarget = null, budgetPending = null;
|
|
47
|
+
let customer = null, fundingReview = null, fundingEpoch = null, fundingMemory = null;
|
|
48
|
+
let fundingJournal;
|
|
49
|
+
try { fundingJournal = new FundingJournal(window.sessionStorage); } catch { fundingJournal = new FundingJournal(null); }
|
|
50
|
+
const messages = {
|
|
51
|
+
local_gateway_required: 'Use the signer URL on localhost or 127.0.0.1, including its port.',
|
|
52
|
+
pairing_invalid_or_expired: 'This pairing link was used or expired. Press Enter in the signer terminal for a fresh link.',
|
|
53
|
+
owner_session_required: 'The owner session expired. Open a fresh pairing link from your signer.',
|
|
54
|
+
wallet_response_unreadable: 'The signer’s response was incomplete. Refresh state, or recover the same delegation request.',
|
|
55
|
+
schema_mismatch: 'The signer rejected the fields. Correct them and review the delegation again.',
|
|
56
|
+
invalid_amount: 'Use a positive USDC amount with at most six decimal places; no commas or exponent notation.',
|
|
57
|
+
delegation_limit_invalid: 'The per-payment limit must fit this agent’s total limit, and that total must fit the wallet’s lifetime limit.',
|
|
58
|
+
delegation_expired: 'Choose an expiry in the future.', invalid_payee: 'Enter a nonzero Base receiving address.',
|
|
59
|
+
invalid_merchant_id: 'Enter the seller’s merchant UUID.', invalid_agent_name: 'Use an agent label of 1–80 characters.',
|
|
60
|
+
delegation_request_conflict: 'This request ID already belongs to different terms. Inspect existing delegations.',
|
|
61
|
+
chain_unavailable: 'The signer could not read Base. Balance is unavailable; try Refresh again.',
|
|
62
|
+
wrong_rpc_chain: 'The configured RPC is not Base mainnet. Check the signer configuration.',
|
|
63
|
+
wallet_already_exists: 'This directory already holds a wallet with a different lifetime spending limit. Reconnect to inspect it.',
|
|
64
|
+
local_connection_failed: 'Cannot reach the signer. Check it is running, allow localhost access in your browser, or open the local console link printed in the terminal.',
|
|
65
|
+
};
|
|
66
|
+
function notice(message, error = false) { $('notice').textContent = message; $('notice').dataset.error = String(error); }
|
|
67
|
+
function fail(error) { if (error.message !== 'session_changed') notice(messages[error.message] || error.message, true); }
|
|
68
|
+
function clear() {
|
|
69
|
+
budgetTarget = null; budgetPending = null; $('budget-form').hidden = true; $('agent-setup').hidden = true; $('agent-setup-command').textContent = ''; $('agent-next-command').textContent = '';
|
|
70
|
+
epoch++; session = null; state = null; pending = null; sent = false; refreshing = null;
|
|
71
|
+
$('connection').hidden = false; $('create-wallet').hidden = true; $('owner-panels').hidden = true;
|
|
72
|
+
$('wallet').hidden = true; $('permissions-prerequisite').hidden = false; $('activity-link').hidden = true;
|
|
73
|
+
$('refresh').hidden = true; $('disconnect').hidden = true; $('grant-review').hidden = true; $('grant-form').hidden = false;
|
|
74
|
+
$('delegation-list').replaceChildren(); $('activity-list').replaceChildren(); $('wallet-address').textContent = '';
|
|
75
|
+
$('balance').textContent = '—'; $('pair-code').value = ''; $('grant-form').reset(); $('review-terms').replaceChildren();
|
|
76
|
+
for (const id of ['reserved', 'spent', 'remaining']) $(id).textContent = '—';
|
|
77
|
+
for (const id of ['wallet-context', 'merchant-info', 'grant-recovery']) $(id).textContent = '';
|
|
78
|
+
$('wallet-limit').value = ''; $('balance-time').textContent = 'Balance has not been read.';
|
|
79
|
+
fundingReview = null; fundingEpoch = null; renderCustomer();
|
|
80
|
+
}
|
|
81
|
+
async function api(path, body, authenticated = true) {
|
|
82
|
+
const current = epoch, headers = { 'X-402Mob-Wallet': '1' };
|
|
83
|
+
if (body !== undefined) headers['Content-Type'] = 'application/json';
|
|
84
|
+
if (authenticated) { if (!session) throw new Error('owner_session_required'); headers.Authorization = 'Bearer ' + session.token; }
|
|
85
|
+
let response;
|
|
86
|
+
try { response = await fetch(gateway + path, { method: body === undefined ? 'GET' : 'POST', headers,
|
|
87
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }), credentials: 'omit', redirect: 'error', cache: 'no-store',
|
|
88
|
+
referrerPolicy: 'no-referrer', signal: AbortSignal.timeout(15000), targetAddressSpace: 'loopback' }); }
|
|
89
|
+
catch { throw new Error(current === epoch ? 'local_connection_failed' : 'session_changed'); }
|
|
90
|
+
if (current !== epoch) throw new Error('session_changed');
|
|
91
|
+
let data;
|
|
92
|
+
try { data = await response.json(); }
|
|
93
|
+
catch { throw new Error(current === epoch ? 'wallet_response_unreadable' : 'session_changed'); }
|
|
94
|
+
if (current !== epoch) throw new Error('session_changed');
|
|
95
|
+
if (!response.ok) {
|
|
96
|
+
if (response.status === 401 && authenticated) { clear(); notice(messages.owner_session_required, true); }
|
|
97
|
+
const error = new Error(data.error || 'wallet_request_failed'); error.status = response.status; throw error;
|
|
98
|
+
}
|
|
99
|
+
return data;
|
|
100
|
+
}
|
|
101
|
+
function element(tag, text, className) { const n = document.createElement(tag); n.textContent = text; if (className) n.className = className; return n; }
|
|
102
|
+
function button(text, action) { const b = element('button', text); b.type = 'button'; b.addEventListener('click', async () => { b.disabled = true; try { await action(); } catch (e) { fail(e); } finally { b.disabled = false; } }); return b; }
|
|
103
|
+
function download(credential) {
|
|
104
|
+
if (!/^mobrt_[0-9a-f]{64}$/.test(credential.token)) throw new Error('invalid_credential_response');
|
|
105
|
+
const url = URL.createObjectURL(new Blob([JSON.stringify(credential, null, 2) + '\n'], { type: 'application/json' }));
|
|
106
|
+
const a = document.createElement('a'); a.href = url; a.download = '402mob-agent-' + credential.id + '.json';
|
|
107
|
+
$('agent-setup').hidden = false; $('agent-setup-command').textContent = 'chmod 600 /absolute/private/' + a.download + '\n402mob-runtime buyer check --credential /absolute/private/' + a.download;
|
|
108
|
+
$('agent-next-command').textContent = '402mob-runtime buyer workers --credential /absolute/private/' + a.download + '\n402mob-runtime buyer resources --credential /absolute/private/' + a.download;
|
|
109
|
+
document.body.append(a); a.click(); a.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000);
|
|
110
|
+
}
|
|
111
|
+
function render(data) {
|
|
112
|
+
state = data; $('connection').hidden = true; $('refresh').hidden = false; $('disconnect').hidden = false;
|
|
113
|
+
$('create-wallet').hidden = data.initialized; $('owner-panels').hidden = !data.initialized;
|
|
114
|
+
$('wallet').hidden = !data.initialized; $('permissions-prerequisite').hidden = data.initialized; $('activity-link').hidden = !data.initialized;
|
|
115
|
+
renderCustomer();
|
|
116
|
+
if (!data.initialized) return;
|
|
117
|
+
const w = data.wallet;
|
|
118
|
+
$('wallet-address').textContent = w.address;
|
|
119
|
+
$('reserved').textContent = formatUSDC(w.reservedAtomic); $('spent').textContent = formatUSDC(w.spentAtomic); $('remaining').textContent = data.walletLimitUSDC === null ? 'No extra ceiling' : formatUSDC(w.walletRemainingAtomic ?? w.remainingAtomic);
|
|
120
|
+
$('wallet-context').textContent = 'Shared ceiling: ' + (data.walletLimitUSDC === null ? 'none' : data.walletLimitUSDC + ' USDC lifetime') + ' · Service: ' + data.serviceOrigin + ' · Agent task API: ' + data.agentGateway;
|
|
121
|
+
$('delegation-list').replaceChildren();
|
|
122
|
+
for (const d of data.delegations) {
|
|
123
|
+
const row = element('article', '', 'record'); row.append(element('h3', d.policy.name + ' / ' + d.state));
|
|
124
|
+
row.append(element('p', 'Merchant: ' + (d.policy.merchantId || 'agent chooses') + ' · Recipient: ' + (d.policy.payee || 'seller payout')));
|
|
125
|
+
row.append(element('p', 'Per payment: ' + (d.policy.maxPerPaymentUSDC ? d.policy.maxPerPaymentUSDC + ' USDC' : 'up to remaining allocation') + ' · Allocated: ' + d.policy.maxTotalUSDC + ' USDC · Expires: ' + (d.policy.expiresAt ? new Date(d.policy.expiresAt).toLocaleString() : 'no expiry')));
|
|
126
|
+
row.append(element('p', 'Spent: ' + formatUSDC(d.spentAtomic) + ' · Reserved: ' + formatUSDC(d.reservedAtomic) + ' · Remaining grant limit: ' + formatUSDC(d.remainingAtomic) + ' USDC'));
|
|
127
|
+
row.append(element('p', 'Service: ' + (d.policy.capability || 'all supported services') + ' · Delegation ID: ' + d.id));
|
|
128
|
+
const controls = element('div', '', 'actions');
|
|
129
|
+
if (d.credentialRecoverable) controls.append(button(d.state === 'expired' ? 'Download recovery credential' : 'Download credential', async () => { download(await api('/api/delegations/' + d.id + '/credential', {})); notice('The same agent credential was downloaded. Expiry and spending limits are unchanged. Keep it private.'); }));
|
|
130
|
+
if (d.state === 'active') controls.append(button('Increase allocation', () => openBudget(d)));
|
|
131
|
+
if (d.state !== 'revoked') controls.append(button('Revoke spending', async () => { if (!window.confirm('Revoke new spending for ' + d.policy.name + '? Existing signed payments may still settle.')) return; render(await api('/api/delegations/' + d.id + '/revoke', {})); notice('New authorizations revoked. Existing payments and recovery records are retained.'); }));
|
|
132
|
+
row.append(controls); $('delegation-list').append(row);
|
|
133
|
+
}
|
|
134
|
+
if (!data.delegations.length) $('delegation-list').append(element('p', 'No agent delegations yet.', 'note'));
|
|
135
|
+
$('activity-list').replaceChildren();
|
|
136
|
+
for (const job of data.activity) {
|
|
137
|
+
const row = element('article', '', 'record'); row.append(element('h3', job.stage + ' / ' + job.status));
|
|
138
|
+
row.append(element('p', 'Merchant: ' + job.merchantId));
|
|
139
|
+
row.append(element('p', 'Job: ' + job.id + ' · Payment: ' + job.payment + ' · Receipt: ' + (job.verdict || 'not recorded')));
|
|
140
|
+
if (job.ticketId) row.append(element('p', 'Ticket: ' + job.ticketId));
|
|
141
|
+
if (job.operationId) row.append(element('p', 'Operation: ' + job.operationId));
|
|
142
|
+
if (job.transaction) row.append(element('p', 'Transaction: ' + job.transaction));
|
|
143
|
+
if (job.error) row.append(element('p', 'Error: ' + job.error));
|
|
144
|
+
if (job.status === 'needs_attention') row.append(button('Retry same job', async () => { if (!window.confirm('Retry this retained job after correcting its error? Its existing terms and payment remain unchanged.')) return; render(await api('/api/jobs/' + job.id + '/retry', {})); notice('The same job was queued for retry.'); }));
|
|
145
|
+
$('activity-list').append(row);
|
|
146
|
+
}
|
|
147
|
+
if (!data.activity.length) $('activity-list').append(element('p', 'No runtime jobs in this wallet yet.', 'note'));
|
|
148
|
+
}
|
|
149
|
+
async function refresh() {
|
|
150
|
+
if (refreshing === epoch || !session) return; const current = epoch; refreshing = current;
|
|
151
|
+
try {
|
|
152
|
+
render(await api('/api/state')); $('balance').textContent = '—'; $('balance-time').textContent = 'Reading Base…';
|
|
153
|
+
if (state.initialized) {
|
|
154
|
+
const b = await api('/api/balance');
|
|
155
|
+
if (b.address !== state.wallet.address || b.asset.toLowerCase() !== USDC.toLowerCase() || b.network !== 'eip155:8453') throw new Error('balance_identity_mismatch');
|
|
156
|
+
$('balance').textContent = formatUSDC(b.balanceAtomic); $('balance-time').textContent = 'Balance observed ' + new Date(b.observedAt).toLocaleString();
|
|
157
|
+
}
|
|
158
|
+
} catch (e) { if (current === epoch) { $('balance').textContent = '—'; $('balance-time').textContent = 'Balance unavailable. No cached amount is shown.'; fail(e); } }
|
|
159
|
+
finally { if (refreshing === current) refreshing = null; }
|
|
160
|
+
}
|
|
161
|
+
$('connect-form').addEventListener('submit', async event => {
|
|
162
|
+
event.preventDefault(); const b = event.submitter; b.disabled = true;
|
|
163
|
+
try {
|
|
164
|
+
gateway = localGateway($('gateway').value.trim()); epoch++;
|
|
165
|
+
session = await api('/api/session', { code: $('pair-code').value.trim() }, false); $('pair-code').value = '';
|
|
166
|
+
notice('Connected to your signer. Session expires ' + new Date(session.expiresAt).toLocaleTimeString() + '.'); await refresh();
|
|
167
|
+
} catch (e) { fail(e); } finally { b.disabled = false; }
|
|
168
|
+
});
|
|
169
|
+
$('create-form').addEventListener('submit', async event => { event.preventDefault(); const b = event.submitter; b.disabled = true;
|
|
170
|
+
try { const maxTotalUSDC = $('wallet-limit').value.trim() || null; if (maxTotalUSDC !== null) amount(maxTotalUSDC); render(await api('/api/wallet', { maxTotalUSDC })); notice('Wallet created locally. Deposit native Base USDC to its address before purchasing.'); await refresh(); }
|
|
171
|
+
catch (e) { fail(e); } finally { b.disabled = false; }
|
|
172
|
+
});
|
|
173
|
+
function openBudget(delegation) {
|
|
174
|
+
if (budgetPending) { notice('Recover the pending budget update before preparing another.', true); return; }
|
|
175
|
+
budgetTarget = delegation ? { id: delegation.id, expected: delegation.policy.maxTotalUSDC } : { id: null, expected: state.walletLimitUSDC };
|
|
176
|
+
$('budget-title').textContent = delegation ? 'Increase allocation for ' + delegation.policy.name : 'Change shared wallet ceiling';
|
|
177
|
+
$('budget-amount').value = ''; $('budget-amount').disabled = false; $('budget-submit').textContent = 'Review and apply'; $('budget-cancel').hidden = false;
|
|
178
|
+
$('budget-help').textContent = delegation ? 'Enter the new total allocation, including amounts already spent or reserved. Other restrictions stay unchanged.' : 'Enter a lifetime ceiling, or leave empty to remove the extra ceiling. Spent and reserved amounts are retained.';
|
|
179
|
+
$('budget-form').hidden = false;
|
|
180
|
+
}
|
|
181
|
+
$('edit-wallet-limit').addEventListener('click', () => openBudget(null));
|
|
182
|
+
$('budget-cancel').addEventListener('click', () => { if (!budgetPending) { budgetTarget = null; $('budget-form').hidden = true; } });
|
|
183
|
+
$('budget-form').addEventListener('submit', async event => {
|
|
184
|
+
event.preventDefault(); if (!budgetTarget) return; const b = $('budget-submit'); b.disabled = true;
|
|
185
|
+
try {
|
|
186
|
+
if (!budgetPending) {
|
|
187
|
+
const next = $('budget-amount').value.trim() || null; if (next !== null) amount(next);
|
|
188
|
+
if (budgetTarget.id && (next === null || amount(next) < amount(budgetTarget.expected))) throw new Error('delegation_limit_invalid');
|
|
189
|
+
if (!window.confirm((budgetTarget.id ? 'Set this agent’s total allocation to ' : 'Set the shared lifetime ceiling to ') + (next === null ? 'no extra ceiling' : next + ' USDC') + '? Existing spending and pending payments remain recorded.')) return;
|
|
190
|
+
budgetPending = { path: budgetTarget.id ? '/api/delegations/' + budgetTarget.id + '/allocation' : '/api/wallet/limit', body: { requestId: crypto.randomUUID(), maxTotalUSDC: next, ...(budgetTarget.id ? { expectedMaxTotalUSDC: budgetTarget.expected } : { expectedLimitUSDC: budgetTarget.expected }) } };
|
|
191
|
+
}
|
|
192
|
+
$('budget-amount').disabled = true; $('budget-cancel').hidden = true;
|
|
193
|
+
const updated = await api(budgetPending.path, budgetPending.body); budgetPending = null; budgetTarget = null; $('budget-form').hidden = true; render(updated); notice('Budget updated. Spending history and pending authorizations are unchanged.');
|
|
194
|
+
} catch (e) {
|
|
195
|
+
if (e.message === 'session_changed') return;
|
|
196
|
+
if (e.status === 400 || e.status === 409) { budgetPending = null; $('budget-amount').disabled = false; $('budget-cancel').hidden = false; }
|
|
197
|
+
else if (budgetPending) { b.textContent = 'Recover same update'; $('budget-help').textContent = 'Retry this exact update; do not create a replacement. Request: ' + budgetPending.body.requestId; }
|
|
198
|
+
fail(e);
|
|
199
|
+
} finally { b.disabled = false; }
|
|
200
|
+
});
|
|
201
|
+
$('inspect-merchant').addEventListener('click', async () => {
|
|
202
|
+
const b = $('inspect-merchant'); b.disabled = true; const id = $('merchant-id').value.trim(); $('merchant-info').textContent = '';
|
|
203
|
+
try { if (!/^[0-9a-f-]{36}$/i.test(id)) throw new Error('invalid_merchant_id'); const merchant = await api('/api/merchants/' + id);
|
|
204
|
+
if ($('merchant-id').value.trim() !== id) return;
|
|
205
|
+
$('payee').value = merchant.payoutAddress; $('merchant-info').textContent = merchant.name + ' · ' + merchant.payoutAddress;
|
|
206
|
+
} catch (e) { fail(e); } finally { b.disabled = false; }
|
|
207
|
+
});
|
|
208
|
+
$('merchant-id').addEventListener('input', () => { $('merchant-info').textContent = ''; $('payee').value = ''; });
|
|
209
|
+
$('grant-form').addEventListener('submit', event => {
|
|
210
|
+
event.preventDefault();
|
|
211
|
+
try {
|
|
212
|
+
pending = delegationInput({ name: $('agent-name').value.trim(), merchantId: $('merchant-id').value.trim(), payee: $('payee').value.trim(),
|
|
213
|
+
capability: $('capability').value, maxPerPaymentUSDC: $('per-payment').value.trim(), maxTotalUSDC: $('total-limit').value.trim(), expiresAt: $('expires').value }, crypto.randomUUID());
|
|
214
|
+
if (state.walletLimitUSDC !== null && amount(pending.policy.maxTotalUSDC) > amount(state.walletLimitUSDC)) throw new Error('delegation_limit_invalid');
|
|
215
|
+
sent = false; $('review-terms').replaceChildren();
|
|
216
|
+
for (const [label, value] of Object.entries({ Agent: pending.policy.name, 'Allocated USDC': pending.policy.maxTotalUSDC, Merchant: pending.policy.merchantId || 'Agent chooses', Recipient: pending.policy.payee || 'Seller payout', Service: pending.policy.capability || 'All supported services',
|
|
217
|
+
'Per payment': pending.policy.maxPerPaymentUSDC ? pending.policy.maxPerPaymentUSDC + ' USDC' : 'Up to remaining allocation', Expiry: pending.policy.expiresAt || 'No expiry' })) $('review-terms').append(element('dt', label), element('dd', value));
|
|
218
|
+
$('grant-form').hidden = true; $('grant-review').hidden = false; $('cancel-grant').hidden = false; $('confirm-grant').textContent = 'Authorize and download credential'; $('grant-recovery').textContent = '';
|
|
219
|
+
} catch (e) { pending = null; fail(e); }
|
|
220
|
+
});
|
|
221
|
+
$('cancel-grant').addEventListener('click', () => { if (sent) return; pending = null; $('grant-review').hidden = true; $('grant-form').hidden = false; });
|
|
222
|
+
$('confirm-grant').addEventListener('click', async () => {
|
|
223
|
+
if (!pending) return; const b = $('confirm-grant'); b.disabled = true; sent = true; $('cancel-grant').hidden = true;
|
|
224
|
+
try { download(await api('/api/delegations', pending)); pending = null; sent = false; $('grant-review').hidden = true; $('grant-form').hidden = false; $('grant-form').reset();
|
|
225
|
+
notice('Agent credential downloaded. Pass it to the agent’s secret store; keep the wallet directory private.'); await refresh(); }
|
|
226
|
+
catch (e) {
|
|
227
|
+
if (e.message === 'session_changed') return;
|
|
228
|
+
// Explicit rejection or confirmed revocation unlocks editing. Unknown outcomes retain the exact request.
|
|
229
|
+
const rejected = e.status === 400 && e.message === 'schema_mismatch' || e.status === 409 && ['delegation_expired', 'delegation_limit_invalid', 'delegation_capacity', 'delegation_revoked'].includes(e.message);
|
|
230
|
+
if (pending && rejected) {
|
|
231
|
+
pending = null; sent = false; $('grant-review').hidden = true; $('grant-form').hidden = false; $('cancel-grant').hidden = false;
|
|
232
|
+
$('grant-recovery').textContent = '';
|
|
233
|
+
} else if (pending) { b.textContent = 'Recover same credential'; $('grant-recovery').textContent = 'Keep this request: ' + pending.requestId + '. Retry recovers the same delegation. After reloading, inspect the delegation list before creating another.'; }
|
|
234
|
+
fail(e);
|
|
235
|
+
}
|
|
236
|
+
finally { b.disabled = false; }
|
|
237
|
+
});
|
|
238
|
+
$('refresh').addEventListener('click', refresh);
|
|
239
|
+
$('disconnect').addEventListener('click', async () => {
|
|
240
|
+
const logout = api('/api/logout', {}); clear();
|
|
241
|
+
notice('Disconnected. Agent delegations remain active until revoked or expired.');
|
|
242
|
+
try { await logout; } catch { /* Never restore an ended session, including if logout cannot reach the signer. */ }
|
|
243
|
+
});
|
|
244
|
+
$('copy-address').addEventListener('click', async () => { try { await navigator.clipboard.writeText(state.wallet.address); notice('Receiving address copied. Use native USDC on Base.'); } catch { notice('Select and copy the receiving address shown above.', true); } });
|
|
245
|
+
|
|
246
|
+
const walletMessages = {
|
|
247
|
+
browser_wallet_missing: 'No compatible browser wallet was detected. Enable an Ethereum wallet extension, then scan again.',
|
|
248
|
+
browser_wallet_changed: 'The connected account or network changed. Refresh and review the deposit again.',
|
|
249
|
+
browser_wallet_account_required: 'Choose an account in your wallet to connect.',
|
|
250
|
+
browser_wallet_base_required: 'Switch your wallet to Base before funding or checking a transfer.',
|
|
251
|
+
browser_wallet_usdc_insufficient: 'The connected wallet account has insufficient native Base USDC.',
|
|
252
|
+
browser_wallet_gas_required: 'Your wallet account needs Base ETH to pay the deposit transaction gas.',
|
|
253
|
+
funding_record_exists: 'Resolve the existing funding record before starting another deposit.',
|
|
254
|
+
funding_review_required: 'Review the deposit again before requesting your wallet confirmation.',
|
|
255
|
+
funding_review_expired: 'The deposit review expired. Review its terms again.',
|
|
256
|
+
funding_recipient_changed: 'The paired agent wallet changed. Review its receiving address again.',
|
|
257
|
+
funding_outcome_unknown: 'The wallet response was interrupted. Check your wallet activity and recover the transaction hash below; do not send again.',
|
|
258
|
+
funding_hash_not_saved: 'The transaction was submitted, but its hash could not be saved in this tab. Copy the hash below before closing the page.',
|
|
259
|
+
funding_hash_required: 'Paste the Base transaction hash from your wallet activity.',
|
|
260
|
+
funding_transaction_unavailable: 'The transaction is not available yet. Keep this record and check again.',
|
|
261
|
+
funding_transaction_mismatch: 'This transaction does not match the recorded sender, token, recipient and amount.',
|
|
262
|
+
funding_nonce_mismatch: 'This transaction has a different nonce. Use the original deposit or its replacement.',
|
|
263
|
+
funding_transaction_predates_intent: 'This transaction predates this deposit attempt. Check your wallet activity for the current transaction.',
|
|
264
|
+
funding_legacy_recovery_required: 'This older record has no nonce binding. Only its original saved hash can be checked here. Keep the record and inspect your wallet activity before sending again.',
|
|
265
|
+
funding_request_pending: 'A deposit or receipt check is already running. Wait for it to finish.',
|
|
266
|
+
funding_transfer_mismatch: 'The receipt does not contain the recorded USDC transfer. Keep the record for inspection.',
|
|
267
|
+
funding_storage_unavailable: 'Tab storage is unavailable. Connection still works; funding requires storage for safe recovery.',
|
|
268
|
+
funding_record_invalid: 'This tab has an unreadable funding record. Inspect your wallet activity before clearing browser storage.',
|
|
269
|
+
invalid_amount: messages.invalid_amount,
|
|
270
|
+
invalid_funding_terms: 'Choose a different agent receiving address and a positive USDC amount.',
|
|
271
|
+
};
|
|
272
|
+
function customerNotice(text, error = false) { $('customer-notice').textContent = text; $('customer-notice').dataset.error = String(error); }
|
|
273
|
+
function customerFail(error) {
|
|
274
|
+
if (error.message === 'session_changed') return;
|
|
275
|
+
if (error.record) fundingMemory = error.record;
|
|
276
|
+
customerNotice(error.code === 4200 || error.code === -32601 ? 'This wallet does not support the requested method. Use a compatible Ethereum wallet, or select Base manually for a network change.' : error.code === 4001 ? 'The request was rejected in your wallet.' : error.code === -32002 ? 'A wallet request is already open. Finish it in the extension.' : walletMessages[error.message] || messages[error.message] || 'Your wallet could not complete the request. Check the extension and try refreshing.', true);
|
|
277
|
+
}
|
|
278
|
+
function renderCustomer() {
|
|
279
|
+
const s = customer?.state, connected = Boolean(s?.account);
|
|
280
|
+
$('customer-connected').hidden = !connected;
|
|
281
|
+
$('browser-wallet-connect').hidden = connected; $('browser-wallet-disconnect').hidden = !customer;
|
|
282
|
+
$('browser-wallet-select').disabled = Boolean(customer);
|
|
283
|
+
$('customer-address').textContent = s?.account || '';
|
|
284
|
+
$('customer-network').textContent = s?.chainId === BASE_CHAIN ? 'Base / 8453' : s?.chainId ? 'Network ' + BigInt(s.chainId).toString() : 'Not connected';
|
|
285
|
+
$('customer-usdc').textContent = s?.usdcAtomic === null || s?.usdcAtomic === undefined ? '—' : formatUSDC(s.usdcAtomic) + ' USDC';
|
|
286
|
+
$('customer-gas').textContent = s?.ethAtomic === null || s?.ethAtomic === undefined ? '' : BigInt(s.ethAtomic) > 0n ? 'Some Base ETH is available. Check your wallet’s gas estimate before confirming.' : 'Your wallet account needs Base ETH to pay the deposit gas fee.';
|
|
287
|
+
$('browser-wallet-switch').hidden = !connected || s.chainId === BASE_CHAIN;
|
|
288
|
+
if (fundingReview && (fundingReview !== customer?.review || fundingEpoch !== epoch)) fundingReview = null;
|
|
289
|
+
$('funding-review').hidden = !fundingReview;
|
|
290
|
+
$('funding-target').textContent = state?.initialized ? state.wallet.address : 'Complete step 01 to see your agent wallet’s address.';
|
|
291
|
+
let record = fundingMemory;
|
|
292
|
+
try { record ||= fundingJournal.read(); } catch (error) { customerFail(error); }
|
|
293
|
+
$('funding-form').hidden = !connected || !state?.initialized || !session || s.chainId !== BASE_CHAIN || Boolean(fundingReview) || Boolean(record);
|
|
294
|
+
$('funding-record').hidden = !record;
|
|
295
|
+
if (record) {
|
|
296
|
+
$('funding-record-text').textContent = record.status + ' · ' + formatUSDC(record.amountAtomic) + ' USDC · from ' + record.from + ' · to ' + record.to;
|
|
297
|
+
$('funding-record-hash').textContent = record.hash || 'Hash not received. Check your wallet activity before sending again.';
|
|
298
|
+
$('funding-hash-input').hidden = false;
|
|
299
|
+
$('funding-check').disabled = !customer || s?.chainId !== BASE_CHAIN || customer.busy;
|
|
300
|
+
$('funding-new').hidden = !['confirmed', 'reverted', 'cancelled'].includes(record.status);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
let discoveredWallets = [];
|
|
304
|
+
const discovery = discoverBrowserWallets(window, () => {
|
|
305
|
+
const selected = $('browser-wallet-select').value;
|
|
306
|
+
const previous = discoveredWallets.find(w => w.id === selected)?.provider;
|
|
307
|
+
$('browser-wallet-select').replaceChildren();
|
|
308
|
+
const wallets = discovery.list();
|
|
309
|
+
for (const [i, wallet] of wallets.entries()) { const option = element('option', wallet.name + (wallets.length > 1 ? ' / ' + (i + 1) : '')); option.value = wallet.id; $('browser-wallet-select').append(option); }
|
|
310
|
+
const active = wallets.find(w => w.provider === (customer?.provider || previous));
|
|
311
|
+
if (active) $('browser-wallet-select').value = active.id;
|
|
312
|
+
else if (wallets.some(w => w.id === selected)) $('browser-wallet-select').value = selected;
|
|
313
|
+
if (!wallets.length) { const option = element('option', 'No browser wallets detected'); option.value = ''; $('browser-wallet-select').append(option); }
|
|
314
|
+
discoveredWallets = wallets;
|
|
315
|
+
});
|
|
316
|
+
$('browser-wallet-scan').addEventListener('click', () => { discovery.scan(); if (!discovery.list().length) customerFail(new Error('browser_wallet_missing')); });
|
|
317
|
+
$('browser-wallet-connect').addEventListener('click', async () => {
|
|
318
|
+
const b = $('browser-wallet-connect'); b.disabled = true;
|
|
319
|
+
try {
|
|
320
|
+
const chosen = discovery.list().find(w => w.id === $('browser-wallet-select').value);
|
|
321
|
+
if (!chosen) throw new Error('browser_wallet_missing');
|
|
322
|
+
customer?.disconnect(); customer = new BrowserWallet(chosen.provider, fundingJournal, renderCustomer, { pendingRequestIsRejection: chosen.pendingRequestIsRejection });
|
|
323
|
+
await customer.connect(); customerNotice(customer.state.chainId === BASE_CHAIN ? 'Wallet connected on Base. Review a deposit to fund your agent wallet.' : 'Wallet connected. Switch to Base to view its USDC balance and fund your agent wallet.');
|
|
324
|
+
} catch (error) { customerFail(error); } finally { b.disabled = false; renderCustomer(); }
|
|
325
|
+
});
|
|
326
|
+
$('browser-wallet-disconnect').addEventListener('click', () => { customer?.disconnect(); customer = null; fundingReview = null; renderCustomer(); customerNotice('Disconnected from this page. Manage saved site permissions in your wallet. Any funding record is retained.'); });
|
|
327
|
+
for (const [id, action] of [['browser-wallet-refresh', () => customer?.refresh()], ['browser-wallet-switch', () => customer?.switchBase()]]) $(id).addEventListener('click', async () => {
|
|
328
|
+
$(id).disabled = true; try { await action(); } catch (error) { customerFail(error); } finally { $(id).disabled = false; renderCustomer(); }
|
|
329
|
+
});
|
|
330
|
+
$('funding-form').addEventListener('submit', async event => {
|
|
331
|
+
event.preventDefault(); event.submitter.disabled = true; const current = epoch, wallet = customer;
|
|
332
|
+
try {
|
|
333
|
+
const latest = await api('/api/state');
|
|
334
|
+
if (!latest.initialized || latest.wallet.asset.toLowerCase() !== USDC.toLowerCase() || latest.wallet.network !== 'eip155:8453') throw new Error('funding_recipient_changed');
|
|
335
|
+
const review = await wallet.prepareFunding(latest.wallet.address, $('funding-amount').value.trim());
|
|
336
|
+
if (current !== epoch || wallet !== customer) throw new Error('session_changed');
|
|
337
|
+
fundingReview = review; fundingEpoch = current;
|
|
338
|
+
$('funding-review-terms').textContent = formatUSDC(review.amountAtomic) + ' USDC on Base\nFrom wallet: ' + review.from + '\nTo agent wallet: ' + review.to + '\nUSDC contract: ' + USDC;
|
|
339
|
+
customerNotice('Review this deposit, then confirm its transaction in your wallet. Depositing does not change the lifetime spending limit.'); renderCustomer();
|
|
340
|
+
} catch (error) { customerFail(error); } finally { event.submitter.disabled = false; }
|
|
341
|
+
});
|
|
342
|
+
$('funding-edit').addEventListener('click', () => { if (customer?.busy) return; fundingReview = null; renderCustomer(); });
|
|
343
|
+
$('funding-confirm').addEventListener('click', async () => {
|
|
344
|
+
const wallet = customer, review = fundingReview, current = epoch, b = $('funding-confirm'); b.disabled = true; $('funding-edit').disabled = true;
|
|
345
|
+
try {
|
|
346
|
+
if (!wallet || !review || fundingEpoch !== current) throw new Error('funding_review_required');
|
|
347
|
+
const result = await wallet.sendFunding(review, async () => {
|
|
348
|
+
const latest = await api('/api/state');
|
|
349
|
+
if (current !== epoch || customer !== wallet || !latest.initialized || latest.wallet.asset.toLowerCase() !== USDC.toLowerCase() || latest.wallet.network !== 'eip155:8453') throw new Error('funding_recipient_changed');
|
|
350
|
+
return latest.wallet.address;
|
|
351
|
+
});
|
|
352
|
+
customerNotice('Deposit submitted: ' + result.hash + '. Check its receipt before starting another deposit.');
|
|
353
|
+
} catch (error) { customerFail(error); } finally { fundingReview = null; b.disabled = false; $('funding-edit').disabled = false; renderCustomer(); }
|
|
354
|
+
});
|
|
355
|
+
$('funding-check').addEventListener('click', async () => {
|
|
356
|
+
const b = $('funding-check'); b.disabled = true;
|
|
357
|
+
try {
|
|
358
|
+
if (fundingMemory) { fundingJournal.write(fundingMemory); fundingMemory = null; }
|
|
359
|
+
const result = await customer.checkFunding($('funding-hash').value.trim());
|
|
360
|
+
$('funding-hash').value = '';
|
|
361
|
+
customerNotice(result.status === 'confirmed' ? 'The exact Base USDC deposit has three confirmations.' : result.status === 'cancelled' ? 'A same-nonce cancellation has three confirmations. This deposit cannot settle.' : result.status === 'reverted' ? 'The transaction reverted; USDC was not transferred. Gas may have been spent.' : 'Deposit is ' + result.status + '. Keep its hash; if replaced in your wallet, check the replacement hash.');
|
|
362
|
+
if (result.status === 'confirmed') { await customer.refresh(); await refresh(); }
|
|
363
|
+
} catch (error) { customerFail(error); } finally { b.disabled = false; renderCustomer(); }
|
|
364
|
+
});
|
|
365
|
+
$('funding-new').addEventListener('click', () => {
|
|
366
|
+
try { const record = fundingJournal.read(); if (!record || !['confirmed', 'reverted', 'cancelled'].includes(record.status)) throw new Error('funding_record_exists');
|
|
367
|
+
fundingJournal.clear(); fundingMemory = null; $('funding-amount').value = ''; $('funding-hash').value = ''; renderCustomer(); customerNotice('Ready to review a new deposit.');
|
|
368
|
+
} catch (error) { customerFail(error); }
|
|
369
|
+
});
|
|
370
|
+
discovery.scan(); renderCustomer();
|
|
371
|
+
const fragment = new URLSearchParams(location.hash.slice(1));
|
|
372
|
+
if (fragment.has('pair') || fragment.has('gateway')) {
|
|
373
|
+
history.replaceState(null, '', location.pathname + location.search);
|
|
374
|
+
try { gateway = localGateway(fragment.get('gateway') || gateway); $('gateway').value = gateway; $('pair-code').value = fragment.get('pair') || ''; notice('Pairing link loaded. Connect to your local signer to continue.'); } catch (e) { fail(e); }
|
|
375
|
+
} else { $('gateway').value = initialGateway(location.href); }
|
|
376
|
+
setInterval(() => { if (session && Date.parse(session.expiresAt) <= Date.now()) { clear(); notice(messages.owner_session_required, true); } else if (session && !document.hidden) void refresh(); }, 30000);
|
|
377
|
+
}
|