paralith-mcp 0.5.0 → 0.5.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/dist/bridge.mjs CHANGED
@@ -1,1962 +1,1999 @@
1
- #!/usr/bin/env node
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __esm = (fn, res, err) => function __init() {
4
- if (err) throw err[0];
5
- try {
6
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
- } catch (e) {
8
- throw err = [e], e;
9
- }
10
- };
11
-
12
- // ../../backend/native/deploy-target.mjs
13
- function origin(url) {
14
- let parsed;
15
- try {
16
- parsed = new URL(String(url));
17
- } catch {
18
- return null;
19
- }
20
- const host = parsed.hostname === "localhost" ? "127.0.0.1" : parsed.hostname;
21
- const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
22
- return `${parsed.protocol}//${host}:${port}`;
23
- }
24
- function pinnedTargets(env = process.env) {
25
- const list = parseList(env[TARGET_ENV]).map(origin).filter(Boolean);
26
- return list.length ? new Set(list) : null;
27
- }
28
- function assertDeployTarget(url, env = process.env) {
29
- const pinned = pinnedTargets(env);
30
- if (!pinned) return;
31
- const o = origin(url);
32
- if (!o || !pinned.has(o)) {
33
- throw new Error(`refusing to send to ${url}: this deploy is pinned to ${[...pinned].join(", ")}`);
34
- }
35
- }
36
- var TARGET_ENV, parseList, RECEIPT_FILES;
37
- var init_deploy_target = __esm({
38
- "../../backend/native/deploy-target.mjs"() {
39
- TARGET_ENV = "PARALITH_DEPLOY_TARGET";
40
- parseList = (value) => String(value || "").split(",").map((s) => s.trim()).filter(Boolean);
41
- RECEIPT_FILES = Object.freeze([
42
- "backend/native/deployment-state.json",
43
- "backend/native/dao-state.json",
44
- "backend/native/marketplace-state.json",
45
- "backend/native/venue-state.json",
46
- "backend/native/sharded-venue-state.json",
47
- "backend/native/ranking-state.json",
48
- "backend/native/faucet-state.json",
49
- "backend/native/wasm-runtime-state.json",
50
- "live-process.txt",
51
- "rune-process.txt",
52
- "hunt-process.txt",
53
- "products/bridge/deployments/pusd-standin.json"
54
- ]);
55
- }
56
- });
57
-
58
- // ../rune-ao/src/lib/poll-wait.mjs
59
- var init_poll_wait = __esm({
60
- "../rune-ao/src/lib/poll-wait.mjs"() {
61
- "use strict";
62
- }
63
- });
64
-
65
- // ../rune-ao/src/lib/slot-settle.mjs
66
- var init_slot_settle = __esm({
67
- "../rune-ao/src/lib/slot-settle.mjs"() {
68
- "use strict";
69
- init_poll_wait();
70
- }
71
- });
72
-
73
- // ../rune-ao/src/lib/gas.mjs
74
- function isGasRefusal(res) {
75
- return res?.status === 402;
76
- }
77
- function header(headers, name) {
78
- if (!headers) return null;
79
- if (typeof headers.get === "function") return headers.get(name);
80
- return headers[name] ?? headers[name.toLowerCase()] ?? null;
81
- }
82
- function gasInt(value) {
83
- if (typeof value === "number") return Number.isSafeInteger(value) ? value : null;
84
- if (typeof value === "bigint") {
85
- return value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : null;
86
- }
87
- const text = String(value ?? "").trim().replace(/^"(.*)"$/, "$1");
88
- if (!/^-?\d+$/.test(text)) return null;
89
- const n = Number(text);
90
- return Number.isSafeInteger(n) ? n : null;
91
- }
92
- function parseGasRequired(res, { node = null, account = null, process: process2 = null, body = null } = {}) {
93
- if (!isGasRefusal(res)) return null;
94
- let price = gasInt(header(res.headers, "price"));
95
- let balance = gasInt(header(res.headers, "balance"));
96
- const text = body === null || body === void 0 ? typeof res.body === "string" || res.body instanceof Uint8Array ? res.body : "" : body;
97
- const str = typeof text === "string" ? text : new TextDecoder().decode(text);
98
- if ((price === null || balance === null) && /^\s*\{/.test(str)) {
99
- try {
100
- const json = JSON.parse(str);
101
- if (price === null) price = gasInt(json?.price);
102
- if (balance === null) balance = gasInt(json?.balance);
103
- } catch {
104
- }
105
- }
106
- const detail = HTML.test(str) ? "" : str.trim().slice(0, 120);
107
- return new GasRequiredError({ price, balance, node, account, process: process2, detail: detail === "Insufficient funds" ? "" : detail });
108
- }
109
- var GAS_MAX_TAG_BYTES, GAS_MAX_FOR, HTML, GasRequiredError;
110
- var init_gas = __esm({
111
- "../rune-ao/src/lib/gas.mjs"() {
112
- "use strict";
113
- GAS_MAX_TAG_BYTES = 3072;
114
- GAS_MAX_FOR = Math.floor((GAS_MAX_TAG_BYTES + 1) / 44);
115
- HTML = /^\s*(?:<!doctype\s+html|<html|<head|<body)/i;
116
- GasRequiredError = class extends Error {
117
- constructor({ price = null, balance = null, node = null, account = null, process: process2 = null, detail = "" } = {}) {
118
- const need = price === null ? "" : ` It costs ${price}`;
119
- const have = balance === null ? "" : `${need ? ";" : " The"} balance is ${balance}`;
120
- super(`Gas required${node ? ` on ${node}` : ""}.${need}${have}${need || have ? " (PUSD base units)." : ""} Nothing was scheduled. Deposit gas, then send it again.` + (detail ? ` (${detail})` : ""));
121
- this.name = "GasRequiredError";
122
- this.status = 402;
123
- this.scheduled = false;
124
- this.gas = true;
125
- this.price = price;
126
- this.balance = balance;
127
- this.node = node;
128
- this.account = account;
129
- this.process = process2;
130
- }
131
- };
132
- }
133
- });
134
-
135
- // ../rune-ao/src/lib/admission.mjs
136
- function header2(headers, name) {
137
- if (!headers) return null;
138
- if (typeof headers.get === "function") return headers.get(name);
139
- return headers[name] ?? null;
140
- }
141
- function isAdmissionRefusal(res) {
142
- if (res?.status === 429) return true;
143
- return res?.status === 503 && String(header2(res.headers, ADMISSION_HEADER) ?? "").trim() === "busy";
144
- }
145
- function retryAfterMs(value, now = Date.now()) {
146
- const text = String(value ?? "").trim();
147
- if (/^\d+$/.test(text)) return Number(text) * 1e3;
148
- const at = Date.parse(text);
149
- return Number.isFinite(at) ? Math.max(0, at - now) : 1e3;
150
- }
151
- function admissionDelayMs(attempt, retryAfter, random = Math.random) {
152
- const exp = Math.min(ADMISSION_BACKOFF.capMs, ADMISSION_BACKOFF.baseMs * 2 ** attempt);
153
- const wait = Math.max(retryAfter, exp);
154
- return Math.round(wait + random() * wait / 2);
155
- }
156
- async function postAdmitted(post, {
157
- budgetMs = ADMISSION_BUDGET_MS,
158
- signal,
159
- onRefused,
160
- random = Math.random,
161
- now = Date.now,
162
- sleep = pause
163
- } = {}) {
164
- const started = now();
165
- for (let attempt = 0; ; attempt += 1) {
166
- const res = await post();
167
- if (!isAdmissionRefusal(res)) return res;
168
- try {
169
- onRefused?.();
170
- } catch {
171
- }
172
- const wait = admissionDelayMs(attempt, retryAfterMs(header2(res.headers, "retry-after"), now()), random);
173
- if (now() - started + wait > budgetMs) return res;
174
- try {
175
- await res.arrayBuffer?.();
176
- } catch {
177
- }
178
- try {
179
- await sleep(wait, signal);
180
- } catch (reason) {
181
- throw new AdmissionWaitAborted(reason);
182
- }
183
- }
184
- }
185
- var ADMISSION_HEADER, ADMISSION_BACKOFF, ADMISSION_BUDGET_MS, pause, AdmissionWaitAborted;
186
- var init_admission = __esm({
187
- "../rune-ao/src/lib/admission.mjs"() {
188
- "use strict";
189
- init_gas();
190
- ADMISSION_HEADER = "hb-admission";
191
- ADMISSION_BACKOFF = Object.freeze({ baseMs: 1e3, capMs: 8e3 });
192
- ADMISSION_BUDGET_MS = 3e4;
193
- pause = (ms, signal) => new Promise((resolve, reject) => {
194
- if (signal?.aborted) {
195
- reject(signal.reason);
196
- return;
197
- }
198
- const timer = setTimeout(() => {
199
- signal?.removeEventListener?.("abort", onAbort);
200
- resolve();
201
- }, ms);
202
- const onAbort = () => {
203
- clearTimeout(timer);
204
- reject(signal.reason);
205
- };
206
- signal?.addEventListener?.("abort", onAbort, { once: true });
207
- });
208
- AdmissionWaitAborted = class extends Error {
209
- constructor(reason) {
210
- super("The write was aborted while the node was refusing it; nothing was accepted.");
211
- this.name = "AbortError";
212
- this.cause = reason;
213
- }
214
- };
215
- }
216
- });
217
-
218
- // ../rune-ao/src/lib/transport-timeouts.mjs
219
- function pushRequestInit() {
220
- const dispatcher = globalThis[PUSH_DISPATCHER];
221
- return dispatcher ? { dispatcher } : {};
222
- }
223
- var DEFAULT_TRANSPORT_TIMEOUTS, PUSH_SOCKET_CAP_MS, PUSH_DISPATCHER;
224
- var init_transport_timeouts = __esm({
225
- "../rune-ao/src/lib/transport-timeouts.mjs"() {
226
- "use strict";
227
- DEFAULT_TRANSPORT_TIMEOUTS = Object.freeze({
228
- publishedReadMs: 3e3,
229
- computeReadMs: 6e3,
230
- replyMs: 25e3,
231
- replyRecoveryMs: 3e4,
232
- deliveryMs: 9e4
233
- });
234
- PUSH_SOCKET_CAP_MS = 10 * 6e4;
235
- PUSH_DISPATCHER = /* @__PURE__ */ Symbol.for("paralith.push-dispatcher");
236
- }
237
- });
238
-
239
- // ../rune-ao/src/lib/slot-result.mjs
240
- async function nodeDeliversOutboxes(node, {
241
- fetchImpl = globalThis.fetch,
242
- timeoutMs = 3e3,
243
- maxAgeMs = OUTBOX_DELIVERY_RECHECK_MS
244
- } = {}) {
245
- const base = String(node ?? "").replace(/\/+$/, "");
246
- const known = deliveringNodes.get(base);
247
- if (known !== void 0 && Date.now() - known.at < maxAgeMs) return known.delivers;
248
- let answer = null;
249
- try {
250
- const res = await fetchImpl(`${base}/${OUTBOX_DELIVERY_PATH}`, {
251
- headers: { accept: "text/plain" },
252
- signal: AbortSignal.timeout(timeoutMs)
253
- });
254
- const text = res.status === 200 ? (await res.text()).trim() : "";
255
- answer = text === OUTBOX_DELIVERY_VALUE ? true : res.status >= 500 ? null : false;
256
- } catch {
257
- answer = null;
258
- }
259
- if (answer !== null) deliveringNodes.set(base, { delivers: answer, at: Date.now() });
260
- return answer === true;
261
- }
262
- function parsePushReceipts(text) {
263
- let body;
264
- try {
265
- body = JSON.parse(String(text ?? ""));
266
- } catch {
267
- return null;
268
- }
269
- if (body === null || typeof body !== "object" || Array.isArray(body)) return null;
270
- const outbox = body.outbox ?? body.results?.outbox;
271
- if (outbox !== void 0 && (outbox === null || typeof outbox !== "object")) return null;
272
- const keys = nonEmpty(outbox) ? Object.keys(outbox) : [];
273
- const receipts = {};
274
- const terminal = [];
275
- let delivered = true;
276
- for (const key of keys) {
277
- const receipt = body[key];
278
- receipts[key] = receipt ?? null;
279
- if (receiptTerminal(receipt)) terminal.push(key);
280
- else if (!receiptSlot(receipt)) delivered = false;
281
- }
282
- const output = body.output ?? body.results?.output;
283
- const data = output !== null && typeof output === "object" ? output.data : void 0;
284
- return {
285
- delivered,
286
- receipts,
287
- terminal,
288
- reply: typeof data === "string" && data !== "" ? data : null
289
- };
290
- }
291
- async function pushVerdict(node, status2, text, delivers, { fetchImpl = globalThis.fetch } = {}) {
292
- if (notDeliveringAnswer(status2, text) && (delivers || await nodeDeliversOutboxes(node, { fetchImpl, maxAgeMs: 0 }))) {
293
- return { delivered: false, notDelivering: true };
294
- }
295
- if (!delivers) return { delivered: null, notDelivering: false };
296
- return {
297
- delivered: status2 >= 200 && status2 < 300 && parsePushReceipts(text)?.delivered === true,
298
- notDelivering: false
299
- };
300
- }
301
- var SLOT_RESULT_HEADERS, nonEmpty, OUTBOX_DELIVERY_PATH, OUTBOX_DELIVERY_VALUE, deliveringNodes, OUTBOX_DELIVERY_RECHECK_MS, receiptSlot, receiptTerminal, notDeliveringAnswer;
302
- var init_slot_result = __esm({
303
- "../rune-ao/src/lib/slot-result.mjs"() {
304
- "use strict";
305
- SLOT_RESULT_HEADERS = Object.freeze({ accept: "application/json", "accept-bundle": "true" });
306
- nonEmpty = (value) => value !== null && typeof value === "object" && Object.keys(value).length > 0;
307
- OUTBOX_DELIVERY_PATH = "~meta@1.0/info/outbox-delivery";
308
- OUTBOX_DELIVERY_VALUE = "durable";
309
- deliveringNodes = /* @__PURE__ */ new Map();
310
- OUTBOX_DELIVERY_RECHECK_MS = 5 * 6e4;
311
- receiptSlot = (r) => r !== null && typeof r === "object" && r.status !== "terminal" && (typeof r.slot === "number" && Number.isSafeInteger(r.slot) && r.slot >= 0 || typeof r.slot === "string" && /^\d+$/.test(r.slot));
312
- receiptTerminal = (r) => r !== null && typeof r === "object" && r.status === "terminal";
313
- notDeliveringAnswer = (status2, text) => status2 !== 200 && /does not deliver/i.test(String(text ?? ""));
314
- }
315
- });
316
-
317
- // ../../backend/native/hbclient.mjs
318
- import crypto2 from "node:crypto";
319
- function sfString(s) {
320
- return '"' + String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
321
- }
322
- function sfBareItem(v) {
323
- if (v && v.__sf === "binary") return ":" + b64std(v.value) + ":";
324
- if (v && v.__sf === "token") return String(v.value);
325
- if (v && v.__sf === "string") return sfString(v.value);
326
- if (typeof v === "number") return String(v);
327
- return sfString(v);
328
- }
329
- function sfParams(params) {
330
- return params.map(([k, v]) => ";" + k + "=" + sfBareItem(v)).join("");
331
- }
332
- function sfInnerList(items, params) {
333
- return "(" + items.map((i) => sfBareItem(i)).join(" ") + ")" + sfParams(params || []);
334
- }
335
- function sfDict(entries) {
336
- return entries.map(([k, v]) => k + "=" + v).join(", ");
337
- }
338
- function binCmp(a, b) {
339
- return Buffer.compare(Buffer.from(a, "binary"), Buffer.from(b, "binary"));
340
- }
341
- function encodeHeaderValue(v) {
342
- const s = Buffer.isBuffer(v) ? v.toString("latin1") : String(v);
343
- return s.replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n");
344
- }
345
- function escapeKey(k) {
346
- if (URI_SAFE.test(k)) return k;
347
- let out = "";
348
- for (const byte of Buffer.from(k, "utf8")) {
349
- const c = String.fromCharCode(byte);
350
- if (/[a-z0-9.\-_/?&]/.test(c)) out += c;
351
- else out += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
352
- }
353
- return out;
354
- }
355
- function isPlainObject(v) {
356
- return v !== null && typeof v === "object" && !Buffer.isBuffer(v) && !Array.isArray(v);
357
- }
358
- function toTabm(value) {
359
- if (Buffer.isBuffer(value)) return value;
360
- if (typeof value === "string") return Buffer.from(value, "utf8");
361
- if (Array.isArray(value)) {
362
- const numbered = {};
363
- value.forEach((v, i) => {
364
- numbered[String(i + 1)] = v;
365
- });
366
- const m = toTabm(numbered);
367
- const types = parseAoTypes(m["ao-types"]);
368
- types["."] = "list";
369
- m["ao-types"] = Buffer.from(encodeAoTypes(types), "utf8");
370
- return m;
371
- }
372
- if (isPlainObject(value)) {
373
- const types = {};
374
- const out = {};
375
- for (const key of sortedKeys(value)) {
376
- if (key === "commitments" || key === "priv" || key.startsWith("priv/")) continue;
377
- const v = value[key];
378
- if (v === void 0) continue;
379
- if (typeof v === "string" || Buffer.isBuffer(v)) {
380
- out[key] = toTabm(v);
381
- } else if (Array.isArray(v) || isPlainObject(v)) {
382
- out[key] = toTabm(v);
383
- } else if (typeof v === "number") {
384
- if (Number.isInteger(v)) {
385
- types[key] = "integer";
386
- out[key] = Buffer.from(String(v));
387
- } else {
388
- types[key] = "float";
389
- out[key] = Buffer.from(String(v));
390
- }
391
- } else if (typeof v === "boolean" || v === null) {
392
- types[key] = "atom";
393
- out[key] = Buffer.from(v === null ? "null" : String(v));
394
- }
395
- }
396
- if (Object.keys(types).length) out["ao-types"] = Buffer.from(encodeAoTypes(types), "utf8");
397
- return out;
398
- }
399
- return Buffer.from(String(value), "utf8");
400
- }
401
- function encodeAoTypes(types) {
402
- const groups = /* @__PURE__ */ new Map();
403
- for (const key of Object.keys(types).sort(byBytes)) {
404
- const type = types[key];
405
- if (!groups.has(type)) groups.set(type, []);
406
- groups.get(type).push(key);
407
- }
408
- return [...groups.keys()].sort(byBytes).map(
409
- (type) => type + "=(" + groups.get(type).map(
410
- (key) => /^[ -~]*$/.test(key) ? sfString(key) : ":" + b64std(Buffer.from(key)) + ":"
411
- ).join(" ") + ")"
412
- ).join(", ");
413
- }
414
- function parseAoTypes(bin) {
415
- if (!bin) return {};
416
- const s = Buffer.isBuffer(bin) ? bin.toString("utf8") : String(bin);
417
- const out = {};
418
- for (const m of s.matchAll(/([a-z0-9*_.-]+)=\(([^)]*)\)/g)) {
419
- for (const k of m[2].matchAll(/"((?:[^"\\]|\\.)*)"|:([A-Za-z0-9+/=]*):/g)) {
420
- const key = k[1] !== void 0 ? k[1].replace(/\\(.)/g, "$1") : Buffer.from(k[2], "base64").toString("utf8");
421
- out[key] = m[1];
422
- }
423
- }
424
- for (const part of s.split(",")) {
425
- const m = part.trim().match(/^([^=(]+)="([^"]*)"$/);
426
- if (m) out[m[1]] = m[2];
427
- }
428
- return out;
429
- }
430
- function inlineKey(msg) {
431
- const explicit = msg["ao-body-key"];
432
- if (explicit !== void 0) {
433
- return { extra: {}, key: Buffer.isBuffer(explicit) ? explicit.toString() : String(explicit) };
434
- }
435
- if (Object.prototype.hasOwnProperty.call(msg, "body")) return { extra: {}, key: "body" };
436
- if (Object.prototype.hasOwnProperty.call(msg, "data")) {
437
- return { extra: { "ao-body-key": Buffer.from("data") }, key: "data" };
438
- }
439
- return { extra: {}, key: "body" };
440
- }
441
- function groupMaps(map, parent, top) {
442
- const flattened = {};
443
- for (const key of sortedKeys(map)) {
444
- const value = map[key];
445
- const normKey = key;
446
- const flatK = parent === "" ? normKey : parent + "/" + normKey;
447
- if (isPlainObject(value)) {
448
- if (Object.keys(value).length === 0) {
449
- top[flatK] = { "ao-types": Buffer.from("empty-message") };
450
- } else {
451
- top = groupMaps(value, flatK, top);
452
- }
453
- } else {
454
- const buf = Buffer.isBuffer(value) ? value : Buffer.from(String(value));
455
- if (normKey === "content-disposition" || buf.length > MAX_HEADER_LENGTH) {
456
- top[flatK] = buf;
457
- } else {
458
- flattened[normKey] = buf;
459
- }
460
- }
461
- }
462
- if (Object.keys(flattened).length === 0) return top;
463
- if (parent === "") return Object.assign({}, top, flattened);
464
- top[parent] = flattened;
465
- return top;
466
- }
467
- function encodeFlatMsg(msg) {
468
- const headerKeys = sortedKeys(msg).filter((k) => k !== "body" && k !== "priv");
469
- const headers = headerKeys.map((k) => Buffer.concat([Buffer.from(k + ": "), asBuf(msg[k])])).reduce((acc, b, i) => i === 0 ? [b] : acc.concat([Buffer.from(CRLF), b]), []);
470
- const head = Buffer.concat(headers);
471
- const body = msg.body === void 0 ? Buffer.alloc(0) : asBuf(msg.body);
472
- if (body.length === 0) return head;
473
- return Buffer.concat([head, Buffer.from(CRLF + CRLF), body]);
474
- }
475
- function encodeBodyPart(partName, part, inlKey) {
476
- const disposition = partName === inlKey ? "inline" : `form-data;name="${partName}"`;
477
- if (isPlainObject(part)) {
478
- return encodeFlatMsg(Object.assign({}, part, {
479
- "content-disposition": Buffer.from(disposition)
480
- }));
481
- }
482
- return Buffer.concat([
483
- Buffer.from("content-disposition: " + disposition + CRLF + CRLF),
484
- asBuf(part)
485
- ]);
486
- }
487
- function tabmToHttp(tabm) {
488
- const stripped = {};
489
- for (const k of Object.keys(tabm)) {
490
- if (["commitments", "signature", "signature-input", "priv"].includes(k)) continue;
491
- stripped[IS_ID(k) ? escapeKey(k) : k] = tabm[k];
492
- }
493
- const { extra, key: inlKey } = inlineKey(stripped);
494
- const headers = {};
495
- const bodyMap = {};
496
- for (const [k, v] of Object.entries(extra)) headers[k] = v;
497
- for (const key of sortedKeys(stripped)) {
498
- const value = stripped[key];
499
- if (key === "body") {
500
- bodyMap["body"] = value;
501
- continue;
502
- }
503
- if (key === inlKey) {
504
- bodyMap[inlKey] = value;
505
- continue;
506
- }
507
- if (isPlainObject(value)) {
508
- bodyMap[key] = value;
509
- continue;
510
- }
511
- const buf = asBuf(value);
512
- if (buf.length <= MAX_HEADER_LENGTH) headers[key] = buf;
513
- else bodyMap[key] = buf;
514
- }
515
- const grouped = groupMaps(bodyMap, "", {});
516
- const gKeys = sortedKeys(grouped);
517
- let body = null;
518
- if (gKeys.length === 0) {
519
- body = null;
520
- } else if (gKeys.length === 1 && gKeys[0] === inlKey && Buffer.isBuffer(grouped[inlKey])) {
521
- body = grouped[inlKey];
522
- } else {
523
- const parts = gKeys.map((k) => {
524
- const v = grouped[k];
525
- if (isPlainObject(v) && Object.keys(v).length === 1 && Object.prototype.hasOwnProperty.call(v, "body")) {
526
- return encodeBodyPart(k + "/body", v, "body");
527
- }
528
- return encodeBodyPart(k, v, inlKey);
529
- });
530
- const joined = parts.reduce(
531
- (acc, p, i) => i === 0 ? [p] : acc.concat([Buffer.from(CRLF), p]),
532
- []
533
- );
534
- const boundary = b64url(sha256(Buffer.concat(joined)));
535
- const withMarkers = parts.reduce(
536
- (acc, p, i) => acc.concat(
537
- i === 0 ? [] : [Buffer.from(CRLF)],
538
- [Buffer.from("--" + boundary + CRLF), p]
539
- ),
540
- []
541
- );
542
- body = Buffer.concat([
543
- Buffer.concat(withMarkers),
544
- Buffer.from(CRLF + "--" + boundary + "--")
545
- ]);
546
- headers["content-type"] = Buffer.from(`multipart/form-data; boundary="${boundary}"`);
547
- }
548
- const outHeaders = {};
549
- for (const k of Object.keys(headers)) outHeaders[k] = encodeHeaderValue(headers[k]);
550
- if (body && body.length) {
551
- outHeaders["content-digest"] = "sha-256=:" + b64std(sha256(body)) + ":";
552
- }
553
- return { headers: outHeaders, body };
554
- }
555
- function addDerivedSpecifiers(keys) {
556
- return keys.map((k) => {
557
- const bare = k.startsWith("@") ? k.slice(1) : k;
558
- return DERIVED_COMPONENTS.has(bare) ? "@" + bare : bare;
559
- });
560
- }
561
- function signatureBase(encHeaders, committed, params) {
562
- const lines = committed.map((name) => {
563
- const v = encHeaders[name];
564
- if (v === void 0) {
565
- throw new Error("missing_key_for_signature_component_line: " + name);
566
- }
567
- return `"${name}": ${v}`;
568
- });
569
- const paramsLine = sfInnerList(
570
- addDerivedSpecifiers(committed).map((k) => sfStr(k)),
571
- params
572
- );
573
- return Buffer.from(lines.join("\n") + '\n"@signature-params": ' + paramsLine, "utf8");
574
- }
575
- function commitmentParams({ alg, bundle, created, expires, keyid, nonce, tag, publicKey }) {
576
- const out = [];
577
- if (alg !== void 0) out.push(["alg", sfStr(alg)]);
578
- if (bundle !== void 0) out.push(["bundle", sfStr(bundle)]);
579
- if (created !== void 0) out.push(["created", created]);
580
- if (expires !== void 0) out.push(["expires", expires]);
581
- if (keyid !== void 0) out.push(["keyid", sfStr(keyid)]);
582
- if (nonce !== void 0) out.push(["nonce", sfStr(nonce)]);
583
- if (publicKey !== void 0) out.push(["public-key", sfStr(publicKey)]);
584
- if (tag !== void 0) out.push(["tag", sfStr(tag)]);
585
- return out;
586
- }
587
- function committerUri(address) {
588
- const lower = address.toLowerCase().replace(/_/g, "-");
589
- let mask = 0n;
590
- for (const c of address) mask = mask << 1n | (c >= "A" && c <= "Z" || c === "_" ? 1n : 0n);
591
- return "uri-did-ar-" + lower + (mask << 3n).toString(36).padStart(9, "0");
592
- }
593
- function keyParams(jwk) {
594
- return { keyid: committerUri(jwkToAddress(jwk)), publicKey: b64url(pubKeyBuf(jwk)) };
595
- }
596
- function jwkToPrivateKey(jwk) {
597
- return crypto2.createPrivateKey({ key: { ...jwk, kty: "RSA" }, format: "jwk" });
598
- }
599
- function pubKeyBuf(jwk) {
600
- return b64urlDec(jwk.n);
601
- }
602
- function ownerToAddress(nB64url) {
603
- return b64url(sha256(b64urlDec(nB64url)));
604
- }
605
- function jwkToAddress(jwk) {
606
- return ownerToAddress(jwk.kty === "OKP" ? jwk.x : jwk.n);
607
- }
608
- function rsaPssSign(jwk, data) {
609
- return crypto2.sign("sha512", data, {
610
- key: jwkToPrivateKey(jwk),
611
- padding: crypto2.constants.RSA_PKCS1_PSS_PADDING,
612
- saltLength: 64
613
- // SHA-512 digest length; ar_wallet/rsa_pss uses saltLen == hashLen
614
- });
615
- }
616
- function wireToMessageKeys(wire, bodyKeys, headers) {
617
- let out = [];
618
- for (const k of wire) {
619
- if (k === "content-digest") out.push(...bodyKeys);
620
- else out.push(k);
621
- }
622
- if (headers["ao-body-key"] !== void 0) {
623
- const abk = String(headers["ao-body-key"]);
624
- out = out.flatMap((k) => k === "body" ? [abk] : [k]).filter((k) => k !== "ao-body-key");
625
- }
626
- if (/^multipart\//.test(String(headers["content-type"] || ""))) {
627
- out = out.filter((k) => k !== "content-type");
628
- }
629
- return out;
630
- }
631
- function isListTabm(sub) {
632
- const t = parseAoTypes(sub["ao-types"]);
633
- return t["."] === "list";
634
- }
635
- function hmacCommit(subTabm) {
636
- const bare = { ...subTabm };
637
- delete bare.commitments;
638
- const { headers } = tabmToHttp(bare);
639
- const wire = sortedKeys(headers).filter((k) => k !== "signature" && k !== "signature-input");
640
- const params = commitmentParams({ alg: "hmac-sha256", keyid: "constant:ao" });
641
- const base = signatureBase(headers, wire, params);
642
- const mac = crypto2.createHmac("sha256", "constant:ao").update(base).digest();
643
- const id = b64url(mac);
644
- const rawInputs = sortedKeys(bare);
645
- const bodyKeys = rawInputs.filter((k) => headers[k] === void 0 && headers[k + "+link"] === void 0);
646
- const committed = wireToMessageKeys(wire, bodyKeys, headers);
647
- return {
648
- ...subTabm,
649
- commitments: {
650
- [id]: {
651
- "commitment-device": Buffer.from("httpsig@1.0"),
652
- committed: toTabm(committed),
653
- keyid: Buffer.from("constant:ao"),
654
- signature: Buffer.from(id),
655
- type: Buffer.from("hmac-sha256")
656
- }
657
- }
658
- };
659
- }
660
- function withNestedHmacs(tabm) {
661
- if (!isPlainObject(tabm)) return tabm;
662
- const out = {};
663
- for (const [k, v] of Object.entries(tabm)) {
664
- if (k === "commitments") {
665
- out[k] = v;
666
- continue;
667
- }
668
- if (isPlainObject(v)) {
669
- const inner = withNestedHmacs(v);
670
- out[k] = isListTabm(v) || v.commitments ? inner : hmacCommit(inner);
671
- } else out[k] = v;
672
- }
673
- return out;
674
- }
675
- function commit(msg, jwk, opts = {}) {
676
- const { bundle = "true", nestedHmacs = false, ...params0 } = opts;
677
- const tEncode = process.hrtime.bigint();
678
- const tabm = nestedHmacs ? withNestedHmacs(toTabm(msg)) : toTabm(msg);
679
- const { headers, body } = tabmToHttp(tabm);
680
- const committed = sortedKeys(headers).filter(
681
- (k) => k !== "signature" && k !== "signature-input"
682
- );
683
- const params = commitmentParams({ alg: "rsa-pss-sha512", bundle, ...keyParams(jwk), ...params0 });
684
- const base = signatureBase(headers, committed, params);
685
- const tSign = process.hrtime.bigint();
686
- const sig = rsaPssSign(jwk, base);
687
- const tSeal = process.hrtime.bigint();
688
- const name = "comm-" + b64url(sha256(sig)).toLowerCase();
689
- const outHeaders = { ...headers };
690
- outHeaders["signature"] = sfDict([[name, ":" + b64std(sig) + ":"]]);
691
- outHeaders["signature-input"] = sfDict([[name, sfInnerList(
692
- addDerivedSpecifiers(committed).map((k) => sfStr(k)),
693
- params
694
- )]]);
695
- return {
696
- headers: outHeaders,
697
- body,
698
- signatureBase: base,
699
- committed,
700
- sigName: name,
701
- timing: {
702
- // The message's signed ID, as the node names it: the SHA-256 of the
703
- // signature. The node's message trace (`/~hyperbuddy@1.0/trace`) carries it.
704
- mid: b64url(sha256(sig)),
705
- encodeMs: durMs(tEncode, tSign),
706
- signMs: durMs(tSign, tSeal),
707
- sealMs: durMs(tSeal, process.hrtime.bigint())
708
- }
709
- };
710
- }
711
- async function send(node, path3, method, headers, body, signal, init = {}) {
712
- const url = transportNode(node) + (path3.startsWith("/") ? path3 : "/" + path3);
713
- httpRequests += 1;
714
- assertDeployTarget(url);
715
- const res = await fetchWithinTarget(url, {
716
- ...init,
717
- method,
718
- headers: { ...headers, "accept-bundle": "true" },
719
- body: body && body.length ? body : void 0,
720
- ...signal ? { signal } : {}
721
- });
722
- const buf = Buffer.from(await res.arrayBuffer());
723
- const h = {};
724
- res.headers.forEach((v, k) => {
725
- h[k] = v;
726
- });
727
- return { status: res.status, headers: h, body: buf, url };
728
- }
729
- async function fetchWithinTarget(url, init, hops = 0) {
730
- if (!pinnedTargets()) return fetch(url, { ...init, redirect: "follow" });
731
- const res = await fetch(url, { ...init, redirect: "manual" });
732
- const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
733
- if (!location) return res;
734
- if (hops >= 5) throw new Error(`too many redirects from ${url}`);
735
- const next = new URL(location, url).toString();
736
- assertDeployTarget(next);
737
- const keepsBody = res.status === 307 || res.status === 308;
738
- return fetchWithinTarget(next, keepsBody ? init : { ...init, method: "GET", body: void 0 }, hops + 1);
739
- }
740
- function transportNode(node) {
741
- return (process.env.NODE_TRANSPORT_URL || node).replace(/\/$/, "");
742
- }
743
- function hbError(res) {
744
- const t = res.body.toString();
745
- const m = t.match(/Error details:([\s\S]*?)<\/pre>/);
746
- const dec = (x) => x.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&#39;/g, "'");
747
- if (m) return dec(m[1]).replace(/\s+/g, " ").trim();
748
- return res.headers["details"] || t.slice(0, 400);
749
- }
750
- async function postSigned(node, path3, msg, jwk, opts = {}) {
751
- const { headers, body, signatureBase: base, committed, timing } = commit(msg, jwk, opts);
752
- const tPost = process.hrtime.bigint();
753
- let refusals = 0;
754
- const res = await postAdmitted(
755
- () => send(node, path3, "POST", headers, body),
756
- { onRefused: () => {
757
- refusals += 1;
758
- } }
759
- );
760
- const postMs = durMs(tPost, process.hrtime.bigint());
761
- res.request = { headers, body, base, committed };
762
- res.timing = { ...timing, postMs, bytes: body ? body.length : 0, ...refusals ? { refusals } : {} };
763
- if (isGasRefusal(res)) {
764
- const error = parseGasRequired(res, { node, account: jwkToAddress(jwk), process: msg?.target ?? null });
765
- error.timing = res.timing;
766
- throw error;
767
- }
768
- return res;
769
- }
770
- function observeSend(timing, observer = sendObserver) {
771
- if (!observer) return;
772
- try {
773
- observer(timing);
774
- } catch {
775
- }
776
- }
777
- async function sendMessage({
778
- node,
779
- jwk,
780
- process: pid,
781
- action: action2,
782
- tags = {},
783
- data,
784
- body,
785
- path: path3,
786
- push = true
787
- }) {
788
- const t0 = Date.now();
789
- const started = process.hrtime.bigint();
790
- const fields = /* @__PURE__ */ new Map();
791
- const put = (k, v) => {
792
- if (v === void 0 || v === null) return;
793
- fields.set(String(k).toLowerCase(), typeof v === "string" ? v : String(v));
794
- };
795
- put("target", pid);
796
- put("type", "Message");
797
- put("subject", "self");
798
- if (action2) put("action", action2);
799
- for (const [k, v] of Object.entries(tags)) put(k, v);
800
- if (data !== void 0) put("data", data);
801
- put("random-seed", String(Math.floor(Math.random() * 1e9)));
802
- const msg = {
803
- ...Object.fromEntries(fields),
804
- ...body === void 0 ? {} : { body }
805
- };
806
- const sentAction = fields.get("action")?.toLowerCase() ?? null;
807
- const timing = (outcome, { res = null, slot = null, error: error2 } = {}) => {
808
- const t = res?.timing;
809
- return {
810
- action: sentAction,
811
- slot: slot === null || slot === void 0 ? null : Number(slot),
812
- node,
813
- pid,
814
- pidRole: sentAction?.startsWith("admin.") ? "admin" : sendRoles[pid] ?? null,
815
- t0,
816
- t1: Date.now(),
817
- buildMs: t ? t.encodeMs : 0,
818
- ...t?.mid ? { mid: t.mid } : {},
819
- signMs: t ? t.signMs + t.sealMs : 0,
820
- postMs: t ? t.postMs : 0,
821
- sendMs: durMs(started, process.hrtime.bigint()),
822
- bytes: t ? t.bytes : 0,
823
- ...t?.refusals ? { refusals: t.refusals } : {},
824
- // As in `TransportTiming`: a reply was read, which a refusal also is.
825
- ok: outcome === "ok" || outcome === "rejected",
826
- outcome,
827
- ...error2 === void 0 ? {} : { error: error2 }
828
- };
829
- };
830
- const report = (outcome, detail) => {
831
- if (sendObserver) observeSend(timing(outcome, detail));
832
- };
833
- const candidates = path3 ? [path3] : [`/${pid}~process@1.0/schedule`, `/${pid}~scheduler@1.0/schedule`, `/${pid}/schedule`];
834
- const known = SCHEDULE_ROUTE.get(node)?.replaceAll(PID_SLOT, pid);
835
- const ordered = known && !path3 ? [known, ...candidates.filter((p) => p !== known)] : candidates;
836
- const tried = [];
837
- let lastResponse = null;
838
- for (const candidate of ordered) {
839
- let res;
840
- try {
841
- res = await postSigned(node, candidate, msg, jwk);
842
- } catch (error2) {
843
- report(error2?.name === "GasRequiredError" ? "gas-required" : "post-failed", { error: error2 instanceof Error ? `${error2.name}: ${error2.message}` : String(error2) });
844
- throw error2;
845
- }
846
- lastResponse = res;
847
- if (res.status === 200) {
848
- if (!path3) SCHEDULE_ROUTE.set(node, candidate.replaceAll(pid, PID_SLOT));
849
- const slot = res.headers["slot"];
850
- if (push && slot !== void 0 && slot !== null) {
851
- queuePush({ node, process: pid, slot });
852
- }
853
- if (sendObserver && slot !== void 0 && slot !== null && Number.isSafeInteger(Number(slot))) {
854
- unsettledSends.push({
855
- node: transportNode(node),
856
- pid,
857
- slot: Number(slot),
858
- timing: timing("accepted-unread", { res, slot }),
859
- observer: sendObserver
860
- });
861
- } else {
862
- report("accepted-unread", { res, slot });
863
- }
864
- return { slot, headers: res.headers };
865
- }
866
- tried.push(`${candidate} -> ${res.status} ${hbError(res)}`);
867
- if (res.status !== 404) break;
868
- }
869
- const error = new Error(`send failed on ${node}:
870
- ${tried.join("\n ")}`);
871
- error.status = lastResponse?.status ?? null;
872
- error.refused = isAdmissionRefusal(lastResponse);
873
- report(
874
- error.status === 429 ? "rate-limited" : error.refused ? "refused" : error.status === 408 ? "timeout" : "post-failed",
875
- { res: lastResponse, error: error.message }
876
- );
877
- throw error;
878
- }
879
- async function pushSlot({ node, process: pid, slot }) {
880
- let verdict;
881
- try {
882
- const base = transportNode(node);
883
- const delivers = await nodeDeliversOutboxes(base);
884
- const res = await send(
885
- node,
886
- `/${pid}~process@1.0/push&slot=${slot}&max-depth=0`,
887
- "GET",
888
- delivers ? { accept: SLOT_RESULT_HEADERS.accept } : {},
889
- void 0,
890
- AbortSignal.timeout(PUSH_SOCKET_CAP_MS),
891
- pushRequestInit()
892
- );
893
- verdict = { ...await pushVerdict(base, res.status, res.body.toString(), delivers), status: res.status };
894
- } catch {
895
- return false;
896
- }
897
- if (verdict.notDelivering) throw new NotDeliveringNodeError({ node, process: pid, slot, status: verdict.status });
898
- return verdict.delivered ?? verdict.status === 200;
899
- }
900
- function queuePush({ node, process: pid, slot }) {
901
- const key = `${node}|${pid}`;
902
- const running = PUSHES.get(key) ?? /* @__PURE__ */ new Set();
903
- PUSHES.set(key, running);
904
- const push = pushSlot({ node, process: pid, slot }).catch((error) => {
905
- if (error?.name === "NotDeliveringNodeError" && !NOT_DELIVERING_REPORTED.has(key)) {
906
- NOT_DELIVERING_REPORTED.add(key);
907
- console.error(`[hbclient] ${error.message}`);
908
- }
909
- return false;
910
- }).finally(() => {
911
- running.delete(push);
912
- if (running.size === 0 && PUSHES.get(key) === running) PUSHES.delete(key);
913
- });
914
- running.add(push);
915
- return push;
916
- }
917
- async function pendingPushes({ node, process: pid } = {}) {
918
- const sets = node && pid ? [PUSHES.get(`${node}|${pid}`)] : [...PUSHES.values()];
919
- await Promise.all(sets.filter(Boolean).flatMap((running) => [...running]));
920
- }
921
- var CRLF, MAX_HEADER_LENGTH, DERIVED_COMPONENTS, b64url, b64urlDec, b64std, sha256, sfStr, sortedKeys, URI_SAFE, IS_ID, byBytes, asBuf, durMs, httpRequests, SCHEDULE_ROUTE, PID_SLOT, sendObserver, sendRoles, unsettledSends, NotDeliveringNodeError, PUSHES, NOT_DELIVERING_REPORTED;
922
- var init_hbclient = __esm({
923
- "../../backend/native/hbclient.mjs"() {
924
- init_deploy_target();
925
- init_slot_settle();
926
- init_admission();
927
- init_gas();
928
- init_transport_timeouts();
929
- init_slot_result();
930
- CRLF = "\r\n";
931
- MAX_HEADER_LENGTH = 4096;
932
- DERIVED_COMPONENTS = /* @__PURE__ */ new Set([
933
- "method",
934
- "target-uri",
935
- "authority",
936
- "scheme",
937
- "request-target",
938
- "path",
939
- "query",
940
- "query-param"
941
- ]);
942
- b64url = (buf) => Buffer.from(buf).toString("base64url");
943
- b64urlDec = (s) => Buffer.from(s, "base64url");
944
- b64std = (buf) => Buffer.from(buf).toString("base64");
945
- sha256 = (b) => crypto2.createHash("sha256").update(b).digest();
946
- sfStr = (s) => ({ __sf: "string", value: s });
947
- sortedKeys = (obj) => Object.keys(obj).sort(binCmp);
948
- URI_SAFE = /^[a-z0-9.\-_/?&]*$/;
949
- IS_ID = (k) => /^[a-zA-Z0-9_-]{43}$/.test(k);
950
- byBytes = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
951
- asBuf = (v) => Buffer.isBuffer(v) ? v : Buffer.from(String(v));
952
- durMs = (from, to) => Number(to - from) / 1e6;
953
- httpRequests = 0;
954
- SCHEDULE_ROUTE = /* @__PURE__ */ new Map();
955
- PID_SLOT = "{pid}";
956
- sendObserver = null;
957
- sendRoles = {};
958
- unsettledSends = [];
959
- NotDeliveringNodeError = class extends Error {
960
- constructor({ node, process: pid, slot, status: status2 }) {
961
- super(`${transportNode(node)} does not deliver the outbox of ${pid} (push&slot=${slot} answered ${status2}); the node that schedules it delivers it. Push there, or read its published state.`);
962
- this.name = "NotDeliveringNodeError";
963
- Object.assign(this, { node, process: pid, slot, status: status2 });
964
- }
965
- };
966
- PUSHES = /* @__PURE__ */ new Map();
967
- NOT_DELIVERING_REPORTED = /* @__PURE__ */ new Set();
968
- process.on("beforeExit", () => {
969
- void pendingPushes();
970
- });
971
- }
972
- });
973
-
974
- // ../paralith-bridge/src/cli.mjs
975
- init_hbclient();
976
- import crypto3 from "node:crypto";
977
- import fs2 from "node:fs";
978
- import os from "node:os";
979
- import path2 from "node:path";
980
- import { createPublicClient, createWalletClient, encodeAbiParameters as encodeAbiParameters2, http, keccak256 as keccak2562, parseAbi, recoverMessageAddress, toBytes as toBytes2 } from "viem";
981
- import { privateKeyToAccount } from "viem/accounts";
982
- import { base as baseChain } from "viem/chains";
983
- import {
984
- Connection,
985
- Ed25519Program,
986
- Keypair,
987
- PublicKey,
988
- SYSVAR_INSTRUCTIONS_PUBKEY,
989
- SystemProgram,
990
- Transaction,
991
- TransactionInstruction,
992
- sendAndConfirmTransaction
993
- } from "@solana/web3.js";
994
- import { SuiGrpcClient } from "@mysten/sui/grpc";
995
- import { Transaction as SuiTransaction } from "@mysten/sui/transactions";
996
- import { bcs } from "@mysten/sui/bcs";
997
- import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
998
-
999
- // ../hypertoken/src/quantity.mjs
1000
- var MAX_QUANTITY = 2n ** 53n - 1n;
1001
- var ID = /^[A-Za-z0-9_-]{43}$/;
1002
- var isId = (value) => typeof value === "string" && ID.test(value);
1003
-
1004
- // ../hypertoken/src/root-carrier.mjs
1005
- import { bls12_381 as bls } from "@noble/curves/bls12-381";
1006
-
1007
- // ../hypertoken/src/read.mjs
1008
- var HTML2 = /^\s*<(!doctype|html|head|body)/i;
1009
- var cleanNode = (url) => String(url ?? "").trim().replace(/\/+$/, "").replace(/^(?!https?:\/\/)/, "https://");
1010
- function unwrap(value) {
1011
- for (let depth = 0; depth < 3; depth += 1) {
1012
- if (value && typeof value === "object" && !Array.isArray(value) && value["ao-result"] === "body") value = value.body;
1013
- else if (typeof value === "string" && /^\s*[[{]/.test(value)) {
1014
- try {
1015
- value = JSON.parse(value);
1016
- } catch {
1017
- break;
1018
- }
1019
- } else break;
1020
- }
1021
- return value;
1022
- }
1023
- async function readPublished(node, pid, key, { fetch: f = globalThis.fetch, timeoutMs = 2e4 } = {}) {
1024
- const url = `${cleanNode(node)}/${pid}~process@1.0/now/${key}`;
1025
- let res;
1026
- try {
1027
- res = await f(url, {
1028
- headers: { accept: "application/json", "cache-control": "no-cache" },
1029
- signal: typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : void 0
1030
- });
1031
- } catch (error) {
1032
- return { present: false, error: `unreachable: ${error?.message ?? error}` };
1033
- }
1034
- const text = await res.text();
1035
- if (HTML2.test(text)) return { present: false, status: res.status, text };
1036
- if (res.status === 404) return { present: false, status: 404, text };
1037
- if (!res.ok) return { present: false, status: res.status, error: `HTTP ${res.status}`, text };
1038
- if (text.trim() === "") return { present: false, status: res.status, text };
1039
- try {
1040
- return { present: true, status: res.status, text, value: unwrap(JSON.parse(text)) };
1041
- } catch {
1042
- return { present: true, status: res.status, text, value: text.trim().replace(/^"+|"+$/g, "") };
1043
- }
1044
- }
1045
-
1046
- // ../hypertoken/src/manifest.mjs
1047
- var SCHEMA = "hypertoken-manifest/v2";
1048
- var DOMAIN = `${SCHEMA}
1049
- `;
1050
-
1051
- // ../hypertoken/src/root-carrier.mjs
1052
- var utf8 = new TextEncoder();
1053
-
1054
- // ../hypertoken/src/root-certificate.mjs
1055
- var fail = (reason) => {
1056
- throw new Error(`Root certificate: ${reason}`);
1057
- };
1058
- var ROOT_ACTIONS = Object.freeze({
1059
- Transfer: "holder",
1060
- "Ledger-Enter": "holder",
1061
- "Bridge-Redeem": "holder",
1062
- "Ledger-Release": "lane",
1063
- "Ledger-Register": "lane",
1064
- "Ledger-Accepts": "lane",
1065
- "Bridge-Mint": "member",
1066
- "Ledger-Exit": "member",
1067
- "Ledger-Move-Root": "member",
1068
- "Bridge-Released": "member",
1069
- "Ledger-Credited": "member",
1070
- "Attestor-Apply": "member"
1071
- });
1072
- async function readEndorsement(response) {
1073
- const limit = 65536;
1074
- if (Number(response.headers.get("content-length")) > limit || !response.body) fail("oversized or empty endorsement");
1075
- const reader = response.body.getReader();
1076
- const chunks = [];
1077
- let length = 0;
1078
- try {
1079
- for (; ; ) {
1080
- const { done, value } = await reader.read();
1081
- if (done) break;
1082
- length += value.length;
1083
- if (length > limit) {
1084
- await reader.cancel();
1085
- fail("oversized endorsement");
1086
- }
1087
- if (value.length) chunks.push(value);
1088
- }
1089
- } finally {
1090
- reader.releaseLock();
1091
- }
1092
- const bytes = new Uint8Array(length);
1093
- let offset = 0;
1094
- for (const chunk of chunks) {
1095
- bytes.set(chunk, offset);
1096
- offset += chunk.length;
1097
- }
1098
- return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1099
- }
1100
- async function memberNodes(node, aos, nodes, fetcher) {
1101
- const known = new Map(nodes.filter((n) => isId(n.ao) && n.url).map((n) => [n.ao, cleanNode(n.url)]));
1102
- return Promise.all(aos.map(async (ao) => {
1103
- let endpoint = known.get(ao) ?? "";
1104
- if (!endpoint) {
1105
- try {
1106
- const response = await fetcher(
1107
- `${cleanNode(node)}/~location@1.0/${ao}?variant=ao.N.1`,
1108
- { headers: { accept: "application/json" }, signal: AbortSignal.timeout(1e4) }
1109
- );
1110
- if (response.ok) {
1111
- const location = await readEndorsement(response);
1112
- if (typeof location.url === "string") endpoint = cleanNode(location.url);
1113
- }
1114
- } catch {
1115
- }
1116
- }
1117
- return { ao, node: endpoint };
1118
- }));
1119
- }
1120
- async function collectChainSignatures({
1121
- root,
1122
- node,
1123
- withdrawal,
1124
- proposal: proposal2,
1125
- nodes = [],
1126
- fetch: fetcher = globalThis.fetch,
1127
- timeoutMs = 2e4
1128
- }) {
1129
- if (withdrawal === void 0 === (proposal2 === void 0)) fail("name one withdrawal or one proposal");
1130
- const id = String(withdrawal ?? proposal2);
1131
- if (!/^[1-9][0-9]*$/.test(id)) fail("invalid record id");
1132
- const read = await readPublished(node, root, "bridgeinfo", { fetch: fetcher });
1133
- const info = read.present ? read.value : null;
1134
- if (!Array.isArray(info?.attestors)) fail("root bridge state is unavailable");
1135
- let members = info.attestors;
1136
- if (proposal2 !== void 0) {
1137
- const p = (info.proposals ?? []).find((x) => String(x.id) === id);
1138
- if (!p || p.status !== "applied" || !Array.isArray(p.prior)) fail("the proposal is not applied");
1139
- members = p.prior;
1140
- }
1141
- const located = await memberNodes(node, members.map((m) => m.ao), nodes, fetcher);
1142
- const query = withdrawal !== void 0 ? `withdrawal=${id}` : `proposal=${id}`;
1143
- const answers = await Promise.all(located.map(async ({ ao, node: url }) => {
1144
- try {
1145
- const endpoint = new URL(url);
1146
- if (!["https:", "http:"].includes(endpoint.protocol) || endpoint.username || endpoint.password) return null;
1147
- endpoint.pathname = endpoint.pathname.replace(/\/+$/, "") + "/~bridge-attestor@1.0/chain-sig";
1148
- endpoint.search = query;
1149
- const response = await fetcher(endpoint.href, {
1150
- headers: { accept: "application/json" },
1151
- signal: AbortSignal.timeout(timeoutMs)
1152
- });
1153
- if (!response.ok) return null;
1154
- const answer = await readEndorsement(response);
1155
- return answer?.signer === ao ? [ao, answer] : null;
1156
- } catch {
1157
- return null;
1158
- }
1159
- }));
1160
- const ok = answers.filter(Boolean);
1161
- const isSig = (s) => typeof s === "string" && /^0x[0-9a-fA-F]{2,200}$/.test(s);
1162
- if (withdrawal !== void 0) {
1163
- return { sigs: Object.fromEntries(ok.filter(([, a]) => String(a.withdrawal) === id && isSig(a.sig)).map(([ao, a]) => [ao, a.sig])) };
1164
- }
1165
- return { votes: Object.fromEntries(ok.filter(([, a]) => String(a.proposal) === id).map(([ao, a]) => [ao, Object.fromEntries(["base", "solana", "sui"].filter((c) => isSig(a[c])).map((c) => [c, a[c]]))])) };
1166
- }
1167
-
1168
- // ../paralith-bridge/src/rpc.mjs
1169
- import fs from "node:fs";
1170
- import path from "node:path";
1171
- function solanaRpcRefusal(url) {
1172
- let host;
1173
- try {
1174
- host = new URL(url).hostname.toLowerCase();
1175
- } catch {
1176
- return "an RPC that is not a URL";
1177
- }
1178
- if (host === "api.mainnet-beta.solana.com") return "the public mainnet endpoint";
1179
- if (host.includes("helius")) return "a Helius endpoint";
1180
- return null;
1181
- }
1182
- var solanaMainnet = (deployment2) => !/devnet|testnet|localnet/.test(String(deployment2?.solana?.cluster ?? deployment2?.network ?? ""));
1183
- function rpcFor(chain, { flag, env, keysDir, deployment: deployment2 }) {
1184
- const given = flag ?? env[`PARALITH_${chain.toUpperCase()}_RPC`];
1185
- if (chain !== "solana") return given || deployment2[chain].rpc;
1186
- const file = path.join(keysDir, "solana-rpc.txt");
1187
- const url = given || (fs.existsSync(file) ? fs.readFileSync(file, "utf8").trim() : "");
1188
- if (!url) throw new Error(`no private Solana RPC: write it to ${file}, or pass --rpc / PARALITH_SOLANA_RPC`);
1189
- const why = solanaMainnet(deployment2) ? solanaRpcRefusal(url) : null;
1190
- if (why) throw new Error(`refusing ${why} as the Solana mainnet RPC (${given ? "--rpc / PARALITH_SOLANA_RPC" : file}): use the private RPC`);
1191
- return url;
1192
- }
1193
-
1194
- // ../paralith-bridge/src/admin-message.mjs
1195
- import { encodeAbiParameters, keccak256, toBytes } from "viem";
1196
- var ADMIN_TYPE = "PARALITH_ADMIN_V2";
1197
- var ALLOW_TOKEN = 1;
1198
- var UNPAUSE = 2;
1199
- var ZERO_EVM = "0x0000000000000000000000000000000000000000";
1200
- function u64(n) {
1201
- const v = BigInt(n);
1202
- if (v < 0n || v >= 1n << 64n) throw new Error(`${n} is not a u64`);
1203
- const b = Buffer.alloc(8);
1204
- b.writeBigUInt64LE(v);
1205
- return b;
1206
- }
1207
- function bytes32(value, what) {
1208
- const b = Buffer.from(value);
1209
- if (b.length !== 32) throw new Error(`${what} must be 32 bytes`);
1210
- return b;
1211
- }
1212
- function action(a) {
1213
- if (a !== ALLOW_TOKEN && a !== UNPAUSE) throw new Error(`unknown admin action ${a}`);
1214
- return a;
1215
- }
1216
- function rootBytes(id) {
1217
- return bytes32(Buffer.from(id ?? "", "base64url"), `process id ${id || "<empty>"}`);
1218
- }
1219
- function baseAdminInner({ chainId, bridge, root, epoch, nonce, action: a, token, value = true }) {
1220
- const allow = action(a) === ALLOW_TOKEN;
1221
- return keccak256(encodeAbiParameters(
1222
- [
1223
- { type: "bytes32" },
1224
- { type: "uint256" },
1225
- { type: "address" },
1226
- { type: "bytes32" },
1227
- { type: "uint64" },
1228
- { type: "uint64" },
1229
- { type: "bytes32" },
1230
- { type: "address" },
1231
- { type: "bool" }
1232
- ],
1233
- [
1234
- keccak256(toBytes(ADMIN_TYPE)),
1235
- BigInt(chainId),
1236
- bridge,
1237
- `0x${rootBytes(root).toString("hex")}`,
1238
- BigInt(epoch),
1239
- u64(nonce).readBigUInt64LE(0),
1240
- keccak256(toBytes(allow ? "ALLOW_TOKEN" : "UNPAUSE")),
1241
- allow ? token : ZERO_EVM,
1242
- value
1243
- ]
1244
- ));
1245
- }
1246
- function solanaAdminMessage({ program, root, epoch, nonce, action: a, mint, value = true }) {
1247
- const allow = action(a) === ALLOW_TOKEN;
1248
- return Buffer.concat([
1249
- Buffer.from(ADMIN_TYPE),
1250
- bytes32(program, "program id"),
1251
- rootBytes(root),
1252
- u64(epoch),
1253
- u64(nonce),
1254
- Buffer.from([a]),
1255
- allow ? bytes32(mint, "mint") : Buffer.alloc(32),
1256
- Buffer.from([value ? 1 : 0])
1257
- ]);
1258
- }
1259
- var ATTESTORS_TYPE = "PARALITH_ATTESTORS_V2";
1260
- function setOf(set) {
1261
- if (!Array.isArray(set) || set.length < 1 || set.length > 16) throw new Error("an attestor set is 1-16 keys");
1262
- return set;
1263
- }
1264
- function baseAttestorsInner({ chainId, bridge, root, epoch, newEpoch, set }) {
1265
- setOf(set);
1266
- return keccak256(encodeAbiParameters(
1267
- [
1268
- { type: "bytes32" },
1269
- { type: "uint256" },
1270
- { type: "address" },
1271
- { type: "bytes32" },
1272
- { type: "uint64" },
1273
- { type: "uint64" },
1274
- { type: "address[]" }
1275
- ],
1276
- [
1277
- keccak256(toBytes(ATTESTORS_TYPE)),
1278
- BigInt(chainId),
1279
- bridge,
1280
- `0x${rootBytes(root).toString("hex")}`,
1281
- u64(epoch).readBigUInt64LE(0),
1282
- u64(newEpoch).readBigUInt64LE(0),
1283
- set
1284
- ]
1285
- ));
1286
- }
1287
- function solanaAttestorsMessage({ program, root, epoch, newEpoch, set }) {
1288
- const keys = setOf(set).map((k) => bytes32(k, "Solana attestor key"));
1289
- return Buffer.concat([
1290
- Buffer.from(ATTESTORS_TYPE),
1291
- bytes32(program, "program id"),
1292
- rootBytes(root),
1293
- u64(epoch),
1294
- u64(newEpoch),
1295
- Buffer.from([keys.length]),
1296
- ...keys
1297
- ]);
1298
- }
1299
-
1300
- // ../paralith-bridge/src/cli.mjs
1301
- var MANIFEST = "https://bridge.paralithmarkets.com/bridge.json";
1302
- var HELP = `paralith-bridge <command>
1303
-
1304
- status the set, open changes, each chain's epoch
1305
- propose-add <node-url> propose adding a node (its keys are read from the node)
1306
- propose-remove <node-ao> propose removing one
1307
- propose-migrate <new-pusd> propose moving the set to a replacement PUSD; every node follows
1308
- propose-token <base|solana|sui> ask the current majority to admit the recorded TEST token
1309
- approve <id> approve as operator; once a majority of nodes' operators
1310
- approve, the nodes apply it at PUSD with one certificate
1311
- apply <id> collect the prior members' chain signatures from their nodes
1312
- and carry them to Base, Solana and Sui (pays each chain's gas;
1313
- --chain base|solana|sui for one)
1314
- pause stop PUSD minting, redeeming and signing releases (any operator)
1315
- unpause propose lifting the owner's pause on every chain (--chain one);
1316
- binds each chain's current admin nonce; majority approves and signs
1317
-
1318
- Keys are read from ~/.paralith/bridge/ unless a flag names another file:
1319
- operator.json the operator's Arweave keyfile (--wallet <file>)
1320
- base.key Base gas payer, 0x-hex private key (--key <file>)
1321
- solana.json Solana gas payer, keypair JSON array (--key <file>)
1322
- sui.key Sui gas payer, suiprivkey1... (--key <file>)
1323
-
1324
- --operator <addr> propose-add: the new node's operator (default: --wallet's address)
1325
- --rpc <url> apply's RPC (or PARALITH_BASE_RPC / _SOLANA_RPC / _SUI_RPC);
1326
- Solana otherwise needs a private RPC in solana-rpc.txt
1327
- --pusd <id> act on this PUSD, not the manifest's (approve on a PUSD being replaced)
1328
- --manifest <url> the deployment description (default ${MANIFEST})`;
1329
- var CHAINS = ["base", "solana", "sui"];
1330
- var argv = process.argv.slice(2);
1331
- var opt = (name) => {
1332
- const i = argv.indexOf(`--${name}`);
1333
- return i >= 0 ? argv[i + 1] : void 0;
1334
- };
1335
- var positional = argv.filter((a, i) => !a.startsWith("--") && !argv[i - 1]?.startsWith("--"));
1336
- var [cmd, target] = positional;
1337
- var die = (msg) => {
1338
- console.error(`error: ${msg}`);
1339
- process.exit(1);
1340
- };
1341
- var KEYS = path2.join(os.homedir(), ".paralith", "bridge");
1342
- var readFile = (file, what) => {
1343
- try {
1344
- return fs2.readFileSync(file, "utf8").trim();
1345
- } catch {
1346
- die(`no ${what} at ${file}`);
1347
- }
1348
- };
1349
- var threshold = (n) => Math.floor(n / 2) + 1;
1350
- async function getJson(url) {
1351
- if (!/^https?:\/\//i.test(url)) {
1352
- const file = path2.resolve(url);
1353
- try {
1354
- return JSON.parse(fs2.readFileSync(file, "utf8"));
1355
- } catch (error) {
1356
- throw new Error(`${file}: ${error.message}`);
1357
- }
1358
- }
1359
- const r = await fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(15e3) });
1360
- const text = await r.text();
1361
- if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`);
1362
- if (text.trimStart().startsWith("<")) throw new Error(`${url}: not found`);
1363
- return JSON.parse(text);
1364
- }
1365
- if (!["status", "propose-add", "propose-remove", "propose-migrate", "propose-token", "approve", "apply", "pause", "unpause"].includes(cmd)) {
1366
- console.log(HELP);
1367
- process.exit(cmd ? 1 : 0);
1368
- }
1369
- var deployment = await getJson(opt("manifest") ?? MANIFEST).catch((e) => die(`manifest: ${e.message}`));
1370
- var NODE = deployment.node;
1371
- var PUSD = opt("pusd") ?? deployment.pusd;
1372
- async function bridgeInfo(pid = PUSD) {
1373
- let v = await getJson(`${NODE}/${pid}~process@1.0/now/bridgeinfo`);
1374
- if (v && typeof v === "object" && "body" in v) v = v.body;
1375
- return typeof v === "string" ? JSON.parse(v) : v;
1376
- }
1377
- var proposal = (info, id) => (info.proposals ?? []).find((p) => String(p.id) === String(id)) ?? die(`no proposal #${id}`);
1378
- function wallet() {
1379
- const jwk = JSON.parse(readFile(
1380
- opt("wallet") ?? process.env.PARALITH_AO_WALLET ?? path2.join(KEYS, "operator.json"),
1381
- "operator wallet (your operator's Arweave keyfile)"
1382
- ));
1383
- return { jwk, address: jwkToAddress(jwk) };
1384
- }
1385
- async function pusd(tags) {
1386
- const w = wallet();
1387
- console.log(`signing as ${w.address}`);
1388
- const { slot } = await sendMessage({ node: NODE, jwk: w.jwk, process: PUSD, action: tags.Action, tags });
1389
- for (let i = 0; i < 40; i++) {
1390
- await new Promise((r) => setTimeout(r, 1500));
1391
- try {
1392
- const r = await fetch(
1393
- `${NODE}/${PUSD}~process@1.0/compute&slot=${slot}/results/output/data`,
1394
- { headers: { accept: "text/plain" }, signal: AbortSignal.timeout(3e4) }
1395
- );
1396
- const body = r.ok ? (await r.text()).trim() : "";
1397
- if (!body || body.startsWith("<")) continue;
1398
- const reply = JSON.parse(body);
1399
- if (reply.error) die(reply.error);
1400
- return reply;
1401
- } catch {
1402
- }
1403
- }
1404
- die(`sent (slot ${slot}) but no reply yet; run status before sending again`);
1405
- }
1406
- var RELEASE_ROOT = "PARALITH_ROOT_V1";
1407
- var hexBytes = (h) => toBytes2(h);
1408
- var u642 = (n) => {
1409
- const b = Buffer.alloc(8);
1410
- b.writeBigUInt64LE(BigInt(n));
1411
- return b;
1412
- };
1413
- var utf82 = (s) => Buffer.from(s, "utf8");
1414
- var processBytes = (id) => {
1415
- const bytes = Buffer.from(id ?? "", "base64url");
1416
- if (bytes.length !== 32) die(`process id ${id || "<empty>"} does not decode to 32 bytes`);
1417
- return bytes;
1418
- };
1419
- var processHex = (id) => `0x${processBytes(id).toString("hex")}`;
1420
- function voters(p) {
1421
- const v = p.prior.flatMap((member, at) => p.votes?.[member.ao] ? [{ at, member, vote: p.votes[member.ao] }] : []);
1422
- if (v.length < threshold(p.prior.length)) die(`#${p.id} has ${v.length} of ${threshold(p.prior.length)} members' chain signatures`);
1423
- return v;
1424
- }
1425
- var rpcFor2 = (chain) => rpcFor(chain, { flag: opt("rpc"), env: process.env, keysDir: KEYS, deployment });
1426
- var KEY_FILE = { base: "base.key", solana: "solana.json", sui: "sui.key" };
1427
- var keyFor = (chain) => readFile(opt("key") ?? process.env[`PARALITH_${chain.toUpperCase()}_KEY`] ?? path2.join(KEYS, KEY_FILE[chain]), `${chain} gas payer key`);
1428
- var BASE_ABI = parseAbi([
1429
- "function setAttestors(address[] set, uint64 newEpoch, bytes[] sigs)",
1430
- "function setRoot(bytes32 successor, bytes[] sigs)",
1431
- "function setTokenAllowed(address token, bool allowed, uint64 nonce, bytes[] sigs)",
1432
- "function unpause(uint64 nonce, bytes[] sigs)",
1433
- "function adminNonce() view returns (uint64)",
1434
- "function epoch() view returns (uint64)",
1435
- "function root() view returns (bytes32)"
1436
- ]);
1437
- function baseClients(withKey) {
1438
- const cfg = deployment.base;
1439
- const chain = { ...baseChain, id: cfg.chainId, rpcUrls: { default: { http: [rpcFor2("base")] } } };
1440
- const pub = createPublicClient({ chain, transport: http(rpcFor2("base")) });
1441
- if (!withKey) return { pub };
1442
- const account = privateKeyToAccount(keyFor("base"));
1443
- return { pub, account, wallet: createWalletClient({ account, chain, transport: http(rpcFor2("base")) }) };
1444
- }
1445
- var solanaProgram = () => new PublicKey(deployment.solana.programId);
1446
- var solanaConfig = () => PublicKey.findProgramAddressSync([utf82("config")], solanaProgram())[0];
1447
- var anchorIx = (name) => crypto3.createHash("sha256").update(`global:${name}`).digest().subarray(0, 8);
1448
- function ed25519Ix(entries, msg) {
1449
- const head = 2 + 14 * entries.length;
1450
- const msgOff = head + 96 * entries.length;
1451
- const data = Buffer.alloc(msgOff + msg.length);
1452
- data[0] = entries.length;
1453
- entries.forEach(({ pubkey, sig }, i) => {
1454
- const at = head + 96 * i;
1455
- const e = 2 + 14 * i;
1456
- [at + 32, 65535, at, 65535, msgOff, msg.length, 65535].forEach((v, k) => data.writeUInt16LE(v, e + 2 * k));
1457
- data.set(pubkey, at);
1458
- data.set(sig, at + 32);
1459
- });
1460
- data.set(msg, msgOff);
1461
- return new TransactionInstruction({ programId: Ed25519Program.programId, keys: [], data });
1462
- }
1463
- var suiClient = () => new SuiGrpcClient({ network: deployment.sui.network, baseUrl: rpcFor2("sui") });
1464
- var vecBytes = bcs.vector(bcs.vector(bcs.u8()));
1465
- var vecU64 = bcs.vector(bcs.u64());
1466
- var epochOf = {
1467
- async base() {
1468
- return Number(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "epoch" }));
1469
- },
1470
- async solana() {
1471
- const info = await new Connection(rpcFor2("solana"), "confirmed").getAccountInfo(solanaConfig());
1472
- if (!info) throw new Error("config not found");
1473
- const n = info.data.readUInt32LE(40);
1474
- return Number(info.data.readBigUInt64LE(44 + 32 * n));
1475
- },
1476
- async sui() {
1477
- const tx = new SuiTransaction();
1478
- tx.moveCall({ target: `${deployment.sui.package}::para_bridge::epoch`, arguments: [tx.object(deployment.sui.bridge)] });
1479
- tx.setSender("0x0");
1480
- const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
1481
- const bytes = r.commandResults?.[0]?.returnValues?.[0]?.bcs;
1482
- if (!bytes) throw new Error("epoch read returned nothing");
1483
- return Number(Buffer.from(bytes).readBigUInt64LE(0));
1484
- }
1485
- };
1486
- var adminNonceOf = {
1487
- async base() {
1488
- return Number(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "adminNonce" }));
1489
- },
1490
- async solana() {
1491
- const info = await new Connection(rpcFor2("solana"), "confirmed").getAccountInfo(solanaConfig());
1492
- if (!info) throw new Error("config not found");
1493
- const n = info.data.readUInt32LE(40);
1494
- return Number(info.data.readBigUInt64LE(93 + 32 * n));
1495
- },
1496
- async sui() {
1497
- const tx = new SuiTransaction();
1498
- tx.moveCall({ target: `${deployment.sui.package}::para_bridge::admin_nonce`, arguments: [tx.object(deployment.sui.bridge)] });
1499
- tx.setSender("0x0");
1500
- const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
1501
- const bytes = r.commandResults?.[0]?.returnValues?.[0]?.bcs;
1502
- if (!bytes) throw new Error("admin nonce read returned nothing");
1503
- return Number(Buffer.from(bytes).readBigUInt64LE(0));
1504
- }
1505
- };
1506
- async function adminNonceFor(p, chain) {
1507
- const nonce = p.admin?.nonces?.[chain];
1508
- if (!Number.isSafeInteger(nonce) || nonce < 0) die(`#${p.id} binds no admin nonce for ${chain}`);
1509
- const now = await adminNonceOf[chain]();
1510
- if (now !== nonce) die(`#${p.id} is for ${chain} admin nonce ${nonce}, but ${chain} is at ${now}; propose it again`);
1511
- return nonce;
1512
- }
1513
- var rootOf = {
1514
- async base() {
1515
- return String(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "root" })).toLowerCase();
1516
- },
1517
- async solana() {
1518
- const info = await new Connection(rpcFor2("solana"), "confirmed").getAccountInfo(solanaConfig());
1519
- if (!info) throw new Error("config not found");
1520
- const n = info.data.readUInt32LE(40);
1521
- return `0x${info.data.subarray(52 + 32 * n, 84 + 32 * n).toString("hex")}`;
1522
- },
1523
- async sui() {
1524
- const tx = new SuiTransaction();
1525
- tx.moveCall({ target: `${deployment.sui.package}::para_bridge::root`, arguments: [tx.object(deployment.sui.bridge)] });
1526
- tx.setSender("0x0");
1527
- const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
1528
- const encoded = Buffer.from(r.commandResults?.[0]?.returnValues?.[0]?.bcs ?? []);
1529
- if (encoded.length !== 33 || encoded[0] !== 32) throw new Error("root read returned invalid vector<u8>");
1530
- return `0x${encoded.subarray(1).toString("hex")}`;
1531
- }
1532
- };
1533
- async function requireRoot(chain) {
1534
- const onChain = await rootOf[chain]();
1535
- if (onChain !== processHex(PUSD)) die(`${chain} is on root ${onChain}, not ${PUSD} (${processHex(PUSD)}); pass --pusd <its root>`);
1536
- }
1537
- var applyOn = {
1538
- async base(p) {
1539
- const { pub, wallet: w, account } = baseClients(true);
1540
- console.log(`paying as ${account.address}`);
1541
- const set = p.set.map((m) => m.base);
1542
- const epoch = BigInt(p.epoch);
1543
- await requireRoot("base");
1544
- const inner = baseAttestorsInner({
1545
- chainId: deployment.base.chainId,
1546
- bridge: deployment.base.bridge,
1547
- root: PUSD,
1548
- epoch: p.priorEpoch ?? p.currentEpoch,
1549
- newEpoch: p.epoch,
1550
- set
1551
- });
1552
- const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1553
- const rows = await Promise.all(voters(p).map(async (v) => ({
1554
- sig: v.vote.base,
1555
- who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1556
- })));
1557
- const sigs = rows.filter((r2) => allowed.has(r2.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((r2) => r2.sig);
1558
- const hash = await w.writeContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "setAttestors", args: [set, epoch, sigs] });
1559
- const r = await pub.waitForTransactionReceipt({ hash });
1560
- if (r.status !== "success") die(`reverted ${hash}`);
1561
- return hash;
1562
- },
1563
- async solana(p) {
1564
- const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1565
- console.log(`paying as ${payer.publicKey.toBase58()}`);
1566
- const program = solanaProgram();
1567
- const set = p.set.map((m) => new PublicKey(m.solana));
1568
- await requireRoot("solana");
1569
- const msg = solanaAttestorsMessage({
1570
- program: program.toBuffer(),
1571
- root: PUSD,
1572
- epoch: p.priorEpoch ?? p.currentEpoch,
1573
- newEpoch: p.epoch,
1574
- set: set.map((k) => k.toBuffer())
1575
- });
1576
- const len = Buffer.alloc(4);
1577
- len.writeUInt32LE(set.length);
1578
- const tx = new Transaction().add(
1579
- ed25519Ix(voters(p).map((v) => ({ pubkey: new PublicKey(v.member.solana).toBytes(), sig: hexBytes(v.vote.solana) })), msg),
1580
- new TransactionInstruction({
1581
- programId: program,
1582
- keys: [
1583
- { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1584
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1585
- ],
1586
- data: Buffer.concat([anchorIx("set_attestors"), len, ...set.map((k) => k.toBuffer()), u642(p.epoch)])
1587
- })
1588
- );
1589
- return sendAndConfirmTransaction(new Connection(rpcFor2("solana"), "confirmed"), tx, [payer], { commitment: "confirmed" });
1590
- },
1591
- async sui(p) {
1592
- const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1593
- console.log(`paying as ${signer.getPublicKey().toSuiAddress()}`);
1594
- const v = voters(p);
1595
- const tx = new SuiTransaction();
1596
- tx.moveCall({
1597
- target: `${deployment.sui.package}::para_bridge::set_attestors`,
1598
- arguments: [
1599
- tx.object(deployment.sui.bridge),
1600
- tx.pure(vecBytes.serialize(p.set.map((m) => Array.from(hexBytes(m.sui))))),
1601
- tx.pure.u64(BigInt(p.epoch)),
1602
- tx.pure(vecU64.serialize(v.map((x) => BigInt(x.at)))),
1603
- tx.pure(vecBytes.serialize(v.map((x) => Array.from(hexBytes(x.vote.sui)))))
1604
- ]
1605
- });
1606
- const client = suiClient();
1607
- const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1608
- const t = r.Transaction ?? r.FailedTransaction;
1609
- if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1610
- await client.waitForTransaction({ digest: t.digest });
1611
- return t.digest;
1612
- }
1613
- };
1614
- var applyRootOn = {
1615
- async base(p) {
1616
- const { pub, wallet: w, account } = baseClients(true);
1617
- console.log(`paying as ${account.address}`);
1618
- const oldRoot = processHex(PUSD);
1619
- const successor = processHex(p.successor);
1620
- const inner = keccak2562(encodeAbiParameters2(
1621
- [
1622
- { type: "bytes32" },
1623
- { type: "uint256" },
1624
- { type: "address" },
1625
- { type: "uint64" },
1626
- { type: "bytes32" },
1627
- { type: "bytes32" }
1628
- ],
1629
- [
1630
- keccak2562(toBytes2(RELEASE_ROOT)),
1631
- BigInt(deployment.base.chainId),
1632
- deployment.base.bridge,
1633
- BigInt(p.currentEpoch ?? p.priorEpoch),
1634
- oldRoot,
1635
- successor
1636
- ]
1637
- ));
1638
- const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1639
- const rows = await Promise.all(voters(p).map(async (v) => ({
1640
- sig: v.vote.base,
1641
- who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1642
- })));
1643
- const sigs = rows.filter((row) => allowed.has(row.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((row) => row.sig);
1644
- const hash = await w.writeContract({
1645
- address: deployment.base.bridge,
1646
- abi: BASE_ABI,
1647
- functionName: "setRoot",
1648
- args: [successor, sigs]
1649
- });
1650
- const receipt = await pub.waitForTransactionReceipt({ hash });
1651
- if (receipt.status !== "success") die(`reverted ${hash}`);
1652
- return hash;
1653
- },
1654
- async solana(p) {
1655
- const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1656
- const program = solanaProgram();
1657
- const oldRoot = processBytes(PUSD);
1658
- const successor = processBytes(p.successor);
1659
- const msg = Buffer.concat([
1660
- utf82(RELEASE_ROOT),
1661
- program.toBuffer(),
1662
- u642(p.currentEpoch ?? p.priorEpoch),
1663
- oldRoot,
1664
- successor
1665
- ]);
1666
- const tx = new Transaction().add(
1667
- ed25519Ix(voters(p).map((v) => ({ pubkey: new PublicKey(v.member.solana).toBytes(), sig: hexBytes(v.vote.solana) })), msg),
1668
- new TransactionInstruction({
1669
- programId: program,
1670
- keys: [
1671
- { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1672
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1673
- ],
1674
- data: Buffer.concat([anchorIx("set_root"), successor])
1675
- })
1676
- );
1677
- return sendAndConfirmTransaction(new Connection(rpcFor2("solana"), "confirmed"), tx, [payer], { commitment: "confirmed" });
1678
- },
1679
- async sui(p) {
1680
- const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1681
- const v = voters(p);
1682
- const tx = new SuiTransaction();
1683
- tx.moveCall({
1684
- target: `${deployment.sui.package}::para_bridge::set_root`,
1685
- arguments: [
1686
- tx.object(deployment.sui.bridge),
1687
- tx.pure(bcs.vector(bcs.u8()).serialize(Array.from(processBytes(p.successor)))),
1688
- tx.pure(vecU64.serialize(v.map((x) => BigInt(x.at)))),
1689
- tx.pure(vecBytes.serialize(v.map((x) => Array.from(hexBytes(x.vote.sui)))))
1690
- ]
1691
- });
1692
- const client = suiClient();
1693
- const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1694
- const t = r.Transaction ?? r.FailedTransaction;
1695
- if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1696
- await client.waitForTransaction({ digest: t.digest });
1697
- return t.digest;
1698
- }
1699
- };
1700
- var adminVoters = (p, chain) => voters(p).filter((row) => row.vote?.[chain]);
1701
- var applyAdminOn = {
1702
- async base(p) {
1703
- const { pub, wallet: w, account } = baseClients(true);
1704
- console.log(`paying as ${account.address}`);
1705
- const allow = p.op === "add-token";
1706
- const token = allow ? p.admin.token : void 0;
1707
- const nonce = await adminNonceFor(p, "base");
1708
- const inner = baseAdminInner({
1709
- chainId: deployment.base.chainId,
1710
- bridge: deployment.base.bridge,
1711
- root: PUSD,
1712
- epoch: p.currentEpoch ?? p.priorEpoch,
1713
- nonce,
1714
- action: allow ? ALLOW_TOKEN : UNPAUSE,
1715
- token
1716
- });
1717
- const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1718
- const rows = await Promise.all(adminVoters(p, "base").map(async (v) => ({
1719
- sig: v.vote.base,
1720
- who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1721
- })));
1722
- const sigs = rows.filter((row) => allowed.has(row.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((row) => row.sig);
1723
- const hash = allow ? await w.writeContract({
1724
- address: deployment.base.bridge,
1725
- abi: BASE_ABI,
1726
- functionName: "setTokenAllowed",
1727
- args: [token, true, BigInt(nonce), sigs]
1728
- }) : await w.writeContract({
1729
- address: deployment.base.bridge,
1730
- abi: BASE_ABI,
1731
- functionName: "unpause",
1732
- args: [BigInt(nonce), sigs]
1733
- });
1734
- const receipt = await pub.waitForTransactionReceipt({ hash });
1735
- if (receipt.status !== "success") die(`reverted ${hash}`);
1736
- return hash;
1737
- },
1738
- async solana(p) {
1739
- const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1740
- const program = solanaProgram();
1741
- const allow = p.op === "add-token";
1742
- const mint = allow ? new PublicKey(p.admin.token) : new PublicKey(new Uint8Array(32));
1743
- const nonce = await adminNonceFor(p, "solana");
1744
- const msg = solanaAdminMessage({
1745
- program: program.toBuffer(),
1746
- root: PUSD,
1747
- epoch: p.currentEpoch ?? p.priorEpoch,
1748
- nonce,
1749
- action: allow ? ALLOW_TOKEN : UNPAUSE,
1750
- mint: mint.toBuffer()
1751
- });
1752
- const precompile = ed25519Ix(adminVoters(p, "solana").map((v) => ({
1753
- pubkey: new PublicKey(v.member.solana).toBytes(),
1754
- sig: hexBytes(v.vote.solana)
1755
- })), msg);
1756
- let instruction;
1757
- if (allow) {
1758
- const token = (deployment.solana.tokens ?? []).find((row) => row.mint === p.admin.token);
1759
- if (!token) die(`Solana token ${p.admin.token} is absent from the deployment record`);
1760
- const tokenProgram = new PublicKey(token.tokenProgram);
1761
- instruction = new TransactionInstruction({
1762
- programId: program,
1763
- keys: [
1764
- { pubkey: payer.publicKey, isSigner: true, isWritable: true },
1765
- { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1766
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },
1767
- { pubkey: mint, isSigner: false, isWritable: false },
1768
- { pubkey: PublicKey.findProgramAddressSync([utf82("vault"), mint.toBuffer()], program)[0], isSigner: false, isWritable: true },
1769
- { pubkey: tokenProgram, isSigner: false, isWritable: false },
1770
- { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
1771
- ],
1772
- data: Buffer.concat([anchorIx("allow_token"), u642(nonce)])
1773
- });
1774
- } else {
1775
- instruction = new TransactionInstruction({
1776
- programId: program,
1777
- keys: [
1778
- { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1779
- { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1780
- ],
1781
- data: Buffer.concat([anchorIx("unpause"), u642(nonce)])
1782
- });
1783
- }
1784
- return sendAndConfirmTransaction(
1785
- new Connection(rpcFor2("solana"), "confirmed"),
1786
- new Transaction().add(precompile, instruction),
1787
- [payer],
1788
- { commitment: "confirmed" }
1789
- );
1790
- },
1791
- async sui(p) {
1792
- const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1793
- const rows = adminVoters(p, "sui");
1794
- const nonce = await adminNonceFor(p, "sui");
1795
- const tx = new SuiTransaction();
1796
- if (p.op === "add-token") {
1797
- tx.moveCall({
1798
- target: `${deployment.sui.package}::para_bridge::allow_token`,
1799
- typeArguments: [p.admin.token],
1800
- arguments: [
1801
- tx.object(deployment.sui.bridge),
1802
- tx.pure.u64(nonce),
1803
- tx.pure(vecU64.serialize(rows.map((x) => BigInt(x.at)))),
1804
- tx.pure(vecBytes.serialize(rows.map((x) => Array.from(hexBytes(x.vote.sui)))))
1805
- ]
1806
- });
1807
- } else {
1808
- tx.moveCall({
1809
- target: `${deployment.sui.package}::para_bridge::unpause`,
1810
- arguments: [
1811
- tx.object(deployment.sui.bridge),
1812
- tx.pure.u64(nonce),
1813
- tx.pure(vecU64.serialize(rows.map((x) => BigInt(x.at)))),
1814
- tx.pure(vecBytes.serialize(rows.map((x) => Array.from(hexBytes(x.vote.sui)))))
1815
- ]
1816
- });
1817
- }
1818
- const client = suiClient();
1819
- const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1820
- const t = r.Transaction ?? r.FailedTransaction;
1821
- if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1822
- await client.waitForTransaction({ digest: t.digest });
1823
- return t.digest;
1824
- }
1825
- };
1826
- var short = (s = "") => s.length > 18 ? `${s.slice(0, 8)}\u2026${s.slice(-6)}` : s;
1827
- async function status() {
1828
- const info = await bridgeInfo();
1829
- const set = info.attestors ?? [];
1830
- console.log(`PUSD ${PUSD} on ${NODE}`);
1831
- if (info.predecessor) console.log(`replaces ${info.predecessor}`);
1832
- if (info.pausedBy) console.log(`PAUSED by ${info.pausedBy}`);
1833
- if (info.successor) console.log(`MOVED to ${info.successor}: the set and every node follow it there`);
1834
- console.log(`set: ${set.length} node(s), k ${threshold(set.length)}, epoch ${info.epoch ?? 0}`);
1835
- for (const m of set) console.log(` ${m.ao} operator ${m.operator ?? "-"}`);
1836
- const epochs = await Promise.all(CHAINS.map((c) => epochOf[c]().catch((e) => `? (${e.message})`)));
1837
- console.log(`chains: ${CHAINS.map((c, i) => `${c} ${epochs[i]}`).join(", ")}`);
1838
- for (const p of info.proposals ?? []) {
1839
- if (p.status === "superseded") continue;
1840
- const need = threshold(p.prior.length);
1841
- const behind = CHAINS.filter((c, i) => typeof epochs[i] === "number" && epochs[i] < p.epoch);
1842
- if (p.status === "applied" && !behind.length) continue;
1843
- console.log(`#${p.id} ${p.op} ${p.op === "migrate" ? `to ${p.successor}` : `${short(p.member?.ao)} -> epoch ${p.epoch}`}: ${p.status}, approved ${Object.keys(p.approvals ?? {}).length}/${need}` + (p.status === "applied" ? `, apply on: ${behind.join(" ")}` : ""));
1844
- }
1845
- }
1846
- async function main() {
1847
- if (cmd === "status") return status();
1848
- if (cmd === "propose-add") {
1849
- if (!target) die("propose-add <node-url>");
1850
- const url = target.replace(/\/+$/, "").replace(/^(?!https?:\/\/)/, "https://");
1851
- const k = await getJson(`${url}/~bridge-attestor@1.0/keys`);
1852
- if (!k.ao || !k.base || !k.solana || !k.sui) die(`${url} published incomplete keys`);
1853
- const operator = opt("operator") ?? wallet().address;
1854
- console.log(`node ${k.ao}
1855
- base ${k.base}
1856
- solana ${k.solana}
1857
- sui ${k.sui}
1858
- operator ${operator}`);
1859
- const r = await pusd({ Action: "Attestor-Propose", Op: "add", Ao: k.ao, Base: k.base, Solana: k.solana, Sui: k.sui, Operator: operator });
1860
- return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
1861
- }
1862
- if (cmd === "propose-remove") {
1863
- if (!target) die("propose-remove <node-ao>");
1864
- const r = await pusd({ Action: "Attestor-Propose", Op: "remove", Ao: target });
1865
- return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
1866
- }
1867
- if (cmd === "propose-migrate") {
1868
- if (!target) die("propose-migrate <new-pusd>");
1869
- const next = await bridgeInfo(target);
1870
- if (!next.predecessor) die(`${target} names no predecessor`);
1871
- PUSD = next.predecessor;
1872
- const here = await bridgeInfo();
1873
- const members = (i) => JSON.stringify((i.attestors ?? []).map((m) => [m.ao, m.base, m.solana, m.sui]));
1874
- if (members(next) !== members(here) || Number(next.epoch) !== Number(here.epoch)) {
1875
- die(`${target} does not hold ${PUSD}'s set at epoch ${here.epoch}; nodes would refuse to follow it`);
1876
- }
1877
- console.log(`moving the set of ${PUSD}
1878
- to ${target}`);
1879
- const r = await pusd({ Action: "Attestor-Propose", Op: "migrate", Successor: target });
1880
- return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"} --pusd ${PUSD}`);
1881
- }
1882
- if (cmd === "approve") {
1883
- if (!target) die("approve <id>");
1884
- await pusd({ Action: "Attestor-Approve", ProposalId: String(target) });
1885
- return console.log(`approved #${target}; your nodes vote on their next pass`);
1886
- }
1887
- if (cmd === "pause") {
1888
- await pusd({ Action: "Bridge-Pause" });
1889
- return console.log("paused");
1890
- }
1891
- if (cmd === "propose-token") {
1892
- if (!CHAINS.includes(target)) die("propose-token <base|solana|sui>");
1893
- const rows = deployment[target].tokens ?? [];
1894
- const token = rows.find((row) => !row.retired);
1895
- const id = target === "base" ? token?.address : target === "solana" ? token?.mint : token?.type;
1896
- if (!id) die(`manifest has no active ${target} token`);
1897
- const nonce = await adminNonceOf[target]();
1898
- const r = await pusd({
1899
- Action: "Attestor-Propose",
1900
- Op: "add-token",
1901
- Chain: target,
1902
- Token: id,
1903
- Symbol: token.symbol,
1904
- Decimals: String(token.decimals),
1905
- AdminNonce: String(nonce)
1906
- });
1907
- return console.log(`proposed #${r.ProposalId ?? "?"} for ${target} ${id}; next: approve ${r.ProposalId ?? "<id>"}`);
1908
- }
1909
- if (cmd === "unpause") {
1910
- const chain = opt("chain");
1911
- if (chain && !CHAINS.includes(chain)) die("unpause [--chain base|solana|sui]");
1912
- const tags = { Action: "Attestor-Propose", Op: "unpause" };
1913
- const TAG = { base: "BaseAdminNonce", solana: "SolanaAdminNonce", sui: "SuiAdminNonce" };
1914
- for (const c of chain ? [chain] : CHAINS) tags[TAG[c]] = String(await adminNonceOf[c]());
1915
- const r = await pusd(tags);
1916
- return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
1917
- }
1918
- if (cmd === "apply") {
1919
- const chain = opt("chain");
1920
- if (!target || chain && !CHAINS.includes(chain)) die("apply <id> [--chain base|solana|sui]");
1921
- const p = proposal(await bridgeInfo(), target);
1922
- if (p.status !== "applied") die(`#${p.id} is ${p.status}; its operators approve it and the nodes apply it first`);
1923
- p.votes = (await collectChainSignatures({ root: PUSD, node: NODE, proposal: p.id })).votes;
1924
- if (p.op === "migrate") {
1925
- const oldRoot = processHex(PUSD).toLowerCase();
1926
- const successor = processHex(p.successor).toLowerCase();
1927
- for (const c of chain ? [chain] : CHAINS) {
1928
- const current = await rootOf[c]();
1929
- if (current === successor) {
1930
- console.log(`${c}: already points to ${p.successor}`);
1931
- continue;
1932
- }
1933
- if (current !== oldRoot) die(`${c} points to ${current}, not ${PUSD}`);
1934
- console.log(`${c}: root ${p.successor}, ${await applyRootOn[c](p)}`);
1935
- }
1936
- return;
1937
- }
1938
- if (p.kind === "admin") {
1939
- if (!["add-token", "unpause"].includes(p.op)) {
1940
- console.log(`#${p.id} ${p.op} is AO-only and needs no chain application`);
1941
- return;
1942
- }
1943
- const targets = p.op === "add-token" ? [p.admin.chain] : chain ? [chain] : CHAINS;
1944
- if (chain && p.op === "add-token" && chain !== p.admin.chain) {
1945
- die(`#${p.id} adds a token on ${p.admin.chain}, not ${chain}`);
1946
- }
1947
- for (const c of targets) console.log(`${c}: ${p.op}, ${await applyAdminOn[c](p)}`);
1948
- return;
1949
- }
1950
- for (const c of chain ? [chain] : CHAINS) {
1951
- const now = await epochOf[c]();
1952
- if (now >= p.epoch) {
1953
- console.log(`${c}: already at epoch ${now}`);
1954
- continue;
1955
- }
1956
- if (now !== p.epoch - 1) die(`${c} is at epoch ${now}; apply the change to epoch ${now + 1} first`);
1957
- console.log(`${c}: epoch ${p.epoch}, ${await applyOn[c](p)}`);
1958
- }
1959
- return;
1960
- }
1961
- }
1962
- await main().catch((e) => die(e.shortMessage ?? e.message ?? String(e)));
1
+ #!/usr/bin/env node
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res, err) => function __init() {
4
+ if (err) throw err[0];
5
+ try {
6
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
7
+ } catch (e) {
8
+ throw err = [e], e;
9
+ }
10
+ };
11
+
12
+ // ../../backend/native/deploy-target.mjs
13
+ function origin(url) {
14
+ let parsed;
15
+ try {
16
+ parsed = new URL(String(url));
17
+ } catch {
18
+ return null;
19
+ }
20
+ const host = parsed.hostname === "localhost" ? "127.0.0.1" : parsed.hostname;
21
+ const port = parsed.port || (parsed.protocol === "https:" ? "443" : "80");
22
+ return `${parsed.protocol}//${host}:${port}`;
23
+ }
24
+ function pinnedTargets(env = process.env) {
25
+ const list = parseList(env[TARGET_ENV]).map(origin).filter(Boolean);
26
+ return list.length ? new Set(list) : null;
27
+ }
28
+ function assertDeployTarget(url, env = process.env) {
29
+ const pinned = pinnedTargets(env);
30
+ if (!pinned) return;
31
+ const o = origin(url);
32
+ if (!o || !pinned.has(o)) {
33
+ throw new Error(`refusing to send to ${url}: this deploy is pinned to ${[...pinned].join(", ")}`);
34
+ }
35
+ }
36
+ var TARGET_ENV, parseList, RECEIPT_FILES;
37
+ var init_deploy_target = __esm({
38
+ "../../backend/native/deploy-target.mjs"() {
39
+ TARGET_ENV = "PARALITH_DEPLOY_TARGET";
40
+ parseList = (value) => String(value || "").split(",").map((s) => s.trim()).filter(Boolean);
41
+ RECEIPT_FILES = Object.freeze([
42
+ "backend/native/deployment-state.json",
43
+ "backend/native/dao-state.json",
44
+ "backend/native/marketplace-state.json",
45
+ "backend/native/venue-state.json",
46
+ "backend/native/sharded-venue-state.json",
47
+ "backend/native/ranking-state.json",
48
+ "backend/native/faucet-state.json",
49
+ "backend/native/wasm-runtime-state.json",
50
+ "live-process.txt",
51
+ "rune-process.txt",
52
+ "hunt-process.txt",
53
+ "products/bridge/deployments/pusd-standin.json"
54
+ ]);
55
+ }
56
+ });
57
+
58
+ // ../rune-ao/src/lib/poll-wait.mjs
59
+ var init_poll_wait = __esm({
60
+ "../rune-ao/src/lib/poll-wait.mjs"() {
61
+ "use strict";
62
+ }
63
+ });
64
+
65
+ // ../rune-ao/src/lib/slot-settle.mjs
66
+ var init_slot_settle = __esm({
67
+ "../rune-ao/src/lib/slot-settle.mjs"() {
68
+ "use strict";
69
+ init_poll_wait();
70
+ }
71
+ });
72
+
73
+ // ../rune-ao/src/lib/gas.mjs
74
+ function isGasRefusal(res) {
75
+ return res?.status === 402;
76
+ }
77
+ function header(headers, name) {
78
+ if (!headers) return null;
79
+ if (typeof headers.get === "function") return headers.get(name);
80
+ return headers[name] ?? headers[name.toLowerCase()] ?? null;
81
+ }
82
+ function gasInt(value) {
83
+ if (typeof value === "number") return Number.isSafeInteger(value) ? value : null;
84
+ if (typeof value === "bigint") {
85
+ return value <= BigInt(Number.MAX_SAFE_INTEGER) && value >= -BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : null;
86
+ }
87
+ const text = String(value ?? "").trim().replace(/^"(.*)"$/, "$1");
88
+ if (!/^-?\d+$/.test(text)) return null;
89
+ const n = Number(text);
90
+ return Number.isSafeInteger(n) ? n : null;
91
+ }
92
+ function parseGasRequired(res, { node = null, account = null, process: process2 = null, body = null } = {}) {
93
+ if (!isGasRefusal(res)) return null;
94
+ const fields = {};
95
+ for (const name of ["price", "balance", "limit", "estimate", "held"]) fields[name] = gasInt(header(res.headers, name));
96
+ let unpayable = String(header(res.headers, "unpayable") ?? "").split(/[\s,"()]+/).filter((n) => /^https?:/.test(n));
97
+ const text = body === null || body === void 0 ? typeof res.body === "string" || res.body instanceof Uint8Array ? res.body : "" : body;
98
+ const str = typeof text === "string" ? text : new TextDecoder().decode(text);
99
+ let message = str;
100
+ if (/^\s*\{/.test(str)) {
101
+ try {
102
+ const json = JSON.parse(str);
103
+ for (const name of Object.keys(fields)) if (fields[name] === null) fields[name] = gasInt(json?.[name]);
104
+ if (!unpayable.length && Array.isArray(json?.unpayable)) unpayable = json.unpayable.filter((n) => typeof n === "string");
105
+ if (typeof json?.body === "string") message = json.body;
106
+ } catch {
107
+ }
108
+ }
109
+ const detail = HTML.test(message) ? "" : message.trim().slice(0, 120);
110
+ return new GasRequiredError({
111
+ ...fields,
112
+ unpayable,
113
+ node,
114
+ account,
115
+ process: process2,
116
+ detail: detail === "Insufficient funds" ? "" : detail
117
+ });
118
+ }
119
+ var GAS_MAX_TAG_BYTES, GAS_MAX_FOR, HTML, GasRequiredError, reads;
120
+ var init_gas = __esm({
121
+ "../rune-ao/src/lib/gas.mjs"() {
122
+ "use strict";
123
+ GAS_MAX_TAG_BYTES = 3072;
124
+ GAS_MAX_FOR = Math.floor((GAS_MAX_TAG_BYTES + 1) / 44);
125
+ HTML = /^\s*(?:<!doctype\s+html|<html|<head|<body)/i;
126
+ GasRequiredError = class extends Error {
127
+ constructor({
128
+ price = null,
129
+ balance = null,
130
+ node = null,
131
+ account = null,
132
+ process: process2 = null,
133
+ detail = "",
134
+ limit = null,
135
+ estimate = null,
136
+ held = null,
137
+ unpayable = []
138
+ } = {}) {
139
+ const need = price === null ? "" : ` It costs ${price}`;
140
+ const have = balance === null ? "" : `${need ? ";" : " The"} balance is ${balance}`;
141
+ super(`Gas required${node ? ` on ${node}` : ""}.${need}${have}${need || have ? " (PUSD base units)." : ""} Nothing was scheduled. Deposit gas, then send it again.` + (detail ? ` (${detail})` : ""));
142
+ this.name = "GasRequiredError";
143
+ this.status = 402;
144
+ this.scheduled = false;
145
+ this.gas = true;
146
+ this.price = price;
147
+ this.balance = balance;
148
+ this.node = node;
149
+ this.account = account;
150
+ this.process = process2;
151
+ this.limit = limit;
152
+ this.estimate = estimate;
153
+ this.held = held;
154
+ this.unpayable = Array.isArray(unpayable) ? unpayable : [];
155
+ }
156
+ };
157
+ reads = /* @__PURE__ */ new Map();
158
+ if (typeof globalThis.addEventListener === "function") {
159
+ globalThis.addEventListener("paralith:gas-changed", () => reads.clear());
160
+ }
161
+ }
162
+ });
163
+
164
+ // ../rune-ao/src/lib/admission.mjs
165
+ function header2(headers, name) {
166
+ if (!headers) return null;
167
+ if (typeof headers.get === "function") return headers.get(name);
168
+ return headers[name] ?? null;
169
+ }
170
+ function isAdmissionRefusal(res) {
171
+ if (res?.status === 429) return true;
172
+ return res?.status === 503 && String(header2(res.headers, ADMISSION_HEADER) ?? "").trim() === "busy";
173
+ }
174
+ function retryAfterMs(value, now = Date.now()) {
175
+ const text = String(value ?? "").trim();
176
+ if (/^\d+$/.test(text)) return Number(text) * 1e3;
177
+ const at = Date.parse(text);
178
+ return Number.isFinite(at) ? Math.max(0, at - now) : 1e3;
179
+ }
180
+ function admissionDelayMs(attempt, retryAfter, random = Math.random) {
181
+ const exp = Math.min(ADMISSION_BACKOFF.capMs, ADMISSION_BACKOFF.baseMs * 2 ** attempt);
182
+ const wait = Math.max(retryAfter, exp);
183
+ return Math.round(wait + random() * wait / 2);
184
+ }
185
+ async function postAdmitted(post, {
186
+ budgetMs = ADMISSION_BUDGET_MS,
187
+ signal,
188
+ onRefused,
189
+ random = Math.random,
190
+ now = Date.now,
191
+ sleep = pause
192
+ } = {}) {
193
+ const started = now();
194
+ for (let attempt = 0; ; attempt += 1) {
195
+ const res = await post();
196
+ if (!isAdmissionRefusal(res)) return res;
197
+ try {
198
+ onRefused?.();
199
+ } catch {
200
+ }
201
+ const wait = admissionDelayMs(attempt, retryAfterMs(header2(res.headers, "retry-after"), now()), random);
202
+ if (now() - started + wait > budgetMs) return res;
203
+ try {
204
+ await res.arrayBuffer?.();
205
+ } catch {
206
+ }
207
+ try {
208
+ await sleep(wait, signal);
209
+ } catch (reason) {
210
+ throw new AdmissionWaitAborted(reason);
211
+ }
212
+ }
213
+ }
214
+ var ADMISSION_HEADER, ADMISSION_BACKOFF, ADMISSION_BUDGET_MS, pause, AdmissionWaitAborted;
215
+ var init_admission = __esm({
216
+ "../rune-ao/src/lib/admission.mjs"() {
217
+ "use strict";
218
+ init_gas();
219
+ ADMISSION_HEADER = "hb-admission";
220
+ ADMISSION_BACKOFF = Object.freeze({ baseMs: 1e3, capMs: 8e3 });
221
+ ADMISSION_BUDGET_MS = 3e4;
222
+ pause = (ms, signal) => new Promise((resolve, reject) => {
223
+ if (signal?.aborted) {
224
+ reject(signal.reason);
225
+ return;
226
+ }
227
+ const timer = setTimeout(() => {
228
+ signal?.removeEventListener?.("abort", onAbort);
229
+ resolve();
230
+ }, ms);
231
+ const onAbort = () => {
232
+ clearTimeout(timer);
233
+ reject(signal.reason);
234
+ };
235
+ signal?.addEventListener?.("abort", onAbort, { once: true });
236
+ });
237
+ AdmissionWaitAborted = class extends Error {
238
+ constructor(reason) {
239
+ super("The write was aborted while the node was refusing it; nothing was accepted.");
240
+ this.name = "AbortError";
241
+ this.cause = reason;
242
+ }
243
+ };
244
+ }
245
+ });
246
+
247
+ // ../rune-ao/src/lib/transport-timeouts.mjs
248
+ function pushRequestInit() {
249
+ const dispatcher = globalThis[PUSH_DISPATCHER];
250
+ return dispatcher ? { dispatcher } : {};
251
+ }
252
+ var DEFAULT_TRANSPORT_TIMEOUTS, PUSH_SOCKET_CAP_MS, PUSH_DISPATCHER;
253
+ var init_transport_timeouts = __esm({
254
+ "../rune-ao/src/lib/transport-timeouts.mjs"() {
255
+ "use strict";
256
+ DEFAULT_TRANSPORT_TIMEOUTS = Object.freeze({
257
+ publishedReadMs: 3e3,
258
+ computeReadMs: 6e3,
259
+ replyMs: 25e3,
260
+ replyRecoveryMs: 3e4,
261
+ deliveryMs: 9e4
262
+ });
263
+ PUSH_SOCKET_CAP_MS = 10 * 6e4;
264
+ PUSH_DISPATCHER = /* @__PURE__ */ Symbol.for("paralith.push-dispatcher");
265
+ }
266
+ });
267
+
268
+ // ../rune-ao/src/lib/slot-result.mjs
269
+ async function nodeDeliversOutboxes(node, {
270
+ fetchImpl = globalThis.fetch,
271
+ timeoutMs = 3e3,
272
+ maxAgeMs = OUTBOX_DELIVERY_RECHECK_MS
273
+ } = {}) {
274
+ const base = String(node ?? "").replace(/\/+$/, "");
275
+ const known = deliveringNodes.get(base);
276
+ if (known !== void 0 && Date.now() - known.at < maxAgeMs) return known.delivers;
277
+ let answer = null;
278
+ try {
279
+ const res = await fetchImpl(`${base}/${OUTBOX_DELIVERY_PATH}`, {
280
+ headers: { accept: "text/plain" },
281
+ signal: AbortSignal.timeout(timeoutMs)
282
+ });
283
+ const text = res.status === 200 ? (await res.text()).trim() : "";
284
+ answer = text === OUTBOX_DELIVERY_VALUE ? true : res.status >= 500 ? null : false;
285
+ } catch {
286
+ answer = null;
287
+ }
288
+ if (answer !== null) deliveringNodes.set(base, { delivers: answer, at: Date.now() });
289
+ return answer === true;
290
+ }
291
+ function parsePushReceipts(text) {
292
+ let body;
293
+ try {
294
+ body = JSON.parse(String(text ?? ""));
295
+ } catch {
296
+ return null;
297
+ }
298
+ if (body === null || typeof body !== "object" || Array.isArray(body)) return null;
299
+ const outbox = body.outbox ?? body.results?.outbox;
300
+ if (outbox !== void 0 && (outbox === null || typeof outbox !== "object")) return null;
301
+ const keys = nonEmpty(outbox) ? Object.keys(outbox) : [];
302
+ const receipts = {};
303
+ const terminal = [];
304
+ const pending = [];
305
+ let delivered = true;
306
+ for (const key of keys) {
307
+ const receipt = body[key];
308
+ receipts[key] = receipt ?? null;
309
+ if (receiptTerminal(receipt)) terminal.push(key);
310
+ else if (receiptLookup(receipt)) pending.push(key);
311
+ else if (!receiptSlot(receipt)) delivered = false;
312
+ }
313
+ const output = body.output ?? body.results?.output;
314
+ const data = output !== null && typeof output === "object" ? output.data : void 0;
315
+ return {
316
+ delivered,
317
+ receipts,
318
+ terminal,
319
+ pending,
320
+ reply: typeof data === "string" && data !== "" ? data : null
321
+ };
322
+ }
323
+ async function pushVerdict(node, status2, text, delivers, { fetchImpl = globalThis.fetch } = {}) {
324
+ if (notDeliveringAnswer(status2, text) && (delivers || await nodeDeliversOutboxes(node, { fetchImpl, maxAgeMs: 0 }))) {
325
+ return { delivered: false, notDelivering: true };
326
+ }
327
+ if (!delivers) return { delivered: null, notDelivering: false };
328
+ return {
329
+ delivered: status2 >= 200 && status2 < 300 && parsePushReceipts(text)?.delivered === true,
330
+ notDelivering: false
331
+ };
332
+ }
333
+ var SLOT_RESULT_HEADERS, nonEmpty, OUTBOX_DELIVERY_PATH, OUTBOX_DELIVERY_VALUE, deliveringNodes, OUTBOX_DELIVERY_RECHECK_MS, receiptSlot, receiptTerminal, receiptLookup, notDeliveringAnswer;
334
+ var init_slot_result = __esm({
335
+ "../rune-ao/src/lib/slot-result.mjs"() {
336
+ "use strict";
337
+ SLOT_RESULT_HEADERS = Object.freeze({ accept: "application/json", "accept-bundle": "true", "cache-control": "no-cache" });
338
+ nonEmpty = (value) => value !== null && typeof value === "object" && Object.keys(value).length > 0;
339
+ OUTBOX_DELIVERY_PATH = "~meta@1.0/info/outbox-delivery";
340
+ OUTBOX_DELIVERY_VALUE = "durable";
341
+ deliveringNodes = /* @__PURE__ */ new Map();
342
+ OUTBOX_DELIVERY_RECHECK_MS = 5 * 6e4;
343
+ receiptSlot = (r) => r !== null && typeof r === "object" && r.status !== "terminal" && (typeof r.slot === "number" && Number.isSafeInteger(r.slot) && r.slot >= 0 || typeof r.slot === "string" && /^\d+$/.test(r.slot));
344
+ receiptTerminal = (r) => r !== null && typeof r === "object" && r.status === "terminal";
345
+ receiptLookup = (r) => r !== null && typeof r === "object" && r.status === "pending" && r.reason === "target_lookup";
346
+ notDeliveringAnswer = (status2, text) => status2 !== 200 && /does not deliver/i.test(String(text ?? ""));
347
+ }
348
+ });
349
+
350
+ // ../../backend/native/hbclient.mjs
351
+ import crypto2 from "node:crypto";
352
+ function sfString(s) {
353
+ return '"' + String(s).replace(/\\/g, "\\\\").replace(/"/g, '\\"') + '"';
354
+ }
355
+ function sfBareItem(v) {
356
+ if (v && v.__sf === "binary") return ":" + b64std(v.value) + ":";
357
+ if (v && v.__sf === "token") return String(v.value);
358
+ if (v && v.__sf === "string") return sfString(v.value);
359
+ if (typeof v === "number") return String(v);
360
+ return sfString(v);
361
+ }
362
+ function sfParams(params) {
363
+ return params.map(([k, v]) => ";" + k + "=" + sfBareItem(v)).join("");
364
+ }
365
+ function sfInnerList(items, params) {
366
+ return "(" + items.map((i) => sfBareItem(i)).join(" ") + ")" + sfParams(params || []);
367
+ }
368
+ function sfDict(entries) {
369
+ return entries.map(([k, v]) => k + "=" + v).join(", ");
370
+ }
371
+ function binCmp(a, b) {
372
+ return Buffer.compare(Buffer.from(a, "binary"), Buffer.from(b, "binary"));
373
+ }
374
+ function encodeHeaderValue(v) {
375
+ const s = Buffer.isBuffer(v) ? v.toString("latin1") : String(v);
376
+ return s.replace(/\\/g, "\\\\").replace(/\r/g, "\\r").replace(/\n/g, "\\n");
377
+ }
378
+ function escapeKey(k) {
379
+ if (URI_SAFE.test(k)) return k;
380
+ let out = "";
381
+ for (const byte of Buffer.from(k, "utf8")) {
382
+ const c = String.fromCharCode(byte);
383
+ if (/[a-z0-9.\-_/?&]/.test(c)) out += c;
384
+ else out += "%" + byte.toString(16).toUpperCase().padStart(2, "0");
385
+ }
386
+ return out;
387
+ }
388
+ function isPlainObject(v) {
389
+ return v !== null && typeof v === "object" && !Buffer.isBuffer(v) && !Array.isArray(v);
390
+ }
391
+ function toTabm(value) {
392
+ if (Buffer.isBuffer(value)) return value;
393
+ if (typeof value === "string") return Buffer.from(value, "utf8");
394
+ if (Array.isArray(value)) {
395
+ const numbered = {};
396
+ value.forEach((v, i) => {
397
+ numbered[String(i + 1)] = v;
398
+ });
399
+ const m = toTabm(numbered);
400
+ const types = parseAoTypes(m["ao-types"]);
401
+ types["."] = "list";
402
+ m["ao-types"] = Buffer.from(encodeAoTypes(types), "utf8");
403
+ return m;
404
+ }
405
+ if (isPlainObject(value)) {
406
+ const types = {};
407
+ const out = {};
408
+ for (const key of sortedKeys(value)) {
409
+ if (key === "commitments" || key === "priv" || key.startsWith("priv/")) continue;
410
+ const v = value[key];
411
+ if (v === void 0) continue;
412
+ if (typeof v === "string" || Buffer.isBuffer(v)) {
413
+ out[key] = toTabm(v);
414
+ } else if (Array.isArray(v) || isPlainObject(v)) {
415
+ out[key] = toTabm(v);
416
+ } else if (typeof v === "number") {
417
+ if (Number.isInteger(v)) {
418
+ types[key] = "integer";
419
+ out[key] = Buffer.from(String(v));
420
+ } else {
421
+ types[key] = "float";
422
+ out[key] = Buffer.from(String(v));
423
+ }
424
+ } else if (typeof v === "boolean" || v === null) {
425
+ types[key] = "atom";
426
+ out[key] = Buffer.from(v === null ? "null" : String(v));
427
+ }
428
+ }
429
+ if (Object.keys(types).length) out["ao-types"] = Buffer.from(encodeAoTypes(types), "utf8");
430
+ return out;
431
+ }
432
+ return Buffer.from(String(value), "utf8");
433
+ }
434
+ function encodeAoTypes(types) {
435
+ const groups = /* @__PURE__ */ new Map();
436
+ for (const key of Object.keys(types).sort(byBytes)) {
437
+ const type = types[key];
438
+ if (!groups.has(type)) groups.set(type, []);
439
+ groups.get(type).push(key);
440
+ }
441
+ return [...groups.keys()].sort(byBytes).map(
442
+ (type) => type + "=(" + groups.get(type).map(
443
+ (key) => /^[ -~]*$/.test(key) ? sfString(key) : ":" + b64std(Buffer.from(key)) + ":"
444
+ ).join(" ") + ")"
445
+ ).join(", ");
446
+ }
447
+ function parseAoTypes(bin) {
448
+ if (!bin) return {};
449
+ const s = Buffer.isBuffer(bin) ? bin.toString("utf8") : String(bin);
450
+ const out = {};
451
+ for (const m of s.matchAll(/([a-z0-9*_.-]+)=\(([^)]*)\)/g)) {
452
+ for (const k of m[2].matchAll(/"((?:[^"\\]|\\.)*)"|:([A-Za-z0-9+/=]*):/g)) {
453
+ const key = k[1] !== void 0 ? k[1].replace(/\\(.)/g, "$1") : Buffer.from(k[2], "base64").toString("utf8");
454
+ out[key] = m[1];
455
+ }
456
+ }
457
+ for (const part of s.split(",")) {
458
+ const m = part.trim().match(/^([^=(]+)="([^"]*)"$/);
459
+ if (m) out[m[1]] = m[2];
460
+ }
461
+ return out;
462
+ }
463
+ function inlineKey(msg) {
464
+ const explicit = msg["ao-body-key"];
465
+ if (explicit !== void 0) {
466
+ return { extra: {}, key: Buffer.isBuffer(explicit) ? explicit.toString() : String(explicit) };
467
+ }
468
+ if (Object.prototype.hasOwnProperty.call(msg, "body")) return { extra: {}, key: "body" };
469
+ if (Object.prototype.hasOwnProperty.call(msg, "data")) {
470
+ return { extra: { "ao-body-key": Buffer.from("data") }, key: "data" };
471
+ }
472
+ return { extra: {}, key: "body" };
473
+ }
474
+ function groupMaps(map, parent, top) {
475
+ const flattened = {};
476
+ for (const key of sortedKeys(map)) {
477
+ const value = map[key];
478
+ const normKey = key;
479
+ const flatK = parent === "" ? normKey : parent + "/" + normKey;
480
+ if (isPlainObject(value)) {
481
+ if (Object.keys(value).length === 0) {
482
+ top[flatK] = { "ao-types": Buffer.from("empty-message") };
483
+ } else {
484
+ top = groupMaps(value, flatK, top);
485
+ }
486
+ } else {
487
+ const buf = Buffer.isBuffer(value) ? value : Buffer.from(String(value));
488
+ if (normKey === "content-disposition" || buf.length > MAX_HEADER_LENGTH) {
489
+ top[flatK] = buf;
490
+ } else {
491
+ flattened[normKey] = buf;
492
+ }
493
+ }
494
+ }
495
+ if (Object.keys(flattened).length === 0) return top;
496
+ if (parent === "") return Object.assign({}, top, flattened);
497
+ top[parent] = flattened;
498
+ return top;
499
+ }
500
+ function encodeFlatMsg(msg) {
501
+ const headerKeys = sortedKeys(msg).filter((k) => k !== "body" && k !== "priv");
502
+ const headers = headerKeys.map((k) => Buffer.concat([Buffer.from(k + ": "), asBuf(msg[k])])).reduce((acc, b, i) => i === 0 ? [b] : acc.concat([Buffer.from(CRLF), b]), []);
503
+ const head = Buffer.concat(headers);
504
+ const body = msg.body === void 0 ? Buffer.alloc(0) : asBuf(msg.body);
505
+ if (body.length === 0) return head;
506
+ return Buffer.concat([head, Buffer.from(CRLF + CRLF), body]);
507
+ }
508
+ function encodeBodyPart(partName, part, inlKey) {
509
+ const disposition = partName === inlKey ? "inline" : `form-data;name="${partName}"`;
510
+ if (isPlainObject(part)) {
511
+ return encodeFlatMsg(Object.assign({}, part, {
512
+ "content-disposition": Buffer.from(disposition)
513
+ }));
514
+ }
515
+ return Buffer.concat([
516
+ Buffer.from("content-disposition: " + disposition + CRLF + CRLF),
517
+ asBuf(part)
518
+ ]);
519
+ }
520
+ function tabmToHttp(tabm) {
521
+ const stripped = {};
522
+ for (const k of Object.keys(tabm)) {
523
+ if (["commitments", "signature", "signature-input", "priv"].includes(k)) continue;
524
+ stripped[IS_ID(k) ? escapeKey(k) : k] = tabm[k];
525
+ }
526
+ const { extra, key: inlKey } = inlineKey(stripped);
527
+ const headers = {};
528
+ const bodyMap = {};
529
+ for (const [k, v] of Object.entries(extra)) headers[k] = v;
530
+ for (const key of sortedKeys(stripped)) {
531
+ const value = stripped[key];
532
+ if (key === "body") {
533
+ bodyMap["body"] = value;
534
+ continue;
535
+ }
536
+ if (key === inlKey) {
537
+ bodyMap[inlKey] = value;
538
+ continue;
539
+ }
540
+ if (isPlainObject(value)) {
541
+ bodyMap[key] = value;
542
+ continue;
543
+ }
544
+ const buf = asBuf(value);
545
+ if (buf.length <= MAX_HEADER_LENGTH) headers[key] = buf;
546
+ else bodyMap[key] = buf;
547
+ }
548
+ const grouped = groupMaps(bodyMap, "", {});
549
+ const gKeys = sortedKeys(grouped);
550
+ let body = null;
551
+ if (gKeys.length === 0) {
552
+ body = null;
553
+ } else if (gKeys.length === 1 && gKeys[0] === inlKey && Buffer.isBuffer(grouped[inlKey])) {
554
+ body = grouped[inlKey];
555
+ } else {
556
+ const parts = gKeys.map((k) => {
557
+ const v = grouped[k];
558
+ if (isPlainObject(v) && Object.keys(v).length === 1 && Object.prototype.hasOwnProperty.call(v, "body")) {
559
+ return encodeBodyPart(k + "/body", v, "body");
560
+ }
561
+ return encodeBodyPart(k, v, inlKey);
562
+ });
563
+ const joined = parts.reduce(
564
+ (acc, p, i) => i === 0 ? [p] : acc.concat([Buffer.from(CRLF), p]),
565
+ []
566
+ );
567
+ const boundary = b64url(sha256(Buffer.concat(joined)));
568
+ const withMarkers = parts.reduce(
569
+ (acc, p, i) => acc.concat(
570
+ i === 0 ? [] : [Buffer.from(CRLF)],
571
+ [Buffer.from("--" + boundary + CRLF), p]
572
+ ),
573
+ []
574
+ );
575
+ body = Buffer.concat([
576
+ Buffer.concat(withMarkers),
577
+ Buffer.from(CRLF + "--" + boundary + "--")
578
+ ]);
579
+ headers["content-type"] = Buffer.from(`multipart/form-data; boundary="${boundary}"`);
580
+ }
581
+ const outHeaders = {};
582
+ for (const k of Object.keys(headers)) outHeaders[k] = encodeHeaderValue(headers[k]);
583
+ if (body && body.length) {
584
+ outHeaders["content-digest"] = "sha-256=:" + b64std(sha256(body)) + ":";
585
+ }
586
+ return { headers: outHeaders, body };
587
+ }
588
+ function addDerivedSpecifiers(keys) {
589
+ return keys.map((k) => {
590
+ const bare = k.startsWith("@") ? k.slice(1) : k;
591
+ return DERIVED_COMPONENTS.has(bare) ? "@" + bare : bare;
592
+ });
593
+ }
594
+ function signatureBase(encHeaders, committed, params) {
595
+ const lines = committed.map((name) => {
596
+ const v = encHeaders[name];
597
+ if (v === void 0) {
598
+ throw new Error("missing_key_for_signature_component_line: " + name);
599
+ }
600
+ return `"${name}": ${v}`;
601
+ });
602
+ const paramsLine = sfInnerList(
603
+ addDerivedSpecifiers(committed).map((k) => sfStr(k)),
604
+ params
605
+ );
606
+ return Buffer.from(lines.join("\n") + '\n"@signature-params": ' + paramsLine, "utf8");
607
+ }
608
+ function commitmentParams({ alg, bundle, created, expires, keyid, nonce, tag, publicKey }) {
609
+ const out = [];
610
+ if (alg !== void 0) out.push(["alg", sfStr(alg)]);
611
+ if (bundle !== void 0) out.push(["bundle", sfStr(bundle)]);
612
+ if (created !== void 0) out.push(["created", created]);
613
+ if (expires !== void 0) out.push(["expires", expires]);
614
+ if (keyid !== void 0) out.push(["keyid", sfStr(keyid)]);
615
+ if (nonce !== void 0) out.push(["nonce", sfStr(nonce)]);
616
+ if (publicKey !== void 0) out.push(["public-key", sfStr(publicKey)]);
617
+ if (tag !== void 0) out.push(["tag", sfStr(tag)]);
618
+ return out;
619
+ }
620
+ function committerUri(address) {
621
+ const lower = address.toLowerCase().replace(/_/g, "-");
622
+ let mask = 0n;
623
+ for (const c of address) mask = mask << 1n | (c >= "A" && c <= "Z" || c === "_" ? 1n : 0n);
624
+ return "uri-did-ar-" + lower + (mask << 3n).toString(36).padStart(9, "0");
625
+ }
626
+ function keyParams(jwk) {
627
+ return { keyid: committerUri(jwkToAddress(jwk)), publicKey: b64url(pubKeyBuf(jwk)) };
628
+ }
629
+ function jwkToPrivateKey(jwk) {
630
+ return crypto2.createPrivateKey({ key: { ...jwk, kty: "RSA" }, format: "jwk" });
631
+ }
632
+ function pubKeyBuf(jwk) {
633
+ return b64urlDec(jwk.n);
634
+ }
635
+ function ownerToAddress(nB64url) {
636
+ return b64url(sha256(b64urlDec(nB64url)));
637
+ }
638
+ function jwkToAddress(jwk) {
639
+ return ownerToAddress(jwk.kty === "OKP" ? jwk.x : jwk.n);
640
+ }
641
+ function rsaPssSign(jwk, data) {
642
+ return crypto2.sign("sha512", data, {
643
+ key: jwkToPrivateKey(jwk),
644
+ padding: crypto2.constants.RSA_PKCS1_PSS_PADDING,
645
+ saltLength: 64
646
+ // SHA-512 digest length; ar_wallet/rsa_pss uses saltLen == hashLen
647
+ });
648
+ }
649
+ function wireToMessageKeys(wire, bodyKeys, headers) {
650
+ let out = [];
651
+ for (const k of wire) {
652
+ if (k === "content-digest") out.push(...bodyKeys);
653
+ else out.push(k);
654
+ }
655
+ if (headers["ao-body-key"] !== void 0) {
656
+ const abk = String(headers["ao-body-key"]);
657
+ out = out.flatMap((k) => k === "body" ? [abk] : [k]).filter((k) => k !== "ao-body-key");
658
+ }
659
+ if (/^multipart\//.test(String(headers["content-type"] || ""))) {
660
+ out = out.filter((k) => k !== "content-type");
661
+ }
662
+ return out;
663
+ }
664
+ function isListTabm(sub) {
665
+ const t = parseAoTypes(sub["ao-types"]);
666
+ return t["."] === "list";
667
+ }
668
+ function hmacCommit(subTabm) {
669
+ const bare = { ...subTabm };
670
+ delete bare.commitments;
671
+ const { headers } = tabmToHttp(bare);
672
+ const wire = sortedKeys(headers).filter((k) => k !== "signature" && k !== "signature-input");
673
+ const params = commitmentParams({ alg: "hmac-sha256", keyid: "constant:ao" });
674
+ const base = signatureBase(headers, wire, params);
675
+ const mac = crypto2.createHmac("sha256", "constant:ao").update(base).digest();
676
+ const id = b64url(mac);
677
+ const rawInputs = sortedKeys(bare);
678
+ const bodyKeys = rawInputs.filter((k) => headers[k] === void 0 && headers[k + "+link"] === void 0);
679
+ const committed = wireToMessageKeys(wire, bodyKeys, headers);
680
+ return {
681
+ ...subTabm,
682
+ commitments: {
683
+ [id]: {
684
+ "commitment-device": Buffer.from("httpsig@1.0"),
685
+ committed: toTabm(committed),
686
+ keyid: Buffer.from("constant:ao"),
687
+ signature: Buffer.from(id),
688
+ type: Buffer.from("hmac-sha256")
689
+ }
690
+ }
691
+ };
692
+ }
693
+ function withNestedHmacs(tabm) {
694
+ if (!isPlainObject(tabm)) return tabm;
695
+ const out = {};
696
+ for (const [k, v] of Object.entries(tabm)) {
697
+ if (k === "commitments") {
698
+ out[k] = v;
699
+ continue;
700
+ }
701
+ if (isPlainObject(v)) {
702
+ const inner = withNestedHmacs(v);
703
+ out[k] = isListTabm(v) || v.commitments ? inner : hmacCommit(inner);
704
+ } else out[k] = v;
705
+ }
706
+ return out;
707
+ }
708
+ function commit(msg, jwk, opts = {}) {
709
+ const { bundle = "true", nestedHmacs = false, ...params0 } = opts;
710
+ const tEncode = process.hrtime.bigint();
711
+ const tabm = nestedHmacs ? withNestedHmacs(toTabm(msg)) : toTabm(msg);
712
+ const { headers, body } = tabmToHttp(tabm);
713
+ const committed = sortedKeys(headers).filter(
714
+ (k) => k !== "signature" && k !== "signature-input"
715
+ );
716
+ const params = commitmentParams({ alg: "rsa-pss-sha512", bundle, ...keyParams(jwk), ...params0 });
717
+ const base = signatureBase(headers, committed, params);
718
+ const tSign = process.hrtime.bigint();
719
+ const sig = rsaPssSign(jwk, base);
720
+ const tSeal = process.hrtime.bigint();
721
+ const name = "comm-" + b64url(sha256(sig)).toLowerCase();
722
+ const outHeaders = { ...headers };
723
+ outHeaders["signature"] = sfDict([[name, ":" + b64std(sig) + ":"]]);
724
+ outHeaders["signature-input"] = sfDict([[name, sfInnerList(
725
+ addDerivedSpecifiers(committed).map((k) => sfStr(k)),
726
+ params
727
+ )]]);
728
+ return {
729
+ headers: outHeaders,
730
+ body,
731
+ signatureBase: base,
732
+ committed,
733
+ sigName: name,
734
+ timing: {
735
+ // The message's signed ID, as the node names it: the SHA-256 of the
736
+ // signature. The node's message trace (`/~hyperbuddy@1.0/trace`) carries it.
737
+ mid: b64url(sha256(sig)),
738
+ encodeMs: durMs(tEncode, tSign),
739
+ signMs: durMs(tSign, tSeal),
740
+ sealMs: durMs(tSeal, process.hrtime.bigint())
741
+ }
742
+ };
743
+ }
744
+ async function send(node, path3, method, headers, body, signal, init = {}) {
745
+ const url = transportNode(node) + (path3.startsWith("/") ? path3 : "/" + path3);
746
+ httpRequests += 1;
747
+ assertDeployTarget(url);
748
+ const res = await fetchWithinTarget(url, {
749
+ ...init,
750
+ method,
751
+ headers: { ...headers, "accept-bundle": "true" },
752
+ body: body && body.length ? body : void 0,
753
+ ...signal ? { signal } : {}
754
+ });
755
+ const buf = Buffer.from(await res.arrayBuffer());
756
+ const h = {};
757
+ res.headers.forEach((v, k) => {
758
+ h[k] = v;
759
+ });
760
+ return { status: res.status, headers: h, body: buf, url };
761
+ }
762
+ async function fetchWithinTarget(url, init, hops = 0) {
763
+ if (!pinnedTargets()) return fetch(url, { ...init, redirect: "follow" });
764
+ const res = await fetch(url, { ...init, redirect: "manual" });
765
+ const location = res.status >= 300 && res.status < 400 ? res.headers.get("location") : null;
766
+ if (!location) return res;
767
+ if (hops >= 5) throw new Error(`too many redirects from ${url}`);
768
+ const next = new URL(location, url).toString();
769
+ assertDeployTarget(next);
770
+ const keepsBody = res.status === 307 || res.status === 308;
771
+ return fetchWithinTarget(next, keepsBody ? init : { ...init, method: "GET", body: void 0 }, hops + 1);
772
+ }
773
+ function transportNode(node) {
774
+ return (process.env.NODE_TRANSPORT_URL || node).replace(/\/$/, "");
775
+ }
776
+ function hbError(res) {
777
+ const t = res.body.toString();
778
+ const m = t.match(/Error details:([\s\S]*?)<\/pre>/);
779
+ const dec = (x) => x.replace(/&quot;/g, '"').replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&amp;/g, "&").replace(/&#39;/g, "'");
780
+ if (m) return dec(m[1]).replace(/\s+/g, " ").trim();
781
+ return res.headers["details"] || t.slice(0, 400);
782
+ }
783
+ async function postSigned(node, path3, msg, jwk, opts = {}) {
784
+ const { headers, body, signatureBase: base, committed, timing } = commit(msg, jwk, opts);
785
+ const tPost = process.hrtime.bigint();
786
+ let refusals = 0;
787
+ const res = await postAdmitted(
788
+ () => send(node, path3, "POST", headers, body),
789
+ { onRefused: () => {
790
+ refusals += 1;
791
+ } }
792
+ );
793
+ const postMs = durMs(tPost, process.hrtime.bigint());
794
+ res.request = { headers, body, base, committed };
795
+ res.timing = { ...timing, postMs, bytes: body ? body.length : 0, ...refusals ? { refusals } : {} };
796
+ if (isGasRefusal(res)) {
797
+ const error = parseGasRequired(res, { node, account: jwkToAddress(jwk), process: msg?.target ?? null });
798
+ error.timing = res.timing;
799
+ throw error;
800
+ }
801
+ return res;
802
+ }
803
+ function observeSend(timing, observer = sendObserver) {
804
+ if (!observer) return;
805
+ try {
806
+ observer(timing);
807
+ } catch {
808
+ }
809
+ }
810
+ async function sendMessage({
811
+ node,
812
+ jwk,
813
+ process: pid,
814
+ action: action2,
815
+ tags = {},
816
+ data,
817
+ body,
818
+ path: path3,
819
+ push = true
820
+ }) {
821
+ const t0 = Date.now();
822
+ const started = process.hrtime.bigint();
823
+ const fields = /* @__PURE__ */ new Map();
824
+ const put = (k, v) => {
825
+ if (v === void 0 || v === null) return;
826
+ fields.set(String(k).toLowerCase(), typeof v === "string" ? v : String(v));
827
+ };
828
+ put("target", pid);
829
+ put("type", "Message");
830
+ put("subject", "self");
831
+ if (action2) put("action", action2);
832
+ for (const [k, v] of Object.entries(tags)) put(k, v);
833
+ if (data !== void 0) put("data", data);
834
+ put("random-seed", String(Math.floor(Math.random() * 1e9)));
835
+ const msg = {
836
+ ...Object.fromEntries(fields),
837
+ ...body === void 0 ? {} : { body }
838
+ };
839
+ const sentAction = fields.get("action")?.toLowerCase() ?? null;
840
+ const timing = (outcome, { res = null, slot = null, error: error2 } = {}) => {
841
+ const t = res?.timing;
842
+ return {
843
+ action: sentAction,
844
+ slot: slot === null || slot === void 0 ? null : Number(slot),
845
+ node,
846
+ pid,
847
+ pidRole: sentAction?.startsWith("admin.") ? "admin" : sendRoles[pid] ?? null,
848
+ t0,
849
+ t1: Date.now(),
850
+ buildMs: t ? t.encodeMs : 0,
851
+ ...t?.mid ? { mid: t.mid } : {},
852
+ signMs: t ? t.signMs + t.sealMs : 0,
853
+ postMs: t ? t.postMs : 0,
854
+ sendMs: durMs(started, process.hrtime.bigint()),
855
+ bytes: t ? t.bytes : 0,
856
+ ...t?.refusals ? { refusals: t.refusals } : {},
857
+ // As in `TransportTiming`: a reply was read, which a refusal also is.
858
+ ok: outcome === "ok" || outcome === "rejected",
859
+ outcome,
860
+ ...error2 === void 0 ? {} : { error: error2 }
861
+ };
862
+ };
863
+ const report = (outcome, detail) => {
864
+ if (sendObserver) observeSend(timing(outcome, detail));
865
+ };
866
+ const candidates = path3 ? [path3] : [`/${pid}~process@1.0/schedule`, `/${pid}~scheduler@1.0/schedule`, `/${pid}/schedule`];
867
+ const known = SCHEDULE_ROUTE.get(node)?.replaceAll(PID_SLOT, pid);
868
+ const ordered = known && !path3 ? [known, ...candidates.filter((p) => p !== known)] : candidates;
869
+ const tried = [];
870
+ let lastResponse = null;
871
+ for (const candidate of ordered) {
872
+ let res;
873
+ try {
874
+ res = await postSigned(node, candidate, msg, jwk);
875
+ } catch (error2) {
876
+ report(error2?.name === "GasRequiredError" ? "gas-required" : "post-failed", { error: error2 instanceof Error ? `${error2.name}: ${error2.message}` : String(error2) });
877
+ throw error2;
878
+ }
879
+ lastResponse = res;
880
+ if (res.status === 200) {
881
+ if (!path3) SCHEDULE_ROUTE.set(node, candidate.replaceAll(pid, PID_SLOT));
882
+ const slot = res.headers["slot"];
883
+ if (push && slot !== void 0 && slot !== null) {
884
+ queuePush({ node, process: pid, slot });
885
+ }
886
+ if (sendObserver && slot !== void 0 && slot !== null && Number.isSafeInteger(Number(slot))) {
887
+ unsettledSends.push({
888
+ node: transportNode(node),
889
+ pid,
890
+ slot: Number(slot),
891
+ timing: timing("accepted-unread", { res, slot }),
892
+ observer: sendObserver
893
+ });
894
+ } else {
895
+ report("accepted-unread", { res, slot });
896
+ }
897
+ return { slot, headers: res.headers };
898
+ }
899
+ tried.push(`${candidate} -> ${res.status} ${hbError(res)}`);
900
+ if (res.status !== 404) break;
901
+ }
902
+ const error = new Error(`send failed on ${node}:
903
+ ${tried.join("\n ")}`);
904
+ error.status = lastResponse?.status ?? null;
905
+ error.refused = isAdmissionRefusal(lastResponse);
906
+ report(
907
+ error.status === 429 ? "rate-limited" : error.refused ? "refused" : error.status === 408 ? "timeout" : "post-failed",
908
+ { res: lastResponse, error: error.message }
909
+ );
910
+ throw error;
911
+ }
912
+ async function pushSlot({ node, process: pid, slot }) {
913
+ let verdict;
914
+ try {
915
+ const base = transportNode(node);
916
+ const delivers = await nodeDeliversOutboxes(base);
917
+ const res = await send(
918
+ node,
919
+ `/${pid}~process@1.0/push&slot=${slot}&max-depth=0`,
920
+ "GET",
921
+ delivers ? { accept: SLOT_RESULT_HEADERS.accept } : {},
922
+ void 0,
923
+ AbortSignal.timeout(PUSH_SOCKET_CAP_MS),
924
+ pushRequestInit()
925
+ );
926
+ verdict = { ...await pushVerdict(base, res.status, res.body.toString(), delivers), status: res.status };
927
+ } catch {
928
+ return false;
929
+ }
930
+ if (verdict.notDelivering) throw new NotDeliveringNodeError({ node, process: pid, slot, status: verdict.status });
931
+ return verdict.delivered ?? verdict.status === 200;
932
+ }
933
+ function queuePush({ node, process: pid, slot }) {
934
+ const key = `${node}|${pid}`;
935
+ const running = PUSHES.get(key) ?? /* @__PURE__ */ new Set();
936
+ PUSHES.set(key, running);
937
+ const push = pushSlot({ node, process: pid, slot }).catch((error) => {
938
+ if (error?.name === "NotDeliveringNodeError" && !NOT_DELIVERING_REPORTED.has(key)) {
939
+ NOT_DELIVERING_REPORTED.add(key);
940
+ console.error(`[hbclient] ${error.message}`);
941
+ }
942
+ return false;
943
+ }).finally(() => {
944
+ running.delete(push);
945
+ if (running.size === 0 && PUSHES.get(key) === running) PUSHES.delete(key);
946
+ });
947
+ running.add(push);
948
+ return push;
949
+ }
950
+ async function pendingPushes({ node, process: pid } = {}) {
951
+ const sets = node && pid ? [PUSHES.get(`${node}|${pid}`)] : [...PUSHES.values()];
952
+ await Promise.all(sets.filter(Boolean).flatMap((running) => [...running]));
953
+ }
954
+ var CRLF, MAX_HEADER_LENGTH, DERIVED_COMPONENTS, b64url, b64urlDec, b64std, sha256, sfStr, sortedKeys, URI_SAFE, IS_ID, byBytes, asBuf, durMs, httpRequests, SCHEDULE_ROUTE, PID_SLOT, sendObserver, sendRoles, unsettledSends, NotDeliveringNodeError, PUSHES, NOT_DELIVERING_REPORTED;
955
+ var init_hbclient = __esm({
956
+ "../../backend/native/hbclient.mjs"() {
957
+ init_deploy_target();
958
+ init_slot_settle();
959
+ init_admission();
960
+ init_gas();
961
+ init_transport_timeouts();
962
+ init_slot_result();
963
+ CRLF = "\r\n";
964
+ MAX_HEADER_LENGTH = 4096;
965
+ DERIVED_COMPONENTS = /* @__PURE__ */ new Set([
966
+ "method",
967
+ "target-uri",
968
+ "authority",
969
+ "scheme",
970
+ "request-target",
971
+ "path",
972
+ "query",
973
+ "query-param"
974
+ ]);
975
+ b64url = (buf) => Buffer.from(buf).toString("base64url");
976
+ b64urlDec = (s) => Buffer.from(s, "base64url");
977
+ b64std = (buf) => Buffer.from(buf).toString("base64");
978
+ sha256 = (b) => crypto2.createHash("sha256").update(b).digest();
979
+ sfStr = (s) => ({ __sf: "string", value: s });
980
+ sortedKeys = (obj) => Object.keys(obj).sort(binCmp);
981
+ URI_SAFE = /^[a-z0-9.\-_/?&]*$/;
982
+ IS_ID = (k) => /^[a-zA-Z0-9_-]{43}$/.test(k);
983
+ byBytes = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
984
+ asBuf = (v) => Buffer.isBuffer(v) ? v : Buffer.from(String(v));
985
+ durMs = (from, to) => Number(to - from) / 1e6;
986
+ httpRequests = 0;
987
+ SCHEDULE_ROUTE = /* @__PURE__ */ new Map();
988
+ PID_SLOT = "{pid}";
989
+ sendObserver = null;
990
+ sendRoles = {};
991
+ unsettledSends = [];
992
+ NotDeliveringNodeError = class extends Error {
993
+ constructor({ node, process: pid, slot, status: status2 }) {
994
+ super(`${transportNode(node)} does not deliver the outbox of ${pid} (push&slot=${slot} answered ${status2}); the node that schedules it delivers it. Push there, or read its published state.`);
995
+ this.name = "NotDeliveringNodeError";
996
+ Object.assign(this, { node, process: pid, slot, status: status2 });
997
+ }
998
+ };
999
+ PUSHES = /* @__PURE__ */ new Map();
1000
+ NOT_DELIVERING_REPORTED = /* @__PURE__ */ new Set();
1001
+ process.on("beforeExit", () => {
1002
+ void pendingPushes();
1003
+ });
1004
+ }
1005
+ });
1006
+
1007
+ // ../paralith-bridge/src/cli.mjs
1008
+ init_hbclient();
1009
+ import crypto3 from "node:crypto";
1010
+ import fs2 from "node:fs";
1011
+ import os from "node:os";
1012
+ import path2 from "node:path";
1013
+ import { createPublicClient, createWalletClient, encodeAbiParameters as encodeAbiParameters2, http, keccak256 as keccak2562, parseAbi, recoverMessageAddress, toBytes as toBytes2 } from "viem";
1014
+ import { privateKeyToAccount } from "viem/accounts";
1015
+ import { base as baseChain } from "viem/chains";
1016
+ import {
1017
+ Connection,
1018
+ Ed25519Program,
1019
+ Keypair,
1020
+ PublicKey,
1021
+ SYSVAR_INSTRUCTIONS_PUBKEY,
1022
+ SystemProgram,
1023
+ Transaction,
1024
+ TransactionInstruction,
1025
+ sendAndConfirmTransaction
1026
+ } from "@solana/web3.js";
1027
+ import { SuiGrpcClient } from "@mysten/sui/grpc";
1028
+ import { Transaction as SuiTransaction } from "@mysten/sui/transactions";
1029
+ import { bcs } from "@mysten/sui/bcs";
1030
+ import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
1031
+
1032
+ // ../hypertoken/src/quantity.mjs
1033
+ var MAX_QUANTITY = 2n ** 53n - 1n;
1034
+ var ID = /^[A-Za-z0-9_-]{43}$/;
1035
+ var isId = (value) => typeof value === "string" && ID.test(value);
1036
+
1037
+ // ../hypertoken/src/root-carrier.mjs
1038
+ import { bls12_381 as bls } from "@noble/curves/bls12-381";
1039
+
1040
+ // ../hypertoken/src/read.mjs
1041
+ var HTML2 = /^\s*<(!doctype|html|head|body)/i;
1042
+ var cleanNode = (url) => String(url ?? "").trim().replace(/\/+$/, "").replace(/^(?!https?:\/\/)/, "https://");
1043
+ function unwrap(value) {
1044
+ for (let depth = 0; depth < 3; depth += 1) {
1045
+ if (value && typeof value === "object" && !Array.isArray(value) && value["ao-result"] === "body") value = value.body;
1046
+ else if (typeof value === "string" && /^\s*[[{]/.test(value)) {
1047
+ try {
1048
+ value = JSON.parse(value);
1049
+ } catch {
1050
+ break;
1051
+ }
1052
+ } else break;
1053
+ }
1054
+ return value;
1055
+ }
1056
+ async function readPublished(node, pid, key, { fetch: f = globalThis.fetch, timeoutMs = 2e4 } = {}) {
1057
+ const url = `${cleanNode(node)}/${pid}~process@1.0/now/${key}`;
1058
+ let res;
1059
+ try {
1060
+ res = await f(url, {
1061
+ headers: { accept: "application/json", "cache-control": "no-cache" },
1062
+ signal: typeof AbortSignal !== "undefined" && AbortSignal.timeout ? AbortSignal.timeout(timeoutMs) : void 0
1063
+ });
1064
+ } catch (error) {
1065
+ return { present: false, error: `unreachable: ${error?.message ?? error}` };
1066
+ }
1067
+ const text = await res.text();
1068
+ if (HTML2.test(text)) return { present: false, status: res.status, text };
1069
+ if (res.status === 404) return { present: false, status: 404, text };
1070
+ if (!res.ok) return { present: false, status: res.status, error: `HTTP ${res.status}`, text };
1071
+ if (text.trim() === "") return { present: false, status: res.status, text };
1072
+ try {
1073
+ return { present: true, status: res.status, text, value: unwrap(JSON.parse(text)) };
1074
+ } catch {
1075
+ return { present: true, status: res.status, text, value: text.trim().replace(/^"+|"+$/g, "") };
1076
+ }
1077
+ }
1078
+
1079
+ // ../hypertoken/src/manifest.mjs
1080
+ var SCHEMA = "hypertoken-manifest/v2";
1081
+ var DOMAIN = `${SCHEMA}
1082
+ `;
1083
+
1084
+ // ../hypertoken/src/ans104.mjs
1085
+ import { ed25519 } from "@noble/curves/ed25519";
1086
+ var utf8 = new TextEncoder();
1087
+
1088
+ // ../hypertoken/src/root-carrier.mjs
1089
+ var utf82 = new TextEncoder();
1090
+
1091
+ // ../hypertoken/src/root-certificate.mjs
1092
+ var fail = (reason) => {
1093
+ throw new Error(`Root certificate: ${reason}`);
1094
+ };
1095
+ var ROOT_ACTIONS = Object.freeze({
1096
+ Transfer: "holder",
1097
+ "Ledger-Enter": "holder",
1098
+ "Bridge-Redeem": "holder",
1099
+ "Ledger-Release": "lane",
1100
+ "Ledger-Register": "lane",
1101
+ "Ledger-Accepts": "lane",
1102
+ "Bridge-Mint": "member",
1103
+ "Ledger-Exit": "member",
1104
+ "Ledger-Move-Root": "member",
1105
+ "Bridge-Released": "member",
1106
+ "Ledger-Credited": "member",
1107
+ "Attestor-Apply": "member"
1108
+ });
1109
+ async function readEndorsement(response) {
1110
+ const limit = 65536;
1111
+ if (Number(response.headers.get("content-length")) > limit || !response.body) fail("oversized or empty endorsement");
1112
+ const reader = response.body.getReader();
1113
+ const chunks = [];
1114
+ let length = 0;
1115
+ try {
1116
+ for (; ; ) {
1117
+ const { done, value } = await reader.read();
1118
+ if (done) break;
1119
+ length += value.length;
1120
+ if (length > limit) {
1121
+ await reader.cancel();
1122
+ fail("oversized endorsement");
1123
+ }
1124
+ if (value.length) chunks.push(value);
1125
+ }
1126
+ } finally {
1127
+ reader.releaseLock();
1128
+ }
1129
+ const bytes = new Uint8Array(length);
1130
+ let offset = 0;
1131
+ for (const chunk of chunks) {
1132
+ bytes.set(chunk, offset);
1133
+ offset += chunk.length;
1134
+ }
1135
+ return JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(bytes));
1136
+ }
1137
+ async function memberNodes(node, aos, nodes, fetcher) {
1138
+ const known = new Map(nodes.filter((n) => isId(n.ao) && n.url).map((n) => [n.ao, cleanNode(n.url)]));
1139
+ return Promise.all(aos.map(async (ao) => {
1140
+ let endpoint = known.get(ao) ?? "";
1141
+ if (!endpoint) {
1142
+ try {
1143
+ const response = await fetcher(
1144
+ `${cleanNode(node)}/~location@1.0/${ao}?variant=ao.N.1`,
1145
+ { headers: { accept: "application/json" }, signal: AbortSignal.timeout(1e4) }
1146
+ );
1147
+ if (response.ok) {
1148
+ const location = await readEndorsement(response);
1149
+ if (typeof location.url === "string") endpoint = cleanNode(location.url);
1150
+ }
1151
+ } catch {
1152
+ }
1153
+ }
1154
+ return { ao, node: endpoint };
1155
+ }));
1156
+ }
1157
+ async function collectChainSignatures({
1158
+ root,
1159
+ node,
1160
+ withdrawal,
1161
+ proposal: proposal2,
1162
+ nodes = [],
1163
+ fetch: fetcher = globalThis.fetch,
1164
+ timeoutMs = 2e4
1165
+ }) {
1166
+ if (withdrawal === void 0 === (proposal2 === void 0)) fail("name one withdrawal or one proposal");
1167
+ const id = String(withdrawal ?? proposal2);
1168
+ if (!/^[1-9][0-9]*$/.test(id)) fail("invalid record id");
1169
+ const read = await readPublished(node, root, "bridgeinfo", { fetch: fetcher });
1170
+ const info = read.present ? read.value : null;
1171
+ if (!Array.isArray(info?.attestors)) fail("root bridge state is unavailable");
1172
+ let members = info.attestors;
1173
+ if (proposal2 !== void 0) {
1174
+ const p = (info.proposals ?? []).find((x) => String(x.id) === id);
1175
+ if (!p || p.status !== "applied" || !Array.isArray(p.prior)) fail("the proposal is not applied");
1176
+ members = p.prior;
1177
+ }
1178
+ const located = await memberNodes(node, members.map((m) => m.ao), nodes, fetcher);
1179
+ const query = withdrawal !== void 0 ? `withdrawal=${id}` : `proposal=${id}`;
1180
+ const answers = await Promise.all(located.map(async ({ ao, node: url }) => {
1181
+ try {
1182
+ const endpoint = new URL(url);
1183
+ if (!["https:", "http:"].includes(endpoint.protocol) || endpoint.username || endpoint.password) return null;
1184
+ endpoint.pathname = endpoint.pathname.replace(/\/+$/, "") + "/~bridge-attestor@1.0/chain-sig";
1185
+ endpoint.search = query;
1186
+ const response = await fetcher(endpoint.href, {
1187
+ headers: { accept: "application/json" },
1188
+ signal: AbortSignal.timeout(timeoutMs)
1189
+ });
1190
+ if (!response.ok) return null;
1191
+ const answer = await readEndorsement(response);
1192
+ return answer?.signer === ao ? [ao, answer] : null;
1193
+ } catch {
1194
+ return null;
1195
+ }
1196
+ }));
1197
+ const ok = answers.filter(Boolean);
1198
+ const isSig = (s) => typeof s === "string" && /^0x[0-9a-fA-F]{2,200}$/.test(s);
1199
+ if (withdrawal !== void 0) {
1200
+ return { sigs: Object.fromEntries(ok.filter(([, a]) => String(a.withdrawal) === id && isSig(a.sig)).map(([ao, a]) => [ao, a.sig])) };
1201
+ }
1202
+ return { votes: Object.fromEntries(ok.filter(([, a]) => String(a.proposal) === id).map(([ao, a]) => [ao, Object.fromEntries(["base", "solana", "sui"].filter((c) => isSig(a[c])).map((c) => [c, a[c]]))])) };
1203
+ }
1204
+
1205
+ // ../paralith-bridge/src/rpc.mjs
1206
+ import fs from "node:fs";
1207
+ import path from "node:path";
1208
+ function solanaRpcRefusal(url) {
1209
+ let host;
1210
+ try {
1211
+ host = new URL(url).hostname.toLowerCase();
1212
+ } catch {
1213
+ return "an RPC that is not a URL";
1214
+ }
1215
+ if (host === "api.mainnet-beta.solana.com") return "the public mainnet endpoint";
1216
+ if (host.includes("helius")) return "a Helius endpoint";
1217
+ return null;
1218
+ }
1219
+ var solanaMainnet = (deployment2) => !/devnet|testnet|localnet/.test(String(deployment2?.solana?.cluster ?? deployment2?.network ?? ""));
1220
+ function rpcFor(chain, { flag, env, keysDir, deployment: deployment2 }) {
1221
+ const given = flag ?? env[`PARALITH_${chain.toUpperCase()}_RPC`];
1222
+ if (chain !== "solana") return given || deployment2[chain].rpc;
1223
+ const file = path.join(keysDir, "solana-rpc.txt");
1224
+ const url = given || (fs.existsSync(file) ? fs.readFileSync(file, "utf8").trim() : "");
1225
+ if (!url) throw new Error(`no private Solana RPC: write it to ${file}, or pass --rpc / PARALITH_SOLANA_RPC`);
1226
+ const why = solanaMainnet(deployment2) ? solanaRpcRefusal(url) : null;
1227
+ if (why) throw new Error(`refusing ${why} as the Solana mainnet RPC (${given ? "--rpc / PARALITH_SOLANA_RPC" : file}): use the private RPC`);
1228
+ return url;
1229
+ }
1230
+
1231
+ // ../paralith-bridge/src/admin-message.mjs
1232
+ import { encodeAbiParameters, keccak256, toBytes } from "viem";
1233
+ var ADMIN_TYPE = "PARALITH_ADMIN_V2";
1234
+ var ALLOW_TOKEN = 1;
1235
+ var UNPAUSE = 2;
1236
+ var ZERO_EVM = "0x0000000000000000000000000000000000000000";
1237
+ function u64(n) {
1238
+ const v = BigInt(n);
1239
+ if (v < 0n || v >= 1n << 64n) throw new Error(`${n} is not a u64`);
1240
+ const b = Buffer.alloc(8);
1241
+ b.writeBigUInt64LE(v);
1242
+ return b;
1243
+ }
1244
+ function bytes32(value, what) {
1245
+ const b = Buffer.from(value);
1246
+ if (b.length !== 32) throw new Error(`${what} must be 32 bytes`);
1247
+ return b;
1248
+ }
1249
+ function action(a) {
1250
+ if (a !== ALLOW_TOKEN && a !== UNPAUSE) throw new Error(`unknown admin action ${a}`);
1251
+ return a;
1252
+ }
1253
+ function rootBytes(id) {
1254
+ return bytes32(Buffer.from(id ?? "", "base64url"), `process id ${id || "<empty>"}`);
1255
+ }
1256
+ function baseAdminInner({ chainId, bridge, root, epoch, nonce, action: a, token, value = true }) {
1257
+ const allow = action(a) === ALLOW_TOKEN;
1258
+ return keccak256(encodeAbiParameters(
1259
+ [
1260
+ { type: "bytes32" },
1261
+ { type: "uint256" },
1262
+ { type: "address" },
1263
+ { type: "bytes32" },
1264
+ { type: "uint64" },
1265
+ { type: "uint64" },
1266
+ { type: "bytes32" },
1267
+ { type: "address" },
1268
+ { type: "bool" }
1269
+ ],
1270
+ [
1271
+ keccak256(toBytes(ADMIN_TYPE)),
1272
+ BigInt(chainId),
1273
+ bridge,
1274
+ `0x${rootBytes(root).toString("hex")}`,
1275
+ BigInt(epoch),
1276
+ u64(nonce).readBigUInt64LE(0),
1277
+ keccak256(toBytes(allow ? "ALLOW_TOKEN" : "UNPAUSE")),
1278
+ allow ? token : ZERO_EVM,
1279
+ value
1280
+ ]
1281
+ ));
1282
+ }
1283
+ function solanaAdminMessage({ program, root, epoch, nonce, action: a, mint, value = true }) {
1284
+ const allow = action(a) === ALLOW_TOKEN;
1285
+ return Buffer.concat([
1286
+ Buffer.from(ADMIN_TYPE),
1287
+ bytes32(program, "program id"),
1288
+ rootBytes(root),
1289
+ u64(epoch),
1290
+ u64(nonce),
1291
+ Buffer.from([a]),
1292
+ allow ? bytes32(mint, "mint") : Buffer.alloc(32),
1293
+ Buffer.from([value ? 1 : 0])
1294
+ ]);
1295
+ }
1296
+ var ATTESTORS_TYPE = "PARALITH_ATTESTORS_V2";
1297
+ function setOf(set) {
1298
+ if (!Array.isArray(set) || set.length < 1 || set.length > 16) throw new Error("an attestor set is 1-16 keys");
1299
+ return set;
1300
+ }
1301
+ function baseAttestorsInner({ chainId, bridge, root, epoch, newEpoch, set }) {
1302
+ setOf(set);
1303
+ return keccak256(encodeAbiParameters(
1304
+ [
1305
+ { type: "bytes32" },
1306
+ { type: "uint256" },
1307
+ { type: "address" },
1308
+ { type: "bytes32" },
1309
+ { type: "uint64" },
1310
+ { type: "uint64" },
1311
+ { type: "address[]" }
1312
+ ],
1313
+ [
1314
+ keccak256(toBytes(ATTESTORS_TYPE)),
1315
+ BigInt(chainId),
1316
+ bridge,
1317
+ `0x${rootBytes(root).toString("hex")}`,
1318
+ u64(epoch).readBigUInt64LE(0),
1319
+ u64(newEpoch).readBigUInt64LE(0),
1320
+ set
1321
+ ]
1322
+ ));
1323
+ }
1324
+ function solanaAttestorsMessage({ program, root, epoch, newEpoch, set }) {
1325
+ const keys = setOf(set).map((k) => bytes32(k, "Solana attestor key"));
1326
+ return Buffer.concat([
1327
+ Buffer.from(ATTESTORS_TYPE),
1328
+ bytes32(program, "program id"),
1329
+ rootBytes(root),
1330
+ u64(epoch),
1331
+ u64(newEpoch),
1332
+ Buffer.from([keys.length]),
1333
+ ...keys
1334
+ ]);
1335
+ }
1336
+
1337
+ // ../paralith-bridge/src/cli.mjs
1338
+ var MANIFEST = "https://bridge.paralithmarkets.com/bridge.json";
1339
+ var HELP = `paralith-bridge <command>
1340
+
1341
+ status the set, open changes, each chain's epoch
1342
+ propose-add <node-url> propose adding a node (its keys are read from the node)
1343
+ propose-remove <node-ao> propose removing one
1344
+ propose-migrate <new-pusd> propose moving the set to a replacement PUSD; every node follows
1345
+ propose-token <base|solana|sui> ask the current majority to admit the recorded TEST token
1346
+ approve <id> approve as operator; once a majority of nodes' operators
1347
+ approve, the nodes apply it at PUSD with one certificate
1348
+ apply <id> collect the prior members' chain signatures from their nodes
1349
+ and carry them to Base, Solana and Sui (pays each chain's gas;
1350
+ --chain base|solana|sui for one)
1351
+ pause stop PUSD minting, redeeming and signing releases (any operator)
1352
+ unpause propose lifting the owner's pause on every chain (--chain one);
1353
+ binds each chain's current admin nonce; majority approves and signs
1354
+
1355
+ Keys are read from ~/.paralith/bridge/ unless a flag names another file:
1356
+ operator.json the operator's Arweave keyfile (--wallet <file>)
1357
+ base.key Base gas payer, 0x-hex private key (--key <file>)
1358
+ solana.json Solana gas payer, keypair JSON array (--key <file>)
1359
+ sui.key Sui gas payer, suiprivkey1... (--key <file>)
1360
+
1361
+ --operator <addr> propose-add: the new node's operator (default: --wallet's address)
1362
+ --rpc <url> apply's RPC (or PARALITH_BASE_RPC / _SOLANA_RPC / _SUI_RPC);
1363
+ Solana otherwise needs a private RPC in solana-rpc.txt
1364
+ --pusd <id> act on this PUSD, not the manifest's (approve on a PUSD being replaced)
1365
+ --manifest <url> the deployment description (default ${MANIFEST})`;
1366
+ var CHAINS = ["base", "solana", "sui"];
1367
+ var argv = process.argv.slice(2);
1368
+ var opt = (name) => {
1369
+ const i = argv.indexOf(`--${name}`);
1370
+ return i >= 0 ? argv[i + 1] : void 0;
1371
+ };
1372
+ var positional = argv.filter((a, i) => !a.startsWith("--") && !argv[i - 1]?.startsWith("--"));
1373
+ var [cmd, target] = positional;
1374
+ var die = (msg) => {
1375
+ console.error(`error: ${msg}`);
1376
+ process.exit(1);
1377
+ };
1378
+ var KEYS = path2.join(os.homedir(), ".paralith", "bridge");
1379
+ var readFile = (file, what) => {
1380
+ try {
1381
+ return fs2.readFileSync(file, "utf8").trim();
1382
+ } catch {
1383
+ die(`no ${what} at ${file}`);
1384
+ }
1385
+ };
1386
+ var threshold = (n) => Math.floor(n / 2) + 1;
1387
+ async function getJson(url) {
1388
+ if (!/^https?:\/\//i.test(url)) {
1389
+ const file = path2.resolve(url);
1390
+ try {
1391
+ return JSON.parse(fs2.readFileSync(file, "utf8"));
1392
+ } catch (error) {
1393
+ throw new Error(`${file}: ${error.message}`);
1394
+ }
1395
+ }
1396
+ const r = await fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(15e3) });
1397
+ const text = await r.text();
1398
+ if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`);
1399
+ if (text.trimStart().startsWith("<")) throw new Error(`${url}: not found`);
1400
+ return JSON.parse(text);
1401
+ }
1402
+ if (!["status", "propose-add", "propose-remove", "propose-migrate", "propose-token", "approve", "apply", "pause", "unpause"].includes(cmd)) {
1403
+ console.log(HELP);
1404
+ process.exit(cmd ? 1 : 0);
1405
+ }
1406
+ var deployment = await getJson(opt("manifest") ?? MANIFEST).catch((e) => die(`manifest: ${e.message}`));
1407
+ var NODE = deployment.node;
1408
+ var PUSD = opt("pusd") ?? deployment.pusd;
1409
+ async function bridgeInfo(pid = PUSD) {
1410
+ let v = await getJson(`${NODE}/${pid}~process@1.0/now/bridgeinfo`);
1411
+ if (v && typeof v === "object" && "body" in v) v = v.body;
1412
+ return typeof v === "string" ? JSON.parse(v) : v;
1413
+ }
1414
+ var proposal = (info, id) => (info.proposals ?? []).find((p) => String(p.id) === String(id)) ?? die(`no proposal #${id}`);
1415
+ function wallet() {
1416
+ const jwk = JSON.parse(readFile(
1417
+ opt("wallet") ?? process.env.PARALITH_AO_WALLET ?? path2.join(KEYS, "operator.json"),
1418
+ "operator wallet (your operator's Arweave keyfile)"
1419
+ ));
1420
+ return { jwk, address: jwkToAddress(jwk) };
1421
+ }
1422
+ async function pusd(tags) {
1423
+ const w = wallet();
1424
+ console.log(`signing as ${w.address}`);
1425
+ const { slot } = await sendMessage({ node: NODE, jwk: w.jwk, process: PUSD, action: tags.Action, tags });
1426
+ for (let i = 0; i < 40; i++) {
1427
+ await new Promise((r) => setTimeout(r, 1500));
1428
+ try {
1429
+ const r = await fetch(
1430
+ `${NODE}/${PUSD}~process@1.0/compute&slot=${slot}/results/output/data`,
1431
+ { headers: { accept: "text/plain", "cache-control": "no-cache" }, signal: AbortSignal.timeout(3e4) }
1432
+ );
1433
+ const body = r.ok ? (await r.text()).trim() : "";
1434
+ if (!body || body.startsWith("<")) continue;
1435
+ const reply = JSON.parse(body);
1436
+ if (reply.error) die(reply.error);
1437
+ return reply;
1438
+ } catch {
1439
+ }
1440
+ }
1441
+ die(`sent (slot ${slot}) but no reply yet; run status before sending again`);
1442
+ }
1443
+ var RELEASE_ROOT = "PARALITH_ROOT_V1";
1444
+ var hexBytes = (h) => toBytes2(h);
1445
+ var u642 = (n) => {
1446
+ const b = Buffer.alloc(8);
1447
+ b.writeBigUInt64LE(BigInt(n));
1448
+ return b;
1449
+ };
1450
+ var utf83 = (s) => Buffer.from(s, "utf8");
1451
+ var processBytes = (id) => {
1452
+ const bytes = Buffer.from(id ?? "", "base64url");
1453
+ if (bytes.length !== 32) die(`process id ${id || "<empty>"} does not decode to 32 bytes`);
1454
+ return bytes;
1455
+ };
1456
+ var processHex = (id) => `0x${processBytes(id).toString("hex")}`;
1457
+ function voters(p) {
1458
+ const v = p.prior.flatMap((member, at) => p.votes?.[member.ao] ? [{ at, member, vote: p.votes[member.ao] }] : []);
1459
+ if (v.length < threshold(p.prior.length)) die(`#${p.id} has ${v.length} of ${threshold(p.prior.length)} members' chain signatures`);
1460
+ return v;
1461
+ }
1462
+ var rpcFor2 = (chain) => rpcFor(chain, { flag: opt("rpc"), env: process.env, keysDir: KEYS, deployment });
1463
+ var KEY_FILE = { base: "base.key", solana: "solana.json", sui: "sui.key" };
1464
+ var keyFor = (chain) => readFile(opt("key") ?? process.env[`PARALITH_${chain.toUpperCase()}_KEY`] ?? path2.join(KEYS, KEY_FILE[chain]), `${chain} gas payer key`);
1465
+ var BASE_ABI = parseAbi([
1466
+ "function setAttestors(address[] set, uint64 newEpoch, bytes[] sigs)",
1467
+ "function setRoot(bytes32 successor, bytes[] sigs)",
1468
+ "function setTokenAllowed(address token, bool allowed, uint64 nonce, bytes[] sigs)",
1469
+ "function unpause(uint64 nonce, bytes[] sigs)",
1470
+ "function adminNonce() view returns (uint64)",
1471
+ "function epoch() view returns (uint64)",
1472
+ "function root() view returns (bytes32)"
1473
+ ]);
1474
+ function baseClients(withKey) {
1475
+ const cfg = deployment.base;
1476
+ const chain = { ...baseChain, id: cfg.chainId, rpcUrls: { default: { http: [rpcFor2("base")] } } };
1477
+ const pub = createPublicClient({ chain, transport: http(rpcFor2("base")) });
1478
+ if (!withKey) return { pub };
1479
+ const account = privateKeyToAccount(keyFor("base"));
1480
+ return { pub, account, wallet: createWalletClient({ account, chain, transport: http(rpcFor2("base")) }) };
1481
+ }
1482
+ var solanaProgram = () => new PublicKey(deployment.solana.programId);
1483
+ var solanaConfig = () => PublicKey.findProgramAddressSync([utf83("config")], solanaProgram())[0];
1484
+ var anchorIx = (name) => crypto3.createHash("sha256").update(`global:${name}`).digest().subarray(0, 8);
1485
+ function ed25519Ix(entries, msg) {
1486
+ const head = 2 + 14 * entries.length;
1487
+ const msgOff = head + 96 * entries.length;
1488
+ const data = Buffer.alloc(msgOff + msg.length);
1489
+ data[0] = entries.length;
1490
+ entries.forEach(({ pubkey, sig }, i) => {
1491
+ const at = head + 96 * i;
1492
+ const e = 2 + 14 * i;
1493
+ [at + 32, 65535, at, 65535, msgOff, msg.length, 65535].forEach((v, k) => data.writeUInt16LE(v, e + 2 * k));
1494
+ data.set(pubkey, at);
1495
+ data.set(sig, at + 32);
1496
+ });
1497
+ data.set(msg, msgOff);
1498
+ return new TransactionInstruction({ programId: Ed25519Program.programId, keys: [], data });
1499
+ }
1500
+ var suiClient = () => new SuiGrpcClient({ network: deployment.sui.network, baseUrl: rpcFor2("sui") });
1501
+ var vecBytes = bcs.vector(bcs.vector(bcs.u8()));
1502
+ var vecU64 = bcs.vector(bcs.u64());
1503
+ var epochOf = {
1504
+ async base() {
1505
+ return Number(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "epoch" }));
1506
+ },
1507
+ async solana() {
1508
+ const info = await new Connection(rpcFor2("solana"), "confirmed").getAccountInfo(solanaConfig());
1509
+ if (!info) throw new Error("config not found");
1510
+ const n = info.data.readUInt32LE(40);
1511
+ return Number(info.data.readBigUInt64LE(44 + 32 * n));
1512
+ },
1513
+ async sui() {
1514
+ const tx = new SuiTransaction();
1515
+ tx.moveCall({ target: `${deployment.sui.package}::para_bridge::epoch`, arguments: [tx.object(deployment.sui.bridge)] });
1516
+ tx.setSender("0x0");
1517
+ const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
1518
+ const bytes = r.commandResults?.[0]?.returnValues?.[0]?.bcs;
1519
+ if (!bytes) throw new Error("epoch read returned nothing");
1520
+ return Number(Buffer.from(bytes).readBigUInt64LE(0));
1521
+ }
1522
+ };
1523
+ var adminNonceOf = {
1524
+ async base() {
1525
+ return Number(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "adminNonce" }));
1526
+ },
1527
+ async solana() {
1528
+ const info = await new Connection(rpcFor2("solana"), "confirmed").getAccountInfo(solanaConfig());
1529
+ if (!info) throw new Error("config not found");
1530
+ const n = info.data.readUInt32LE(40);
1531
+ return Number(info.data.readBigUInt64LE(93 + 32 * n));
1532
+ },
1533
+ async sui() {
1534
+ const tx = new SuiTransaction();
1535
+ tx.moveCall({ target: `${deployment.sui.package}::para_bridge::admin_nonce`, arguments: [tx.object(deployment.sui.bridge)] });
1536
+ tx.setSender("0x0");
1537
+ const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
1538
+ const bytes = r.commandResults?.[0]?.returnValues?.[0]?.bcs;
1539
+ if (!bytes) throw new Error("admin nonce read returned nothing");
1540
+ return Number(Buffer.from(bytes).readBigUInt64LE(0));
1541
+ }
1542
+ };
1543
+ async function adminNonceFor(p, chain) {
1544
+ const nonce = p.admin?.nonces?.[chain];
1545
+ if (!Number.isSafeInteger(nonce) || nonce < 0) die(`#${p.id} binds no admin nonce for ${chain}`);
1546
+ const now = await adminNonceOf[chain]();
1547
+ if (now !== nonce) die(`#${p.id} is for ${chain} admin nonce ${nonce}, but ${chain} is at ${now}; propose it again`);
1548
+ return nonce;
1549
+ }
1550
+ var rootOf = {
1551
+ async base() {
1552
+ return String(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "root" })).toLowerCase();
1553
+ },
1554
+ async solana() {
1555
+ const info = await new Connection(rpcFor2("solana"), "confirmed").getAccountInfo(solanaConfig());
1556
+ if (!info) throw new Error("config not found");
1557
+ const n = info.data.readUInt32LE(40);
1558
+ return `0x${info.data.subarray(52 + 32 * n, 84 + 32 * n).toString("hex")}`;
1559
+ },
1560
+ async sui() {
1561
+ const tx = new SuiTransaction();
1562
+ tx.moveCall({ target: `${deployment.sui.package}::para_bridge::root`, arguments: [tx.object(deployment.sui.bridge)] });
1563
+ tx.setSender("0x0");
1564
+ const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
1565
+ const encoded = Buffer.from(r.commandResults?.[0]?.returnValues?.[0]?.bcs ?? []);
1566
+ if (encoded.length !== 33 || encoded[0] !== 32) throw new Error("root read returned invalid vector<u8>");
1567
+ return `0x${encoded.subarray(1).toString("hex")}`;
1568
+ }
1569
+ };
1570
+ async function requireRoot(chain) {
1571
+ const onChain = await rootOf[chain]();
1572
+ if (onChain !== processHex(PUSD)) die(`${chain} is on root ${onChain}, not ${PUSD} (${processHex(PUSD)}); pass --pusd <its root>`);
1573
+ }
1574
+ var applyOn = {
1575
+ async base(p) {
1576
+ const { pub, wallet: w, account } = baseClients(true);
1577
+ console.log(`paying as ${account.address}`);
1578
+ const set = p.set.map((m) => m.base);
1579
+ const epoch = BigInt(p.epoch);
1580
+ await requireRoot("base");
1581
+ const inner = baseAttestorsInner({
1582
+ chainId: deployment.base.chainId,
1583
+ bridge: deployment.base.bridge,
1584
+ root: PUSD,
1585
+ epoch: p.priorEpoch ?? p.currentEpoch,
1586
+ newEpoch: p.epoch,
1587
+ set
1588
+ });
1589
+ const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1590
+ const rows = await Promise.all(voters(p).map(async (v) => ({
1591
+ sig: v.vote.base,
1592
+ who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1593
+ })));
1594
+ const sigs = rows.filter((r2) => allowed.has(r2.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((r2) => r2.sig);
1595
+ const hash = await w.writeContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "setAttestors", args: [set, epoch, sigs] });
1596
+ const r = await pub.waitForTransactionReceipt({ hash });
1597
+ if (r.status !== "success") die(`reverted ${hash}`);
1598
+ return hash;
1599
+ },
1600
+ async solana(p) {
1601
+ const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1602
+ console.log(`paying as ${payer.publicKey.toBase58()}`);
1603
+ const program = solanaProgram();
1604
+ const set = p.set.map((m) => new PublicKey(m.solana));
1605
+ await requireRoot("solana");
1606
+ const msg = solanaAttestorsMessage({
1607
+ program: program.toBuffer(),
1608
+ root: PUSD,
1609
+ epoch: p.priorEpoch ?? p.currentEpoch,
1610
+ newEpoch: p.epoch,
1611
+ set: set.map((k) => k.toBuffer())
1612
+ });
1613
+ const len = Buffer.alloc(4);
1614
+ len.writeUInt32LE(set.length);
1615
+ const tx = new Transaction().add(
1616
+ ed25519Ix(voters(p).map((v) => ({ pubkey: new PublicKey(v.member.solana).toBytes(), sig: hexBytes(v.vote.solana) })), msg),
1617
+ new TransactionInstruction({
1618
+ programId: program,
1619
+ keys: [
1620
+ { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1621
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1622
+ ],
1623
+ data: Buffer.concat([anchorIx("set_attestors"), len, ...set.map((k) => k.toBuffer()), u642(p.epoch)])
1624
+ })
1625
+ );
1626
+ return sendAndConfirmTransaction(new Connection(rpcFor2("solana"), "confirmed"), tx, [payer], { commitment: "confirmed" });
1627
+ },
1628
+ async sui(p) {
1629
+ const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1630
+ console.log(`paying as ${signer.getPublicKey().toSuiAddress()}`);
1631
+ const v = voters(p);
1632
+ const tx = new SuiTransaction();
1633
+ tx.moveCall({
1634
+ target: `${deployment.sui.package}::para_bridge::set_attestors`,
1635
+ arguments: [
1636
+ tx.object(deployment.sui.bridge),
1637
+ tx.pure(vecBytes.serialize(p.set.map((m) => Array.from(hexBytes(m.sui))))),
1638
+ tx.pure.u64(BigInt(p.epoch)),
1639
+ tx.pure(vecU64.serialize(v.map((x) => BigInt(x.at)))),
1640
+ tx.pure(vecBytes.serialize(v.map((x) => Array.from(hexBytes(x.vote.sui)))))
1641
+ ]
1642
+ });
1643
+ const client = suiClient();
1644
+ const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1645
+ const t = r.Transaction ?? r.FailedTransaction;
1646
+ if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1647
+ await client.waitForTransaction({ digest: t.digest });
1648
+ return t.digest;
1649
+ }
1650
+ };
1651
+ var applyRootOn = {
1652
+ async base(p) {
1653
+ const { pub, wallet: w, account } = baseClients(true);
1654
+ console.log(`paying as ${account.address}`);
1655
+ const oldRoot = processHex(PUSD);
1656
+ const successor = processHex(p.successor);
1657
+ const inner = keccak2562(encodeAbiParameters2(
1658
+ [
1659
+ { type: "bytes32" },
1660
+ { type: "uint256" },
1661
+ { type: "address" },
1662
+ { type: "uint64" },
1663
+ { type: "bytes32" },
1664
+ { type: "bytes32" }
1665
+ ],
1666
+ [
1667
+ keccak2562(toBytes2(RELEASE_ROOT)),
1668
+ BigInt(deployment.base.chainId),
1669
+ deployment.base.bridge,
1670
+ BigInt(p.currentEpoch ?? p.priorEpoch),
1671
+ oldRoot,
1672
+ successor
1673
+ ]
1674
+ ));
1675
+ const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1676
+ const rows = await Promise.all(voters(p).map(async (v) => ({
1677
+ sig: v.vote.base,
1678
+ who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1679
+ })));
1680
+ const sigs = rows.filter((row) => allowed.has(row.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((row) => row.sig);
1681
+ const hash = await w.writeContract({
1682
+ address: deployment.base.bridge,
1683
+ abi: BASE_ABI,
1684
+ functionName: "setRoot",
1685
+ args: [successor, sigs]
1686
+ });
1687
+ const receipt = await pub.waitForTransactionReceipt({ hash });
1688
+ if (receipt.status !== "success") die(`reverted ${hash}`);
1689
+ return hash;
1690
+ },
1691
+ async solana(p) {
1692
+ const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1693
+ const program = solanaProgram();
1694
+ const oldRoot = processBytes(PUSD);
1695
+ const successor = processBytes(p.successor);
1696
+ const msg = Buffer.concat([
1697
+ utf83(RELEASE_ROOT),
1698
+ program.toBuffer(),
1699
+ u642(p.currentEpoch ?? p.priorEpoch),
1700
+ oldRoot,
1701
+ successor
1702
+ ]);
1703
+ const tx = new Transaction().add(
1704
+ ed25519Ix(voters(p).map((v) => ({ pubkey: new PublicKey(v.member.solana).toBytes(), sig: hexBytes(v.vote.solana) })), msg),
1705
+ new TransactionInstruction({
1706
+ programId: program,
1707
+ keys: [
1708
+ { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1709
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1710
+ ],
1711
+ data: Buffer.concat([anchorIx("set_root"), successor])
1712
+ })
1713
+ );
1714
+ return sendAndConfirmTransaction(new Connection(rpcFor2("solana"), "confirmed"), tx, [payer], { commitment: "confirmed" });
1715
+ },
1716
+ async sui(p) {
1717
+ const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1718
+ const v = voters(p);
1719
+ const tx = new SuiTransaction();
1720
+ tx.moveCall({
1721
+ target: `${deployment.sui.package}::para_bridge::set_root`,
1722
+ arguments: [
1723
+ tx.object(deployment.sui.bridge),
1724
+ tx.pure(bcs.vector(bcs.u8()).serialize(Array.from(processBytes(p.successor)))),
1725
+ tx.pure(vecU64.serialize(v.map((x) => BigInt(x.at)))),
1726
+ tx.pure(vecBytes.serialize(v.map((x) => Array.from(hexBytes(x.vote.sui)))))
1727
+ ]
1728
+ });
1729
+ const client = suiClient();
1730
+ const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1731
+ const t = r.Transaction ?? r.FailedTransaction;
1732
+ if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1733
+ await client.waitForTransaction({ digest: t.digest });
1734
+ return t.digest;
1735
+ }
1736
+ };
1737
+ var adminVoters = (p, chain) => voters(p).filter((row) => row.vote?.[chain]);
1738
+ var applyAdminOn = {
1739
+ async base(p) {
1740
+ const { pub, wallet: w, account } = baseClients(true);
1741
+ console.log(`paying as ${account.address}`);
1742
+ const allow = p.op === "add-token";
1743
+ const token = allow ? p.admin.token : void 0;
1744
+ const nonce = await adminNonceFor(p, "base");
1745
+ const inner = baseAdminInner({
1746
+ chainId: deployment.base.chainId,
1747
+ bridge: deployment.base.bridge,
1748
+ root: PUSD,
1749
+ epoch: p.currentEpoch ?? p.priorEpoch,
1750
+ nonce,
1751
+ action: allow ? ALLOW_TOKEN : UNPAUSE,
1752
+ token
1753
+ });
1754
+ const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1755
+ const rows = await Promise.all(adminVoters(p, "base").map(async (v) => ({
1756
+ sig: v.vote.base,
1757
+ who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1758
+ })));
1759
+ const sigs = rows.filter((row) => allowed.has(row.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((row) => row.sig);
1760
+ const hash = allow ? await w.writeContract({
1761
+ address: deployment.base.bridge,
1762
+ abi: BASE_ABI,
1763
+ functionName: "setTokenAllowed",
1764
+ args: [token, true, BigInt(nonce), sigs]
1765
+ }) : await w.writeContract({
1766
+ address: deployment.base.bridge,
1767
+ abi: BASE_ABI,
1768
+ functionName: "unpause",
1769
+ args: [BigInt(nonce), sigs]
1770
+ });
1771
+ const receipt = await pub.waitForTransactionReceipt({ hash });
1772
+ if (receipt.status !== "success") die(`reverted ${hash}`);
1773
+ return hash;
1774
+ },
1775
+ async solana(p) {
1776
+ const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1777
+ const program = solanaProgram();
1778
+ const allow = p.op === "add-token";
1779
+ const mint = allow ? new PublicKey(p.admin.token) : new PublicKey(new Uint8Array(32));
1780
+ const nonce = await adminNonceFor(p, "solana");
1781
+ const msg = solanaAdminMessage({
1782
+ program: program.toBuffer(),
1783
+ root: PUSD,
1784
+ epoch: p.currentEpoch ?? p.priorEpoch,
1785
+ nonce,
1786
+ action: allow ? ALLOW_TOKEN : UNPAUSE,
1787
+ mint: mint.toBuffer()
1788
+ });
1789
+ const precompile = ed25519Ix(adminVoters(p, "solana").map((v) => ({
1790
+ pubkey: new PublicKey(v.member.solana).toBytes(),
1791
+ sig: hexBytes(v.vote.solana)
1792
+ })), msg);
1793
+ let instruction;
1794
+ if (allow) {
1795
+ const token = (deployment.solana.tokens ?? []).find((row) => row.mint === p.admin.token);
1796
+ if (!token) die(`Solana token ${p.admin.token} is absent from the deployment record`);
1797
+ const tokenProgram = new PublicKey(token.tokenProgram);
1798
+ instruction = new TransactionInstruction({
1799
+ programId: program,
1800
+ keys: [
1801
+ { pubkey: payer.publicKey, isSigner: true, isWritable: true },
1802
+ { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1803
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },
1804
+ { pubkey: mint, isSigner: false, isWritable: false },
1805
+ { pubkey: PublicKey.findProgramAddressSync([utf83("vault"), mint.toBuffer()], program)[0], isSigner: false, isWritable: true },
1806
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
1807
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
1808
+ ],
1809
+ data: Buffer.concat([anchorIx("allow_token"), u642(nonce)])
1810
+ });
1811
+ } else {
1812
+ instruction = new TransactionInstruction({
1813
+ programId: program,
1814
+ keys: [
1815
+ { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1816
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1817
+ ],
1818
+ data: Buffer.concat([anchorIx("unpause"), u642(nonce)])
1819
+ });
1820
+ }
1821
+ return sendAndConfirmTransaction(
1822
+ new Connection(rpcFor2("solana"), "confirmed"),
1823
+ new Transaction().add(precompile, instruction),
1824
+ [payer],
1825
+ { commitment: "confirmed" }
1826
+ );
1827
+ },
1828
+ async sui(p) {
1829
+ const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1830
+ const rows = adminVoters(p, "sui");
1831
+ const nonce = await adminNonceFor(p, "sui");
1832
+ const tx = new SuiTransaction();
1833
+ if (p.op === "add-token") {
1834
+ tx.moveCall({
1835
+ target: `${deployment.sui.package}::para_bridge::allow_token`,
1836
+ typeArguments: [p.admin.token],
1837
+ arguments: [
1838
+ tx.object(deployment.sui.bridge),
1839
+ tx.pure.u64(nonce),
1840
+ tx.pure(vecU64.serialize(rows.map((x) => BigInt(x.at)))),
1841
+ tx.pure(vecBytes.serialize(rows.map((x) => Array.from(hexBytes(x.vote.sui)))))
1842
+ ]
1843
+ });
1844
+ } else {
1845
+ tx.moveCall({
1846
+ target: `${deployment.sui.package}::para_bridge::unpause`,
1847
+ arguments: [
1848
+ tx.object(deployment.sui.bridge),
1849
+ tx.pure.u64(nonce),
1850
+ tx.pure(vecU64.serialize(rows.map((x) => BigInt(x.at)))),
1851
+ tx.pure(vecBytes.serialize(rows.map((x) => Array.from(hexBytes(x.vote.sui)))))
1852
+ ]
1853
+ });
1854
+ }
1855
+ const client = suiClient();
1856
+ const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1857
+ const t = r.Transaction ?? r.FailedTransaction;
1858
+ if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1859
+ await client.waitForTransaction({ digest: t.digest });
1860
+ return t.digest;
1861
+ }
1862
+ };
1863
+ var short = (s = "") => s.length > 18 ? `${s.slice(0, 8)}\u2026${s.slice(-6)}` : s;
1864
+ async function status() {
1865
+ const info = await bridgeInfo();
1866
+ const set = info.attestors ?? [];
1867
+ console.log(`PUSD ${PUSD} on ${NODE}`);
1868
+ if (info.predecessor) console.log(`replaces ${info.predecessor}`);
1869
+ if (info.pausedBy) console.log(`PAUSED by ${info.pausedBy}`);
1870
+ if (info.successor) console.log(`MOVED to ${info.successor}: the set and every node follow it there`);
1871
+ console.log(`set: ${set.length} node(s), k ${threshold(set.length)}, epoch ${info.epoch ?? 0}`);
1872
+ for (const m of set) console.log(` ${m.ao} operator ${m.operator ?? "-"}`);
1873
+ const epochs = await Promise.all(CHAINS.map((c) => epochOf[c]().catch((e) => `? (${e.message})`)));
1874
+ console.log(`chains: ${CHAINS.map((c, i) => `${c} ${epochs[i]}`).join(", ")}`);
1875
+ for (const p of info.proposals ?? []) {
1876
+ if (p.status === "superseded") continue;
1877
+ const need = threshold(p.prior.length);
1878
+ const behind = CHAINS.filter((c, i) => typeof epochs[i] === "number" && epochs[i] < p.epoch);
1879
+ if (p.status === "applied" && !behind.length) continue;
1880
+ console.log(`#${p.id} ${p.op} ${p.op === "migrate" ? `to ${p.successor}` : `${short(p.member?.ao)} -> epoch ${p.epoch}`}: ${p.status}, approved ${Object.keys(p.approvals ?? {}).length}/${need}` + (p.status === "applied" ? `, apply on: ${behind.join(" ")}` : ""));
1881
+ }
1882
+ }
1883
+ async function main() {
1884
+ if (cmd === "status") return status();
1885
+ if (cmd === "propose-add") {
1886
+ if (!target) die("propose-add <node-url>");
1887
+ const url = target.replace(/\/+$/, "").replace(/^(?!https?:\/\/)/, "https://");
1888
+ const k = await getJson(`${url}/~bridge-attestor@1.0/keys`);
1889
+ if (!k.ao || !k.base || !k.solana || !k.sui) die(`${url} published incomplete keys`);
1890
+ const operator = opt("operator") ?? wallet().address;
1891
+ console.log(`node ${k.ao}
1892
+ base ${k.base}
1893
+ solana ${k.solana}
1894
+ sui ${k.sui}
1895
+ operator ${operator}`);
1896
+ const r = await pusd({ Action: "Attestor-Propose", Op: "add", Ao: k.ao, Base: k.base, Solana: k.solana, Sui: k.sui, Operator: operator });
1897
+ return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
1898
+ }
1899
+ if (cmd === "propose-remove") {
1900
+ if (!target) die("propose-remove <node-ao>");
1901
+ const r = await pusd({ Action: "Attestor-Propose", Op: "remove", Ao: target });
1902
+ return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
1903
+ }
1904
+ if (cmd === "propose-migrate") {
1905
+ if (!target) die("propose-migrate <new-pusd>");
1906
+ const next = await bridgeInfo(target);
1907
+ if (!next.predecessor) die(`${target} names no predecessor`);
1908
+ PUSD = next.predecessor;
1909
+ const here = await bridgeInfo();
1910
+ const members = (i) => JSON.stringify((i.attestors ?? []).map((m) => [m.ao, m.base, m.solana, m.sui]));
1911
+ if (members(next) !== members(here) || Number(next.epoch) !== Number(here.epoch)) {
1912
+ die(`${target} does not hold ${PUSD}'s set at epoch ${here.epoch}; nodes would refuse to follow it`);
1913
+ }
1914
+ console.log(`moving the set of ${PUSD}
1915
+ to ${target}`);
1916
+ const r = await pusd({ Action: "Attestor-Propose", Op: "migrate", Successor: target });
1917
+ return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"} --pusd ${PUSD}`);
1918
+ }
1919
+ if (cmd === "approve") {
1920
+ if (!target) die("approve <id>");
1921
+ await pusd({ Action: "Attestor-Approve", ProposalId: String(target) });
1922
+ return console.log(`approved #${target}; your nodes vote on their next pass`);
1923
+ }
1924
+ if (cmd === "pause") {
1925
+ await pusd({ Action: "Bridge-Pause" });
1926
+ return console.log("paused");
1927
+ }
1928
+ if (cmd === "propose-token") {
1929
+ if (!CHAINS.includes(target)) die("propose-token <base|solana|sui>");
1930
+ const rows = deployment[target].tokens ?? [];
1931
+ const token = rows.find((row) => !row.retired);
1932
+ const id = target === "base" ? token?.address : target === "solana" ? token?.mint : token?.type;
1933
+ if (!id) die(`manifest has no active ${target} token`);
1934
+ const nonce = await adminNonceOf[target]();
1935
+ const r = await pusd({
1936
+ Action: "Attestor-Propose",
1937
+ Op: "add-token",
1938
+ Chain: target,
1939
+ Token: id,
1940
+ Symbol: token.symbol,
1941
+ Decimals: String(token.decimals),
1942
+ AdminNonce: String(nonce)
1943
+ });
1944
+ return console.log(`proposed #${r.ProposalId ?? "?"} for ${target} ${id}; next: approve ${r.ProposalId ?? "<id>"}`);
1945
+ }
1946
+ if (cmd === "unpause") {
1947
+ const chain = opt("chain");
1948
+ if (chain && !CHAINS.includes(chain)) die("unpause [--chain base|solana|sui]");
1949
+ const tags = { Action: "Attestor-Propose", Op: "unpause" };
1950
+ const TAG = { base: "BaseAdminNonce", solana: "SolanaAdminNonce", sui: "SuiAdminNonce" };
1951
+ for (const c of chain ? [chain] : CHAINS) tags[TAG[c]] = String(await adminNonceOf[c]());
1952
+ const r = await pusd(tags);
1953
+ return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
1954
+ }
1955
+ if (cmd === "apply") {
1956
+ const chain = opt("chain");
1957
+ if (!target || chain && !CHAINS.includes(chain)) die("apply <id> [--chain base|solana|sui]");
1958
+ const p = proposal(await bridgeInfo(), target);
1959
+ if (p.status !== "applied") die(`#${p.id} is ${p.status}; its operators approve it and the nodes apply it first`);
1960
+ p.votes = (await collectChainSignatures({ root: PUSD, node: NODE, proposal: p.id })).votes;
1961
+ if (p.op === "migrate") {
1962
+ const oldRoot = processHex(PUSD).toLowerCase();
1963
+ const successor = processHex(p.successor).toLowerCase();
1964
+ for (const c of chain ? [chain] : CHAINS) {
1965
+ const current = await rootOf[c]();
1966
+ if (current === successor) {
1967
+ console.log(`${c}: already points to ${p.successor}`);
1968
+ continue;
1969
+ }
1970
+ if (current !== oldRoot) die(`${c} points to ${current}, not ${PUSD}`);
1971
+ console.log(`${c}: root ${p.successor}, ${await applyRootOn[c](p)}`);
1972
+ }
1973
+ return;
1974
+ }
1975
+ if (p.kind === "admin") {
1976
+ if (!["add-token", "unpause"].includes(p.op)) {
1977
+ console.log(`#${p.id} ${p.op} is AO-only and needs no chain application`);
1978
+ return;
1979
+ }
1980
+ const targets = p.op === "add-token" ? [p.admin.chain] : chain ? [chain] : CHAINS;
1981
+ if (chain && p.op === "add-token" && chain !== p.admin.chain) {
1982
+ die(`#${p.id} adds a token on ${p.admin.chain}, not ${chain}`);
1983
+ }
1984
+ for (const c of targets) console.log(`${c}: ${p.op}, ${await applyAdminOn[c](p)}`);
1985
+ return;
1986
+ }
1987
+ for (const c of chain ? [chain] : CHAINS) {
1988
+ const now = await epochOf[c]();
1989
+ if (now >= p.epoch) {
1990
+ console.log(`${c}: already at epoch ${now}`);
1991
+ continue;
1992
+ }
1993
+ if (now !== p.epoch - 1) die(`${c} is at epoch ${now}; apply the change to epoch ${now + 1} first`);
1994
+ console.log(`${c}: epoch ${p.epoch}, ${await applyOn[c](p)}`);
1995
+ }
1996
+ return;
1997
+ }
1998
+ }
1999
+ await main().catch((e) => die(e.shortMessage ?? e.message ?? String(e)));