paralith-mcp 0.4.7 → 0.4.9

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
@@ -14,6 +14,7 @@ import {
14
14
  Keypair,
15
15
  PublicKey,
16
16
  SYSVAR_INSTRUCTIONS_PUBKEY,
17
+ SystemProgram,
17
18
  Transaction,
18
19
  TransactionInstruction,
19
20
  sendAndConfirmTransaction
@@ -25,6 +26,83 @@ import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519";
25
26
 
26
27
  // ../../backend/native/hbclient.mjs
27
28
  import crypto from "node:crypto";
29
+
30
+ // ../rune-ao/src/lib/admission.mjs
31
+ var ADMISSION_HEADER = "hb-admission";
32
+ var ADMISSION_BACKOFF = Object.freeze({ baseMs: 1e3, capMs: 8e3 });
33
+ var ADMISSION_BUDGET_MS = 3e4;
34
+ function header(headers, name) {
35
+ if (!headers) return null;
36
+ if (typeof headers.get === "function") return headers.get(name);
37
+ return headers[name] ?? null;
38
+ }
39
+ function isAdmissionRefusal(res) {
40
+ return res?.status === 503 && String(header(res.headers, ADMISSION_HEADER) ?? "").trim() === "busy";
41
+ }
42
+ function retryAfterMs(value, now = Date.now()) {
43
+ const text = String(value ?? "").trim();
44
+ if (/^\d+$/.test(text)) return Number(text) * 1e3;
45
+ const at = Date.parse(text);
46
+ return Number.isFinite(at) ? Math.max(0, at - now) : 1e3;
47
+ }
48
+ function admissionDelayMs(attempt, retryAfter, random = Math.random) {
49
+ const exp = Math.min(ADMISSION_BACKOFF.capMs, ADMISSION_BACKOFF.baseMs * 2 ** attempt);
50
+ const wait = Math.max(retryAfter, exp);
51
+ return Math.round(wait + random() * wait / 2);
52
+ }
53
+ var pause = (ms, signal) => new Promise((resolve, reject) => {
54
+ if (signal?.aborted) {
55
+ reject(signal.reason);
56
+ return;
57
+ }
58
+ const timer = setTimeout(() => {
59
+ signal?.removeEventListener?.("abort", onAbort);
60
+ resolve();
61
+ }, ms);
62
+ const onAbort = () => {
63
+ clearTimeout(timer);
64
+ reject(signal.reason);
65
+ };
66
+ signal?.addEventListener?.("abort", onAbort, { once: true });
67
+ });
68
+ async function postAdmitted(post, {
69
+ budgetMs = ADMISSION_BUDGET_MS,
70
+ signal,
71
+ onRefused,
72
+ random = Math.random,
73
+ now = Date.now,
74
+ sleep = pause
75
+ } = {}) {
76
+ const started = now();
77
+ for (let attempt = 0; ; attempt += 1) {
78
+ const res = await post();
79
+ if (!isAdmissionRefusal(res)) return res;
80
+ try {
81
+ onRefused?.();
82
+ } catch {
83
+ }
84
+ const wait = admissionDelayMs(attempt, retryAfterMs(header(res.headers, "retry-after"), now()), random);
85
+ if (now() - started + wait > budgetMs) return res;
86
+ try {
87
+ await res.arrayBuffer?.();
88
+ } catch {
89
+ }
90
+ try {
91
+ await sleep(wait, signal);
92
+ } catch (reason) {
93
+ throw new AdmissionWaitAborted(reason);
94
+ }
95
+ }
96
+ }
97
+ var AdmissionWaitAborted = class extends Error {
98
+ constructor(reason) {
99
+ super("The write was aborted while the node was refusing it; nothing was accepted.");
100
+ this.name = "AbortError";
101
+ this.cause = reason;
102
+ }
103
+ };
104
+
105
+ // ../../backend/native/hbclient.mjs
28
106
  var CRLF = "\r\n";
29
107
  var MAX_HEADER_LENGTH = 4096;
30
108
  var DERIVED_COMPONENTS = /* @__PURE__ */ new Set([
@@ -127,15 +205,32 @@ function toTabm(value) {
127
205
  }
128
206
  return Buffer.from(String(value), "utf8");
129
207
  }
208
+ var byBytes = (a, b) => Buffer.compare(Buffer.from(a), Buffer.from(b));
130
209
  function encodeAoTypes(types) {
131
- return sfDict(sortedKeys(types).map((k) => [escapeKey(k), sfString(types[k])]));
210
+ const groups = /* @__PURE__ */ new Map();
211
+ for (const key of Object.keys(types).sort(byBytes)) {
212
+ const type = types[key];
213
+ if (!groups.has(type)) groups.set(type, []);
214
+ groups.get(type).push(key);
215
+ }
216
+ return [...groups.keys()].sort(byBytes).map(
217
+ (type) => type + "=(" + groups.get(type).map(
218
+ (key) => /^[ -~]*$/.test(key) ? sfString(key) : ":" + b64std(Buffer.from(key)) + ":"
219
+ ).join(" ") + ")"
220
+ ).join(", ");
132
221
  }
133
222
  function parseAoTypes(bin) {
134
223
  if (!bin) return {};
135
224
  const s = Buffer.isBuffer(bin) ? bin.toString("utf8") : String(bin);
136
225
  const out = {};
226
+ for (const m of s.matchAll(/([a-z0-9*_.-]+)=\(([^)]*)\)/g)) {
227
+ for (const k of m[2].matchAll(/"((?:[^"\\]|\\.)*)"|:([A-Za-z0-9+/=]*):/g)) {
228
+ const key = k[1] !== void 0 ? k[1].replace(/\\(.)/g, "$1") : Buffer.from(k[2], "base64").toString("utf8");
229
+ out[key] = m[1];
230
+ }
231
+ }
137
232
  for (const part of s.split(",")) {
138
- const m = part.trim().match(/^([^=]+)="([^"]*)"$/);
233
+ const m = part.trim().match(/^([^=(]+)="([^"]*)"$/);
139
234
  if (m) out[m[1]] = m[2];
