-
-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathregister-agents.js
More file actions
162 lines (143 loc) · 4.75 KB
/
Copy pathregister-agents.js
File metadata and controls
162 lines (143 loc) · 4.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
// POST /api/admin/register-agents — SSE stream that back-fills the Metaplex Agent
// Registry for agents already minted as Core assets but missing an Agent Identity
// PDA. Minting an asset (api/admin/bulk-launch.js) makes the NFT; this enrols it
// in Metaplex's on-chain registry so the agent is discoverable there.
//
// The three.ws collection authority signs (it is the asset update authority), so
// agent owners never sign and need no SOL — same custody model as the mint.
//
// The on-chain work lives in api/_lib/onchain-deploy.js (registerAgentOnce),
// shared with the CLI runner scripts/register-agents-onchain.mjs.
//
// Query params:
// network mainnet | devnet (default: mainnet)
// limit max agents to process this run (default: 100, max 500)
// dry_run true | false (default: false) — skips all on-chain steps
//
// SSE events:
// init { total, network, authority, authority_balance_sol, dry_run }
// registered { agent_id, name, asset, identity_pda, signature, already_registered, explorer_url }
// skip { agent_id, name, reason }
// error { agent_id, name, error }
// paused { authority_balance_sol, registered, reason }
// done { registered, already, errors }
import { LAMPORTS_PER_SOL } from '@solana/web3.js';
import { cors, method, error, rateLimited } from '../_lib/http.js';
import { limits } from '../_lib/rate-limit.js';
import { requireAdmin } from '../_lib/admin.js';
import { requireCsrf } from '../_lib/csrf.js';
import {
authoritySecret,
buildAuthorityUmi,
funderLamports,
fetchUnregisteredAgents,
registerAgentOnce,
EST_REGISTER_LAMPORTS,
} from '../_lib/onchain-deploy.js';
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
function sse(res, event, data) {
if (!res.writableEnded) {
res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
}
}
export default async function handler(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
if (!method(req, res, ['POST'])) return;
const admin = await requireAdmin(req, res);
if (!admin) return;
if (!(await requireCsrf(req, res, admin.id))) return;
const rl = await limits.strict(admin.id);
if (!rl.success) return rateLimited(res, rl);
const q = req.query ?? {};
const network = q.network === 'devnet' ? 'devnet' : 'mainnet';
const limit = Math.min(500, Math.max(1, Number(q.limit) || 100));
const dryRun = q.dry_run === 'true';
if (!authoritySecret()) {
return error(
res,
500,
'config_error',
'Set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (or LAUNCH_FUNDER_SECRET) to the funded authority wallet secret.',
);
}
let umi, authoritySigner;
try {
({ umi, authoritySigner } = buildAuthorityUmi(network));
} catch (e) {
return error(res, 500, 'config_error', e.message);
}
// SSE headers
res.statusCode = 200;
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
res.setHeader('cache-control', 'no-cache, no-transform');
res.setHeader('connection', 'keep-alive');
res.setHeader('x-accel-buffering', 'no');
let aborted = false;
req.on('close', () => {
aborted = true;
});
const authorityPk = authoritySigner.publicKey;
const startBalance = await funderLamports(umi, authorityPk);
const agents = await fetchUnregisteredAgents(network, limit);
sse(res, 'init', {
total: agents.length,
network,
authority: authorityPk.toString(),
authority_balance_sol: startBalance / LAMPORTS_PER_SOL,
dry_run: dryRun,
});
let registered = 0;
let already = 0;
let errors = 0;
for (const agent of agents) {
if (aborted) break;
const agentName = agent.name || 'Agent';
const net = network === 'mainnet' ? agent.meta : agent.meta?.devnet || {};
if (dryRun) {
sse(res, 'registered', {
agent_id: agent.id,
name: agentName,
asset: net?.sol_mint_address || null,
identity_pda: '(dry run)',
signature: null,
already_registered: false,
explorer_url: null,
dry_run: true,
});
registered++;
continue;
}
// Authority balance gate.
const bal = await funderLamports(umi, authorityPk);
if (bal < EST_REGISTER_LAMPORTS + 5000) {
sse(res, 'paused', {
authority_balance_sol: bal / LAMPORTS_PER_SOL,
registered,
reason: 'authority wallet is low on SOL — top up and re-run',
});
break;
}
try {
const r = await registerAgentOnce({
umi,
authoritySigner,
agent,
network,
onEvent: (type, data) => sse(res, type, data),
});
if (r.alreadyRegistered) already++;
else registered++;
} catch (err) {
sse(res, 'error', {
agent_id: agent.id,
name: agentName,
error: `register: ${err.message}`,
});
errors++;
}
// ~2 registrations/sec — stay well within RPC limits.
await sleep(400);
}
sse(res, 'done', { registered, already, errors });
res.end();
}