140
235
  }
141
236
  return out;
@@ -286,7 +381,7 @@ function signatureBase(encHeaders, committed, params) {
286
381
  );
287
382
  return Buffer.from(lines.join("\n") + '\n"@signature-params": ' + paramsLine, "utf8");
288
383
  }
289
- function commitmentParams({ alg, bundle, created, expires, keyid, nonce, tag }) {
384
+ function commitmentParams({ alg, bundle, created, expires, keyid, nonce, tag, publicKey }) {
290
385
  const out = [];
291
386
  if (alg !== void 0) out.push(["alg", sfStr(alg)]);
292
387
  if (bundle !== void 0) out.push(["bundle", sfStr(bundle)]);
@@ -294,9 +389,19 @@ function commitmentParams({ alg, bundle, created, expires, keyid, nonce, tag })
294
389
  if (expires !== void 0) out.push(["expires", expires]);
295
390
  if (keyid !== void 0) out.push(["keyid", sfStr(keyid)]);
296
391
  if (nonce !== void 0) out.push(["nonce", sfStr(nonce)]);
392
+ if (publicKey !== void 0) out.push(["public-key", sfStr(publicKey)]);
297
393
  if (tag !== void 0) out.push(["tag", sfStr(tag)]);
298
394
  return out;
299
395
  }
396
+ function committerUri(address) {
397
+ const lower = address.toLowerCase().replace(/_/g, "-");
398
+ let mask = 0n;
399
+ for (const c of address) mask = mask << 1n | (c >= "A" && c <= "Z" || c === "_" ? 1n : 0n);
400
+ return "uri-did-ar-" + lower + (mask << 3n).toString(36).padStart(9, "0");
401
+ }
402
+ function keyParams(jwk) {
403
+ return { keyid: committerUri(jwkToAddress(jwk)), publicKey: b64url(pubKeyBuf(jwk)) };
404
+ }
300
405
  function jwkToPrivateKey(jwk) {
301
406
  return crypto.createPrivateKey({ key: { ...jwk, kty: "RSA" }, format: "jwk" });
302
407
  }
@@ -378,15 +483,14 @@ function withNestedHmacs(tabm) {
378
483
  }
379
484
  var durMs = (from, to) => Number(to - from) / 1e6;
380
485
  function commit(msg, jwk, opts = {}) {
381
- const { bundle = "true", nestedHmacs = true, ...params0 } = opts;
486
+ const { bundle = "true", nestedHmacs = false, ...params0 } = opts;
382
487
  const tEncode = process.hrtime.bigint();
383
488
  const tabm = nestedHmacs ? withNestedHmacs(toTabm(msg)) : toTabm(msg);
384
489
  const { headers, body } = tabmToHttp(tabm);
385
490
  const committed = sortedKeys(headers).filter(
386
491
  (k) => k !== "signature" && k !== "signature-input"
387
492
  );
388
- const keyid = "publickey:" + b64std(pubKeyBuf(jwk));
389
- const params = commitmentParams({ alg: "rsa-pss-sha512", bundle, keyid, ...params0 });
493
+ const params = commitmentParams({ alg: "rsa-pss-sha512", bundle, ...keyParams(jwk), ...params0 });
390
494
  const base = signatureBase(headers, committed, params);
391
495
  const tSign = process.hrtime.bigint();
392
496
  const sig = rsaPssSign(jwk, base);
@@ -441,13 +545,20 @@ function hbError(res) {
441
545
  async function postSigned(node, path2, msg, jwk, opts = {}) {
442
546
  const { headers, body, signatureBase: base, committed, timing } = commit(msg, jwk, opts);
443
547
  const tPost = process.hrtime.bigint();
444
- const res = await send(node, path2, "POST", headers, body);
548
+ let refusals = 0;
549
+ const res = await postAdmitted(
550
+ () => send(node, path2, "POST", headers, body),
551
+ { onRefused: () => {
552
+ refusals += 1;
553
+ } }
554
+ );
445
555
  const postMs = durMs(tPost, process.hrtime.bigint());
446
556
  res.request = { headers, body, base, committed };
447
- res.timing = { ...timing, postMs, bytes: body ? body.length : 0 };
557
+ res.timing = { ...timing, postMs, bytes: body ? body.length : 0, ...refusals ? { refusals } : {} };
448
558
  return res;
449
559
  }
450
560
  var SCHEDULE_ROUTE = /* @__PURE__ */ new Map();
561
+ var PID_SLOT = "{pid}";
451
562
  var sendObserver = null;
452
563
  var sendRoles = {};
453
564
  var unsettledSends = [];
@@ -503,6 +614,7 @@ async function sendMessage({
503
614
  postMs: t ? t.postMs : 0,
504
615
  sendMs: durMs(started, process.hrtime.bigint()),
505
616
  bytes: t ? t.bytes : 0,
617
+ ...t?.refusals ? { refusals: t.refusals } : {},
506
618
  // As in `TransportTiming`: a reply was read, which a refusal also is.
507
619
  ok: outcome === "ok" || outcome === "rejected",
508
620
  outcome,
@@ -513,7 +625,7 @@ async function sendMessage({
513
625
  if (sendObserver) observeSend(timing(outcome, detail));
514
626
  };
515
627
  const candidates = path2 ? [path2] : [`/${pid}~process@1.0/schedule`, `/${pid}~scheduler@1.0/schedule`, `/${pid}/schedule`];
516
- const known = SCHEDULE_ROUTE.get(node);
628
+ const known = SCHEDULE_ROUTE.get(node)?.replaceAll(PID_SLOT, pid);
517
629
  const ordered = known && !path2 ? [known, ...candidates.filter((p) => p !== known)] : candidates;
518
630
  const tried = [];
519
631
  let lastResponse = null;
@@ -527,7 +639,7 @@ async function sendMessage({
527
639
  }
528
640
  lastResponse = res;
529
641
  if (res.status === 200) {
530
- if (!path2) SCHEDULE_ROUTE.set(node, candidate);
642
+ if (!path2) SCHEDULE_ROUTE.set(node, candidate.replaceAll(pid, PID_SLOT));
531
643
  const slot = res.headers["slot"];
532
644
  if (push && slot !== void 0 && slot !== null) {
533
645
  queuePush({ node, process: pid, slot });
@@ -551,8 +663,9 @@ async function sendMessage({
551
663
  const error = new Error(`send failed on ${node}:
552
664
  ${tried.join("\n ")}`);
553
665
  error.status = lastResponse?.status ?? null;
666
+ error.refused = isAdmissionRefusal(lastResponse);
554
667
  report(
555
- error.status === 429 ? "rate-limited" : error.status === 408 ? "timeout" : "post-failed",
668
+ error.refused ? "refused" : error.status === 429 ? "rate-limited" : error.status === 408 ? "timeout" : "post-failed",
556
669
  { res: lastResponse, error: error.message }
557
670
  );
558
671
  throw error;
@@ -588,11 +701,12 @@ var HELP = `paralith-bridge <command>
588
701
  propose-add <node-url> propose adding a node (its keys are read from the node)
589
702
  propose-remove <node-ao> propose removing one
590
703
  propose-migrate <new-pusd> propose moving the set to a replacement PUSD; every node follows
704
+ propose-token <base|solana|sui> ask the current majority to admit the recorded TEST token
591
705
  approve <id> approve as operator; your nodes then vote by themselves
592
706
  apply <id> carry the votes to Base, Solana and Sui (pays each chain's gas;
593
707
  --chain base|solana|sui for one)
594
708
  pause stop PUSD minting, redeeming and signing releases (any operator)
595
- unpause start it again (the PUSD owner only)
709
+ unpause propose starting it again; current majority approves and signs
596
710
 
597
711
  Keys are read from ~/.paralith/bridge/ unless a flag names another file:
598
712
  operator.json the operator's Arweave keyfile (--wallet <file>)
@@ -624,15 +738,23 @@ var readFile = (file, what) => {
624
738
  die(`no ${what} at ${file}`);
625
739
  }
626
740
  };
627
- var threshold = (n) => Math.floor((3 * n + 4) / 5);
741
+ var threshold = (n) => Math.floor(n / 2) + 1;
628
742
  async function getJson(url) {
743
+ if (!/^https?:\/\//i.test(url)) {
744
+ const file = path.resolve(url);
745
+ try {
746
+ return JSON.parse(fs.readFileSync(file, "utf8"));
747
+ } catch (error) {
748
+ throw new Error(`${file}: ${error.message}`);
749
+ }
750
+ }
629
751
  const r = await fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(15e3) });
630
752
  const text = await r.text();
631
753
  if (!r.ok) throw new Error(`${url}: HTTP ${r.status}`);
632
754
  if (text.trimStart().startsWith("<")) throw new Error(`${url}: not found`);
633
755
  return JSON.parse(text);
634
756
  }
635
- if (!["status", "propose-add", "propose-remove", "propose-migrate", "approve", "apply", "pause", "unpause"].includes(cmd)) {
757
+ if (!["status", "propose-add", "propose-remove", "propose-migrate", "propose-token", "approve", "apply", "pause", "unpause"].includes(cmd)) {
636
758
  console.log(HELP);
637
759
  process.exit(cmd ? 1 : 0);
638
760
  }
@@ -673,7 +795,9 @@ async function pusd(tags) {
673
795
  }
674
796
  die(`sent (slot ${slot}) but no reply yet; run status before sending again`);
675
797
  }
676
- var RELEASE_ATTESTORS = "PARALITH_ATTESTORS_V1";
798
+ var RELEASE_ATTESTORS = "PARALITH_ATTESTORS_V2";
799
+ var RELEASE_ROOT = "PARALITH_ROOT_V1";
800
+ var RELEASE_ADMIN = "PARALITH_ADMIN_V1";
677
801
  var hexBytes = (h) => toBytes(h);
678
802
  var u64 = (n) => {
679
803
  const b = Buffer.alloc(8);
@@ -681,6 +805,12 @@ var u64 = (n) => {
681
805
  return b;
682
806
  };
683
807
  var utf8 = (s) => Buffer.from(s, "utf8");
808
+ var processBytes = (id) => {
809
+ const bytes = Buffer.from(id ?? "", "base64url");
810
+ if (bytes.length !== 32) die(`process id ${id || "<empty>"} does not decode to 32 bytes`);
811
+ return bytes;
812
+ };
813
+ var processHex = (id) => `0x${processBytes(id).toString("hex")}`;
684
814
  function voters(p) {
685
815
  const v = p.prior.flatMap((member, at) => p.votes?.[member.ao] ? [{ at, member, vote: p.votes[member.ao] }] : []);
686
816
  if (v.length < threshold(p.prior.length)) die(`#${p.id} has ${v.length} of ${threshold(p.prior.length)} votes`);
@@ -691,7 +821,11 @@ var KEY_FILE = { base: "base.key", solana: "solana.json", sui: "sui.key" };
691
821
  var keyFor = (chain) => readFile(opt("key") ?? process.env[`PARALITH_${chain.toUpperCase()}_KEY`] ?? path.join(KEYS, KEY_FILE[chain]), `${chain} gas payer key`);
692
822
  var BASE_ABI = parseAbi([
693
823
  "function setAttestors(address[] set, uint64 newEpoch, bytes[] sigs)",
694
- "function epoch() view returns (uint64)"
824
+ "function setRoot(bytes32 successor, bytes[] sigs)",
825
+ "function setTokenAllowed(address token, bool allowed, bytes[] sigs)",
826
+ "function unpause(bytes[] sigs)",
827
+ "function epoch() view returns (uint64)",
828
+ "function root() view returns (bytes32)"
695
829
  ]);
696
830
  function baseClients(withKey) {
697
831
  const cfg = deployment.base;
@@ -742,15 +876,50 @@ var epochOf = {
742
876
  return Number(Buffer.from(bytes).readBigUInt64LE(0));
743
877
  }
744
878
  };
879
+ var rootOf = {
880
+ async base() {
881
+ return String(await baseClients(false).pub.readContract({ address: deployment.base.bridge, abi: BASE_ABI, functionName: "root" })).toLowerCase();
882
+ },
883
+ async solana() {
884
+ const info = await new Connection(rpcFor("solana"), "confirmed").getAccountInfo(solanaConfig());
885
+ if (!info) throw new Error("config not found");
886
+ const n = info.data.readUInt32LE(40);
887
+ return `0x${info.data.subarray(52 + 32 * n, 84 + 32 * n).toString("hex")}`;
888
+ },
889
+ async sui() {
890
+ const tx = new SuiTransaction();
891
+ tx.moveCall({ target: `${deployment.sui.package}::para_bridge::root`, arguments: [tx.object(deployment.sui.bridge)] });
892
+ tx.setSender("0x0");
893
+ const r = await suiClient().simulateTransaction({ transaction: tx, include: { commandResults: true }, checksEnabled: false });
894
+ const encoded = Buffer.from(r.commandResults?.[0]?.returnValues?.[0]?.bcs ?? []);
895
+ if (encoded.length !== 33 || encoded[0] !== 32) throw new Error("root read returned invalid vector<u8>");
896
+ return `0x${encoded.subarray(1).toString("hex")}`;
897
+ }
898
+ };
745
899
  var applyOn = {
746
900
  async base(p) {
747
901
  const { pub, wallet: w, account } = baseClients(true);
748
902
  console.log(`paying as ${account.address}`);
749
903
  const set = p.set.map((m) => m.base);
904
+ const currentEpoch = BigInt(p.priorEpoch ?? p.currentEpoch);
750
905
  const epoch = BigInt(p.epoch);
751
906
  const inner = keccak256(encodeAbiParameters(
752
- [{ type: "bytes32" }, { type: "uint256" }, { type: "address" }, { type: "uint64" }, { type: "address[]" }],
753
- [keccak256(toBytes(RELEASE_ATTESTORS)), BigInt(deployment.base.chainId), deployment.base.bridge, epoch, set]
907
+ [
908
+ { type: "bytes32" },
909
+ { type: "uint256" },
910
+ { type: "address" },
911
+ { type: "uint64" },
912
+ { type: "uint64" },
913
+ { type: "address[]" }
914
+ ],
915
+ [
916
+ keccak256(toBytes(RELEASE_ATTESTORS)),
917
+ BigInt(deployment.base.chainId),
918
+ deployment.base.bridge,
919
+ currentEpoch,
920
+ epoch,
921
+ set
922
+ ]
754
923
  ));
755
924
  const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
756
925
  const rows = await Promise.all(voters(p).map(async (v) => ({
@@ -768,9 +937,11 @@ var applyOn = {
768
937
  console.log(`paying as ${payer.publicKey.toBase58()}`);
769
938
  const program = solanaProgram();
770
939
  const set = p.set.map((m) => new PublicKey(m.solana));
940
+ const currentEpoch = p.priorEpoch ?? p.currentEpoch;
771
941
  const msg = Buffer.concat([
772
942
  utf8(RELEASE_ATTESTORS),
773
943
  program.toBuffer(),
944
+ u64(currentEpoch),
774
945
  u64(p.epoch),
775
946
  Buffer.from([set.length]),
776
947
  ...set.map((k) => k.toBuffer())
@@ -813,6 +984,229 @@ var applyOn = {
813
984
  return t.digest;
814
985
  }
815
986
  };
987
+ var applyRootOn = {
988
+ async base(p) {
989
+ const { pub, wallet: w, account } = baseClients(true);
990
+ console.log(`paying as ${account.address}`);
991
+ const oldRoot = processHex(PUSD);
992
+ const successor = processHex(p.successor);
993
+ const inner = keccak256(encodeAbiParameters(
994
+ [
995
+ { type: "bytes32" },
996
+ { type: "uint256" },
997
+ { type: "address" },
998
+ { type: "uint64" },
999
+ { type: "bytes32" },
1000
+ { type: "bytes32" }
1001
+ ],
1002
+ [
1003
+ keccak256(toBytes(RELEASE_ROOT)),
1004
+ BigInt(deployment.base.chainId),
1005
+ deployment.base.bridge,
1006
+ BigInt(p.currentEpoch ?? p.priorEpoch),
1007
+ oldRoot,
1008
+ successor
1009
+ ]
1010
+ ));
1011
+ const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1012
+ const rows = await Promise.all(voters(p).map(async (v) => ({
1013
+ sig: v.vote.base,
1014
+ who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1015
+ })));
1016
+ const sigs = rows.filter((row) => allowed.has(row.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((row) => row.sig);
1017
+ const hash = await w.writeContract({
1018
+ address: deployment.base.bridge,
1019
+ abi: BASE_ABI,
1020
+ functionName: "setRoot",
1021
+ args: [successor, sigs]
1022
+ });
1023
+ const receipt = await pub.waitForTransactionReceipt({ hash });
1024
+ if (receipt.status !== "success") die(`reverted ${hash}`);
1025
+ return hash;
1026
+ },
1027
+ async solana(p) {
1028
+ const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1029
+ const program = solanaProgram();
1030
+ const oldRoot = processBytes(PUSD);
1031
+ const successor = processBytes(p.successor);
1032
+ const msg = Buffer.concat([
1033
+ utf8(RELEASE_ROOT),
1034
+ program.toBuffer(),
1035
+ u64(p.currentEpoch ?? p.priorEpoch),
1036
+ oldRoot,
1037
+ successor
1038
+ ]);
1039
+ const tx = new Transaction().add(
1040
+ ed25519Ix(voters(p).map((v) => ({ pubkey: new PublicKey(v.member.solana).toBytes(), sig: hexBytes(v.vote.solana) })), msg),
1041
+ new TransactionInstruction({
1042
+ programId: program,
1043
+ keys: [
1044
+ { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1045
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1046
+ ],
1047
+ data: Buffer.concat([anchorIx("set_root"), successor])
1048
+ })
1049
+ );
1050
+ return sendAndConfirmTransaction(new Connection(rpcFor("solana"), "confirmed"), tx, [payer], { commitment: "confirmed" });
1051
+ },
1052
+ async sui(p) {
1053
+ const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1054
+ const v = voters(p);
1055
+ const tx = new SuiTransaction();
1056
+ tx.moveCall({
1057
+ target: `${deployment.sui.package}::para_bridge::set_root`,
1058
+ arguments: [
1059
+ tx.object(deployment.sui.bridge),
1060
+ tx.pure(bcs.vector(bcs.u8()).serialize(Array.from(processBytes(p.successor)))),
1061
+ tx.pure(vecU64.serialize(v.map((x) => BigInt(x.at)))),
1062
+ tx.pure(vecBytes.serialize(v.map((x) => Array.from(hexBytes(x.vote.sui)))))
1063
+ ]
1064
+ });
1065
+ const client = suiClient();
1066
+ const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1067
+ const t = r.Transaction ?? r.FailedTransaction;
1068
+ if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1069
+ await client.waitForTransaction({ digest: t.digest });
1070
+ return t.digest;
1071
+ }
1072
+ };
1073
+ var adminVoters = (p, chain) => voters(p).filter((row) => row.vote?.[chain]);
1074
+ var applyAdminOn = {
1075
+ async base(p) {
1076
+ const { pub, wallet: w, account } = baseClients(true);
1077
+ console.log(`paying as ${account.address}`);
1078
+ const allow = p.op === "add-token";
1079
+ const token = allow ? p.admin.token : "0x0000000000000000000000000000000000000000";
1080
+ const action = keccak256(toBytes(allow ? "ALLOW_TOKEN" : "UNPAUSE"));
1081
+ const inner = keccak256(encodeAbiParameters(
1082
+ [
1083
+ { type: "bytes32" },
1084
+ { type: "uint256" },
1085
+ { type: "address" },
1086
+ { type: "bytes32" },
1087
+ { type: "uint64" },
1088
+ { type: "bytes32" },
1089
+ { type: "address" },
1090
+ { type: "bool" }
1091
+ ],
1092
+ [
1093
+ keccak256(toBytes(RELEASE_ADMIN)),
1094
+ BigInt(deployment.base.chainId),
1095
+ deployment.base.bridge,
1096
+ processHex(PUSD),
1097
+ BigInt(p.currentEpoch ?? p.priorEpoch),
1098
+ action,
1099
+ token,
1100
+ true
1101
+ ]
1102
+ ));
1103
+ const allowed = new Set(p.prior.map((m) => m.base.toLowerCase()));
1104
+ const rows = await Promise.all(adminVoters(p, "base").map(async (v) => ({
1105
+ sig: v.vote.base,
1106
+ who: (await recoverMessageAddress({ message: { raw: inner }, signature: v.vote.base })).toLowerCase()
1107
+ })));
1108
+ const sigs = rows.filter((row) => allowed.has(row.who)).sort((a, b) => BigInt(a.who) < BigInt(b.who) ? -1 : 1).map((row) => row.sig);
1109
+ const hash = allow ? await w.writeContract({
1110
+ address: deployment.base.bridge,
1111
+ abi: BASE_ABI,
1112
+ functionName: "setTokenAllowed",
1113
+ args: [token, true, sigs]
1114
+ }) : await w.writeContract({
1115
+ address: deployment.base.bridge,
1116
+ abi: BASE_ABI,
1117
+ functionName: "unpause",
1118
+ args: [sigs]
1119
+ });
1120
+ const receipt = await pub.waitForTransactionReceipt({ hash });
1121
+ if (receipt.status !== "success") die(`reverted ${hash}`);
1122
+ return hash;
1123
+ },
1124
+ async solana(p) {
1125
+ const payer = Keypair.fromSecretKey(Uint8Array.from(JSON.parse(keyFor("solana"))));
1126
+ const program = solanaProgram();
1127
+ const allow = p.op === "add-token";
1128
+ const mint = allow ? new PublicKey(p.admin.token) : new PublicKey(new Uint8Array(32));
1129
+ const action = allow ? 1 : 2;
1130
+ const msg = Buffer.concat([
1131
+ utf8(RELEASE_ADMIN),
1132
+ program.toBuffer(),
1133
+ processBytes(PUSD),
1134
+ u64(p.currentEpoch ?? p.priorEpoch),
1135
+ Buffer.from([action]),
1136
+ mint.toBuffer(),
1137
+ Buffer.from([1])
1138
+ ]);
1139
+ const precompile = ed25519Ix(adminVoters(p, "solana").map((v) => ({
1140
+ pubkey: new PublicKey(v.member.solana).toBytes(),
1141
+ sig: hexBytes(v.vote.solana)
1142
+ })), msg);
1143
+ let instruction;
1144
+ if (allow) {
1145
+ const token = (deployment.solana.tokens ?? []).find((row) => row.mint === p.admin.token);
1146
+ if (!token) die(`Solana token ${p.admin.token} is absent from the deployment record`);
1147
+ const tokenProgram = new PublicKey(token.tokenProgram);
1148
+ instruction = new TransactionInstruction({
1149
+ programId: program,
1150
+ keys: [
1151
+ { pubkey: payer.publicKey, isSigner: true, isWritable: true },
1152
+ { pubkey: solanaConfig(), isSigner: false, isWritable: false },
1153
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false },
1154
+ { pubkey: mint, isSigner: false, isWritable: false },
1155
+ { pubkey: PublicKey.findProgramAddressSync([utf8("vault"), mint.toBuffer()], program)[0], isSigner: false, isWritable: true },
1156
+ { pubkey: tokenProgram, isSigner: false, isWritable: false },
1157
+ { pubkey: SystemProgram.programId, isSigner: false, isWritable: false }
1158
+ ],
1159
+ data: anchorIx("allow_token")
1160
+ });
1161
+ } else {
1162
+ instruction = new TransactionInstruction({
1163
+ programId: program,
1164
+ keys: [
1165
+ { pubkey: solanaConfig(), isSigner: false, isWritable: true },
1166
+ { pubkey: SYSVAR_INSTRUCTIONS_PUBKEY, isSigner: false, isWritable: false }
1167
+ ],
1168
+ data: anchorIx("unpause")
1169
+ });
1170
+ }
1171
+ return sendAndConfirmTransaction(
1172
+ new Connection(rpcFor("solana"), "confirmed"),
1173
+ new Transaction().add(precompile, instruction),
1174
+ [payer],
1175
+ { commitment: "confirmed" }
1176
+ );
1177
+ },
1178
+ async sui(p) {
1179
+ const signer = Ed25519Keypair.fromSecretKey(keyFor("sui"));
1180
+ const rows = adminVoters(p, "sui");
1181
+ const tx = new SuiTransaction();
1182
+ if (p.op === "add-token") {
1183
+ tx.moveCall({
1184
+ target: `${deployment.sui.package}::para_bridge::allow_token`,
1185
+ typeArguments: [p.admin.token],
1186
+ arguments: [
1187
+ tx.object(deployment.sui.bridge),
1188
+ tx.pure(vecU64.serialize(rows.map((x) => BigInt(x.at)))),
1189
+ tx.pure(vecBytes.serialize(rows.map((x) => Array.from(hexBytes(x.vote.sui)))))
1190
+ ]
1191
+ });
1192
+ } else {
1193
+ tx.moveCall({
1194
+ target: `${deployment.sui.package}::para_bridge::unpause`,
1195
+ arguments: [
1196
+ tx.object(deployment.sui.bridge),
1197
+ tx.pure(vecU64.serialize(rows.map((x) => BigInt(x.at)))),
1198
+ tx.pure(vecBytes.serialize(rows.map((x) => Array.from(hexBytes(x.vote.sui)))))
1199
+ ]
1200
+ });
1201
+ }
1202
+ const client = suiClient();
1203
+ const r = await client.signAndExecuteTransaction({ transaction: tx, signer, include: { effects: true } });
1204
+ const t = r.Transaction ?? r.FailedTransaction;
1205
+ if (!t.status.success) die(`failed ${t.digest}: ${JSON.stringify(t.status.error)}`);
1206
+ await client.waitForTransaction({ digest: t.digest });
1207
+ return t.digest;
1208
+ }
1209
+ };
816
1210
  var short = (s = "") => s.length > 18 ? `${s.slice(0, 8)}\u2026${s.slice(-6)}` : s;
817
1211
  async function status() {
818
1212
  const info = await bridgeInfo();
@@ -838,7 +1232,7 @@ async function main() {
838
1232
  if (cmd === "propose-add") {
839
1233
  if (!target) die("propose-add <node-url>");
840
1234
  const url = target.replace(/\/+$/, "").replace(/^(?!https?:\/\/)/, "https://");
841
- const k = await getJson(`${url}/~bridge@1.0/keys`);
1235
+ const k = await getJson(`${url}/~bridge-attestor@1.0/keys`);
842
1236
  if (!k.ao || !k.base || !k.solana || !k.sui) die(`${url} published incomplete keys`);
843
1237
  const operator = opt("operator") ?? wallet().address;
844
1238
  console.log(`node ${k.ao}
@@ -874,15 +1268,61 @@ operator ${operator}`);
874
1268
  await pusd({ Action: "Attestor-Approve", ProposalId: String(target) });
875
1269
  return console.log(`approved #${target}; your nodes vote on their next pass`);
876
1270
  }
877
- if (cmd === "pause" || cmd === "unpause") {
878
- await pusd({ Action: cmd === "pause" ? "Bridge-Pause" : "Bridge-Unpause" });
879
- return console.log(cmd === "pause" ? "paused" : "running");
1271
+ if (cmd === "pause") {
1272
+ await pusd({ Action: "Bridge-Pause" });
1273
+ return console.log("paused");
1274
+ }
1275
+ if (cmd === "propose-token") {
1276
+ if (!CHAINS.includes(target)) die("propose-token <base|solana|sui>");
1277
+ const rows = deployment[target].tokens ?? [];
1278
+ const token = rows.find((row) => !row.retired);
1279
+ const id = target === "base" ? token?.address : target === "solana" ? token?.mint : token?.type;
1280
+ if (!id) die(`manifest has no active ${target} token`);
1281
+ const r = await pusd({
1282
+ Action: "Attestor-Propose",
1283
+ Op: "add-token",
1284
+ Chain: target,
1285
+ Token: id,
1286
+ Symbol: token.symbol,
1287
+ Decimals: String(token.decimals)
1288
+ });
1289
+ return console.log(`proposed #${r.ProposalId ?? "?"} for ${target} ${id}; next: approve ${r.ProposalId ?? "<id>"}`);
1290
+ }
1291
+ if (cmd === "unpause") {
1292
+ const r = await pusd({ Action: "Attestor-Propose", Op: "unpause" });
1293
+ return console.log(`proposed #${r.ProposalId ?? "?"}; next: approve ${r.ProposalId ?? "<id>"}`);
880
1294
  }
881
1295
  if (cmd === "apply") {
882
1296
  const chain = opt("chain");
883
1297
  if (!target || chain && !CHAINS.includes(chain)) die("apply <id> [--chain base|solana|sui]");
884
1298
  const p = proposal(await bridgeInfo(), target);
885
1299
  if (p.status !== "applied") die(`#${p.id} is ${p.status}; it needs its votes first`);
1300
+ if (p.op === "migrate") {
1301
+ const oldRoot = processHex(PUSD).toLowerCase();
1302
+ const successor = processHex(p.successor).toLowerCase();
1303
+ for (const c of chain ? [chain] : CHAINS) {
1304
+ const current = await rootOf[c]();
1305
+ if (current === successor) {
1306
+ console.log(`${c}: already points to ${p.successor}`);
1307
+ continue;
1308
+ }
1309
+ if (current !== oldRoot) die(`${c} points to ${current}, not ${PUSD}`);
1310
+ console.log(`${c}: root ${p.successor}, ${await applyRootOn[c](p)}`);
1311
+ }
1312
+ return;
1313
+ }
1314
+ if (p.kind === "admin") {
1315
+ if (!["add-token", "unpause"].includes(p.op)) {
1316
+ console.log(`#${p.id} ${p.op} is AO-only and needs no chain application`);
1317
+ return;
1318
+ }
1319
+ const targets = p.op === "add-token" ? [p.admin.chain] : chain ? [chain] : CHAINS;
1320
+ if (chain && p.op === "add-token" && chain !== p.admin.chain) {
1321
+ die(`#${p.id} adds a token on ${p.admin.chain}, not ${chain}`);
1322
+ }
1323
+ for (const c of targets) console.log(`${c}: ${p.op}, ${await applyAdminOn[c](p)}`);
1324
+ return;
1325
+ }
886
1326
  for (const c of chain ? [chain] : CHAINS) {
887
1327
  const now = await epochOf[c]();
888
1328
  if (now >= p.epoch) {