@outpost-protocol/core 0.1.1 → 0.2.0

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.
@@ -0,0 +1,435 @@
1
+ /**
2
+ * Soroban Contract Call Operation Builders for Outpost v1.2 (`VaultFactory` & `UserVault`).
3
+ *
4
+ * Pure browser/WebView/Node compatible (uses `Uint8Array`, zero Node `Buffer` dependencies)
5
+ * and 100% asset-agnostic across all Stellar SAC and SEP-41 token contracts.
6
+ */
7
+ import * as StellarSdk from "@stellar/stellar-sdk";
8
+ import { assertBigInt, assertBytesLength, assertSortedUniqueWitnesses, assertU16, assertU32, MAX_U64, MAX_WITNESSES, } from "./digest.js";
9
+ import { MIN_EXIT_DELAY_SECS, MAX_EXIT_DELAY_SECS } from "./wallet.js";
10
+ import { decodeSmeshc1 } from "./wire.js";
11
+ import { hexToBytes } from "./witnessClient.js";
12
+ import { assertNotMuxedStrKey, assertValidWireAddress, normalizeContractHash, strKeyToWireAddress, wireAddressToStrKey, } from "./xdr.js";
13
+ // ---------------------------------------------------------------------------
14
+ // Internal Normalization & XDR Helpers
15
+ // ---------------------------------------------------------------------------
16
+ function normalizeContractStrKey(contract, label) {
17
+ try {
18
+ return StellarSdk.StrKey.encodeContract(normalizeContractHash(contract));
19
+ }
20
+ catch (err) {
21
+ throw new Error(`Invalid ${label} contract address: ${err instanceof Error ? err.message : String(err)}`);
22
+ }
23
+ }
24
+ function normalizeNonMuxedAddressStrKey(addr, label) {
25
+ if (typeof addr === "string") {
26
+ assertNotMuxedStrKey(addr);
27
+ return wireAddressToStrKey(strKeyToWireAddress(addr));
28
+ }
29
+ assertValidWireAddress(addr);
30
+ const strKey = wireAddressToStrKey(addr);
31
+ if (!strKey) {
32
+ throw new Error(`Invalid ${label} address`);
33
+ }
34
+ return strKey;
35
+ }
36
+ function normalizeFixedBytes(value, expectedLen, label) {
37
+ const bytes = typeof value === "string" ? hexToBytes(value) : new Uint8Array(value);
38
+ assertBytesLength(bytes, expectedLen, label);
39
+ return bytes;
40
+ }
41
+ function normalizeU64BigInt(value, label) {
42
+ if (typeof value === "bigint") {
43
+ if (value < 0n || value > MAX_U64) {
44
+ throw new RangeError(`${label} out of u64 range: ${value}`);
45
+ }
46
+ return value;
47
+ }
48
+ if (!Number.isSafeInteger(value) || value < 0) {
49
+ throw new RangeError(`${label} must be a non-negative safe integer, got ${value}`);
50
+ }
51
+ return BigInt(value);
52
+ }
53
+ function encodeWitnessSigsScVal(witnessSigs, label) {
54
+ if (witnessSigs.length < 1 || witnessSigs.length > MAX_WITNESSES) {
55
+ throw new Error(`${label} must contain between 1 and ${MAX_WITNESSES} signatures, got ${witnessSigs.length}`);
56
+ }
57
+ let prevIdx = -1;
58
+ const entries = [];
59
+ for (let i = 0; i < witnessSigs.length; i++) {
60
+ const entry = witnessSigs[i];
61
+ if (!Number.isInteger(entry.index) || entry.index < 0 || entry.index >= MAX_WITNESSES) {
62
+ throw new Error(`${label}[${i}].index (${entry.index}) must be in 0..${MAX_WITNESSES - 1}`);
63
+ }
64
+ if (entry.index <= prevIdx) {
65
+ throw new Error(`${label} witness indices must be strictly ascending and unique`);
66
+ }
67
+ prevIdx = entry.index;
68
+ const sigBytes = normalizeFixedBytes(entry.signature, 64, `${label}[${i}].signature`);
69
+ entries.push(StellarSdk.xdr.ScVal.scvVec([
70
+ StellarSdk.xdr.ScVal.scvU32(entry.index),
71
+ StellarSdk.xdr.ScVal.scvBytes(sigBytes),
72
+ ]));
73
+ }
74
+ return StellarSdk.xdr.ScVal.scvVec(entries);
75
+ }
76
+ /**
77
+ * Low-level Soroban `InvokeHostFunctionOp` (`HostFunctionType::InvokeContract`) builder.
78
+ */
79
+ export function buildContractCallOp(contractId, method, args, auth = []) {
80
+ if (!method || method.trim().length === 0) {
81
+ throw new Error("Contract method name must be non-empty");
82
+ }
83
+ const strKey = normalizeContractStrKey(contractId, "contractId");
84
+ const invokeArgs = new StellarSdk.xdr.InvokeContractArgs({
85
+ contractAddress: StellarSdk.Address.fromString(strKey).toScAddress(),
86
+ functionName: method,
87
+ args: [...args],
88
+ });
89
+ const func = StellarSdk.xdr.HostFunction.hostFunctionTypeInvokeContract(invokeArgs);
90
+ return StellarSdk.Operation.invokeHostFunction({
91
+ func,
92
+ auth: [...auth],
93
+ });
94
+ }
95
+ /**
96
+ * Build `VaultFactory.create_vault(owner: Address) -> Address`.
97
+ */
98
+ export function buildCreateVaultOp(params) {
99
+ const factoryStrKey = normalizeContractStrKey(params.factoryId, "factoryId");
100
+ const ownerStrKey = normalizeNonMuxedAddressStrKey(params.owner, "owner");
101
+ return buildContractCallOp(factoryStrKey, "create_vault", [
102
+ StellarSdk.Address.fromString(ownerStrKey).toScVal(),
103
+ ]);
104
+ }
105
+ /**
106
+ * Build read-only view call `VaultFactory.expected_vault(owner: Address) -> Address`.
107
+ */
108
+ export function buildExpectedVaultOp(params) {
109
+ const factoryStrKey = normalizeContractStrKey(params.factoryId, "factoryId");
110
+ const ownerStrKey = normalizeNonMuxedAddressStrKey(params.owner, "owner");
111
+ return buildContractCallOp(factoryStrKey, "expected_vault", [
112
+ StellarSdk.Address.fromString(ownerStrKey).toScVal(),
113
+ ]);
114
+ }
115
+ /**
116
+ * Build read-only view call `VaultFactory.user_vault_wasm_hash() -> BytesN<32>`.
117
+ */
118
+ export function buildUserVaultWasmHashOp(params) {
119
+ const factoryStrKey = normalizeContractStrKey(params.factoryId, "factoryId");
120
+ return buildContractCallOp(factoryStrKey, "user_vault_wasm_hash", []);
121
+ }
122
+ /**
123
+ * Decode the `Address` (`C...`) returned by `VaultFactory.create_vault` or `expected_vault`.
124
+ */
125
+ export function parseCreateVaultResult(retval) {
126
+ if (retval.type !== "scvAddress") {
127
+ throw new Error(`Expected scvAddress return value from VaultFactory, got ${retval.type}`);
128
+ }
129
+ const strKey = StellarSdk.Address.fromScVal(retval).toString();
130
+ normalizeContractHash(strKey);
131
+ return strKey;
132
+ }
133
+ /**
134
+ * Build `UserVault.deposit(pocket_id, token, amount, device_pubkey, witnesses, witness_threshold, exit_delay_secs)`.
135
+ */
136
+ export function buildDepositOp(params) {
137
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
138
+ const tokenStrKey = normalizeContractStrKey(params.token, "token");
139
+ if (tokenStrKey === vaultStrKey) {
140
+ throw new Error("deposit `token` cannot equal `vaultId`");
141
+ }
142
+ assertU16(params.pocketId, "pocketId");
143
+ assertBigInt(params.amount, "amount");
144
+ if (params.amount <= 0n || params.amount > MAX_U64) {
145
+ throw new Error(`deposit amount must be > 0 and <= u64::MAX, got ${params.amount}`);
146
+ }
147
+ const devicePubkey = normalizeFixedBytes(params.devicePubkey, 32, "devicePubkey");
148
+ const witnesses = params.witnesses.map((w, i) => normalizeFixedBytes(w, 32, `witnesses[${i}]`));
149
+ assertSortedUniqueWitnesses(witnesses);
150
+ const n = witnesses.length;
151
+ if (!Number.isInteger(params.witnessThreshold) ||
152
+ params.witnessThreshold < 1 ||
153
+ params.witnessThreshold > n ||
154
+ params.witnessThreshold * 2 <= n) {
155
+ throw new Error(`witnessThreshold (${params.witnessThreshold}) must satisfy 0 < t <= n and 2t > n (n=${n})`);
156
+ }
157
+ const exitDelaySecs = normalizeU64BigInt(params.exitDelaySecs, "exitDelaySecs");
158
+ if (exitDelaySecs < MIN_EXIT_DELAY_SECS || exitDelaySecs > MAX_EXIT_DELAY_SECS) {
159
+ throw new Error(`exitDelaySecs (${exitDelaySecs}) must be within [${MIN_EXIT_DELAY_SECS}, ${MAX_EXIT_DELAY_SECS}]`);
160
+ }
161
+ return buildContractCallOp(vaultStrKey, "deposit", [
162
+ StellarSdk.xdr.ScVal.scvU32(params.pocketId),
163
+ StellarSdk.Address.fromString(tokenStrKey).toScVal(),
164
+ StellarSdk.nativeToScVal(params.amount, { type: "i128" }),
165
+ StellarSdk.xdr.ScVal.scvBytes(devicePubkey),
166
+ StellarSdk.xdr.ScVal.scvVec(witnesses.map((w) => StellarSdk.xdr.ScVal.scvBytes(w))),
167
+ StellarSdk.xdr.ScVal.scvU32(params.witnessThreshold),
168
+ StellarSdk.nativeToScVal(exitDelaySecs, { type: "u64" }),
169
+ ]);
170
+ }
171
+ /**
172
+ * Build `UserVault.settle_delegated(...)` either directly from a `SMESHC1` certificate or from
173
+ * explicit fields.
174
+ */
175
+ export function buildSettleDelegatedOp(params) {
176
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
177
+ let pocketId;
178
+ let epoch;
179
+ let seq;
180
+ let toStrKey;
181
+ let amount;
182
+ let maxTip;
183
+ let actualTip;
184
+ let gatewayStrKey;
185
+ let expiryTs;
186
+ let expiryLedger;
187
+ let orderId;
188
+ let cumulativeSpent;
189
+ let deviceSig;
190
+ let witnessSigsScVal;
191
+ if ("cert" in params) {
192
+ const cert = typeof params.cert === "string" ? decodeSmeshc1(params.cert) : params.cert;
193
+ const { intent } = cert;
194
+ pocketId = intent.pocketId;
195
+ epoch = intent.epoch;
196
+ seq = intent.seq;
197
+ toStrKey = normalizeNonMuxedAddressStrKey(intent.to, "cert.intent.to");
198
+ amount = intent.amount;
199
+ maxTip = intent.maxTip;
200
+ actualTip = params.actualTip ?? 0n;
201
+ gatewayStrKey = normalizeNonMuxedAddressStrKey(params.gateway, "gateway");
202
+ expiryTs = normalizeU64BigInt(intent.expiryTs, "cert.intent.expiryTs");
203
+ expiryLedger = intent.expiryLedger;
204
+ orderId = intent.orderId;
205
+ cumulativeSpent = cert.cumulativeSpent;
206
+ deviceSig = normalizeFixedBytes(intent.deviceSig, 64, "cert.intent.deviceSig");
207
+ witnessSigsScVal = encodeWitnessSigsScVal(cert.witnessSigs, "cert.witnessSigs");
208
+ }
209
+ else {
210
+ pocketId = params.pocketId;
211
+ epoch = params.epoch;
212
+ seq = params.seq;
213
+ toStrKey = normalizeNonMuxedAddressStrKey(params.to, "to");
214
+ amount = params.amount;
215
+ maxTip = params.maxTip;
216
+ actualTip = params.actualTip;
217
+ gatewayStrKey = normalizeNonMuxedAddressStrKey(params.gateway, "gateway");
218
+ expiryTs = normalizeU64BigInt(params.expiryTs, "expiryTs");
219
+ expiryLedger = params.expiryLedger;
220
+ orderId = params.orderId;
221
+ cumulativeSpent = params.cumulativeSpent;
222
+ deviceSig = normalizeFixedBytes(params.deviceSig, 64, "deviceSig");
223
+ witnessSigsScVal = encodeWitnessSigsScVal(params.witnessSigs, "witnessSigs");
224
+ }
225
+ assertU16(pocketId, "pocketId");
226
+ assertU32(epoch, "epoch");
227
+ if (epoch === 0)
228
+ throw new Error("settle_delegated epoch must be >= 1");
229
+ assertU32(seq, "seq");
230
+ if (seq === 0)
231
+ throw new Error("settle_delegated seq must be >= 1");
232
+ assertU32(expiryLedger, "expiryLedger");
233
+ assertBigInt(amount, "amount");
234
+ assertBigInt(maxTip, "maxTip");
235
+ assertBigInt(actualTip, "actualTip");
236
+ assertBigInt(orderId, "orderId");
237
+ assertBigInt(cumulativeSpent, "cumulativeSpent");
238
+ if (toStrKey === vaultStrKey || gatewayStrKey === vaultStrKey) {
239
+ throw new Error("settle_delegated SelfTransfer forbidden: to/gateway cannot equal vaultId");
240
+ }
241
+ if (amount <= 0n || amount > MAX_U64) {
242
+ throw new Error(`settle_delegated amount out of range: ${amount}`);
243
+ }
244
+ if (maxTip < 0n || actualTip < 0n || actualTip > maxTip) {
245
+ throw new Error(`settle_delegated invalid tip: actualTip=${actualTip}, maxTip=${maxTip}`);
246
+ }
247
+ if (orderId < 0n || orderId > MAX_U64) {
248
+ throw new RangeError(`settle_delegated orderId out of u64 range: ${orderId}`);
249
+ }
250
+ if (cumulativeSpent < amount + maxTip) {
251
+ throw new Error(`settle_delegated cumulativeSpent (${cumulativeSpent}) < amount + maxTip (${amount + maxTip})`);
252
+ }
253
+ return buildContractCallOp(vaultStrKey, "settle_delegated", [
254
+ StellarSdk.xdr.ScVal.scvU32(pocketId),
255
+ StellarSdk.xdr.ScVal.scvU32(epoch),
256
+ StellarSdk.xdr.ScVal.scvU32(seq),
257
+ StellarSdk.Address.fromString(toStrKey).toScVal(),
258
+ StellarSdk.nativeToScVal(amount, { type: "i128" }),
259
+ StellarSdk.nativeToScVal(maxTip, { type: "i128" }),
260
+ StellarSdk.nativeToScVal(actualTip, { type: "i128" }),
261
+ StellarSdk.Address.fromString(gatewayStrKey).toScVal(),
262
+ StellarSdk.nativeToScVal(expiryTs, { type: "u64" }),
263
+ StellarSdk.xdr.ScVal.scvU32(expiryLedger),
264
+ StellarSdk.nativeToScVal(orderId, { type: "u64" }),
265
+ StellarSdk.nativeToScVal(cumulativeSpent, { type: "i128" }),
266
+ StellarSdk.xdr.ScVal.scvBytes(deviceSig),
267
+ witnessSigsScVal,
268
+ ]);
269
+ }
270
+ /**
271
+ * Build `UserVault.close_pocket_cooperative(pocket_id, to_alt, witness_sigs)`.
272
+ */
273
+ export function buildClosePocketCooperativeOp(params) {
274
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
275
+ assertU16(params.pocketId, "pocketId");
276
+ const toAltStrKey = normalizeNonMuxedAddressStrKey(params.toAlt, "toAlt");
277
+ if (toAltStrKey === vaultStrKey) {
278
+ throw new Error("close_pocket_cooperative SelfTransfer forbidden: toAlt cannot equal vaultId");
279
+ }
280
+ const witnessSigsScVal = encodeWitnessSigsScVal(params.witnessSigs, "witnessSigs");
281
+ return buildContractCallOp(vaultStrKey, "close_pocket_cooperative", [
282
+ StellarSdk.xdr.ScVal.scvU32(params.pocketId),
283
+ StellarSdk.Address.fromString(toAltStrKey).toScVal(),
284
+ witnessSigsScVal,
285
+ ]);
286
+ }
287
+ /**
288
+ * Build `UserVault.request_exit(pocket_id)` — initiates unilateral timelocked exit (`exit_delay_secs`).
289
+ */
290
+ export function buildRequestExitOp(params) {
291
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
292
+ assertU16(params.pocketId, "pocketId");
293
+ return buildContractCallOp(vaultStrKey, "request_exit", [
294
+ StellarSdk.xdr.ScVal.scvU32(params.pocketId),
295
+ ]);
296
+ }
297
+ /**
298
+ * Build `UserVault.finalize_exit(pocket_id, to_alt)` — sweeps pocket after `pending_exit_ts` elapses.
299
+ */
300
+ export function buildFinalizeExitOp(params) {
301
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
302
+ assertU16(params.pocketId, "pocketId");
303
+ const toAltStrKey = normalizeNonMuxedAddressStrKey(params.toAlt, "toAlt");
304
+ if (toAltStrKey === vaultStrKey) {
305
+ throw new Error("finalize_exit SelfTransfer forbidden: toAlt cannot equal vaultId");
306
+ }
307
+ return buildContractCallOp(vaultStrKey, "finalize_exit", [
308
+ StellarSdk.xdr.ScVal.scvU32(params.pocketId),
309
+ StellarSdk.Address.fromString(toAltStrKey).toScVal(),
310
+ ]);
311
+ }
312
+ /**
313
+ * Build `UserVault.claim_credit(recipient, token, to_alt)` — claims parked credits when a classic
314
+ * trustline or SAC transfer previously bounced during `settle_delegated`.
315
+ */
316
+ export function buildClaimCreditOp(params) {
317
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
318
+ const recipientStrKey = normalizeNonMuxedAddressStrKey(params.recipient, "recipient");
319
+ const tokenStrKey = normalizeContractStrKey(params.token, "token");
320
+ const toAltStrKey = normalizeNonMuxedAddressStrKey(params.toAlt, "toAlt");
321
+ if (toAltStrKey === vaultStrKey) {
322
+ throw new Error("claim_credit SelfTransfer forbidden: toAlt cannot equal vaultId");
323
+ }
324
+ return buildContractCallOp(vaultStrKey, "claim_credit", [
325
+ StellarSdk.Address.fromString(recipientStrKey).toScVal(),
326
+ StellarSdk.Address.fromString(tokenStrKey).toScVal(),
327
+ StellarSdk.Address.fromString(toAltStrKey).toScVal(),
328
+ ]);
329
+ }
330
+ // ---------------------------------------------------------------------------
331
+ // Read-Only View Call Builders & Decoders
332
+ // ---------------------------------------------------------------------------
333
+ /**
334
+ * Build read-only view call `UserVault.pocket_of(pocket_id: u32) -> Option<PocketState>`.
335
+ */
336
+ export function buildPocketOfOp(params) {
337
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
338
+ assertU16(params.pocketId, "pocketId");
339
+ return buildContractCallOp(vaultStrKey, "pocket_of", [
340
+ StellarSdk.xdr.ScVal.scvU32(params.pocketId),
341
+ ]);
342
+ }
343
+ /**
344
+ * Build read-only view call `UserVault.credit_of(recipient: Address, token: Address) -> i128`.
345
+ */
346
+ export function buildCreditOfOp(params) {
347
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
348
+ const recipientStrKey = normalizeNonMuxedAddressStrKey(params.recipient, "recipient");
349
+ const tokenStrKey = normalizeContractStrKey(params.token, "token");
350
+ return buildContractCallOp(vaultStrKey, "credit_of", [
351
+ StellarSdk.Address.fromString(recipientStrKey).toScVal(),
352
+ StellarSdk.Address.fromString(tokenStrKey).toScVal(),
353
+ ]);
354
+ }
355
+ /**
356
+ * Build read-only view call `UserVault.is_settled(pocket_id: u32, epoch: u32, seq: u32) -> bool`.
357
+ */
358
+ export function buildIsSettledOp(params) {
359
+ const vaultStrKey = normalizeContractStrKey(params.vaultId, "vaultId");
360
+ assertU16(params.pocketId, "pocketId");
361
+ assertU32(params.epoch, "epoch");
362
+ assertU32(params.seq, "seq");
363
+ return buildContractCallOp(vaultStrKey, "is_settled", [
364
+ StellarSdk.xdr.ScVal.scvU32(params.pocketId),
365
+ StellarSdk.xdr.ScVal.scvU32(params.epoch),
366
+ StellarSdk.xdr.ScVal.scvU32(params.seq),
367
+ ]);
368
+ }
369
+ /**
370
+ * Decode `Option<PocketState>` returned by `UserVault.pocket_of(pocket_id)` simulation.
371
+ * Returns `null` when `ScVal` is `scvVoid` (`None`).
372
+ */
373
+ export function decodePocketStateScVal(scVal) {
374
+ if (scVal.type === "scvVoid") {
375
+ return null;
376
+ }
377
+ if (scVal.type !== "scvMap" || !scVal.map) {
378
+ throw new Error(`Expected scvMap or scvVoid for PocketState, got ${scVal.type}`);
379
+ }
380
+ const fields = new Map();
381
+ for (const entry of scVal.map) {
382
+ if (entry.key.type === "scvSymbol") {
383
+ fields.set(String(StellarSdk.scValToNative(entry.key)), entry.val);
384
+ }
385
+ }
386
+ const getField = (name) => {
387
+ const v = fields.get(name);
388
+ if (!v)
389
+ throw new Error(`PocketState ScVal missing required field "${name}"`);
390
+ return v;
391
+ };
392
+ const tokenVal = getField("token");
393
+ if (tokenVal.type !== "scvAddress") {
394
+ throw new Error(`PocketState.token expected scvAddress, got ${tokenVal.type}`);
395
+ }
396
+ const token = StellarSdk.Address.fromScVal(tokenVal).toString();
397
+ normalizeContractHash(token);
398
+ const balance = StellarSdk.scValToBigInt(getField("balance"));
399
+ const epochTotalDeposited = StellarSdk.scValToBigInt(getField("epoch_total_deposited"));
400
+ const deviceVal = getField("device_pubkey");
401
+ if (deviceVal.type !== "scvBytes") {
402
+ throw new Error(`PocketState.device_pubkey expected scvBytes, got ${deviceVal.type}`);
403
+ }
404
+ const deviceNative = StellarSdk.scValToNative(deviceVal);
405
+ const devicePubkey = new Uint8Array(deviceNative);
406
+ assertBytesLength(devicePubkey, 32, "PocketState.device_pubkey");
407
+ const witnessesVal = getField("witnesses");
408
+ if (witnessesVal.type !== "scvVec" || !witnessesVal.vec) {
409
+ throw new Error(`PocketState.witnesses expected scvVec, got ${witnessesVal.type}`);
410
+ }
411
+ const witnesses = witnessesVal.vec.map((w, idx) => {
412
+ if (w.type !== "scvBytes") {
413
+ throw new Error(`PocketState.witnesses[${idx}] expected scvBytes, got ${w.type}`);
414
+ }
415
+ const wNative = StellarSdk.scValToNative(w);
416
+ const b = new Uint8Array(wNative);
417
+ assertBytesLength(b, 32, `PocketState.witnesses[${idx}]`);
418
+ return b;
419
+ });
420
+ const witnessThreshold = Number(StellarSdk.scValToBigInt(getField("witness_threshold")));
421
+ const exitDelaySecs = StellarSdk.scValToBigInt(getField("exit_delay_secs"));
422
+ const pendingExitTs = StellarSdk.scValToBigInt(getField("pending_exit_ts"));
423
+ const epoch = Number(StellarSdk.scValToBigInt(getField("epoch")));
424
+ return {
425
+ token,
426
+ balance,
427
+ epochTotalDeposited,
428
+ devicePubkey,
429
+ witnesses,
430
+ witnessThreshold,
431
+ exitDelaySecs,
432
+ pendingExitTs,
433
+ epoch,
434
+ };
435
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Multi-Witness Certificate Assembly Coordinators for Outpost v1.2 Wallets:
3
+ * - `coordinateInitGenesis`: collects `>= t` verified `"SMW1_GENESIS"` signatures, assembles
4
+ * canonical `cert_0` (`EpochGenesisCert`), and optionally propagates quorum `cert_0` to all witnesses.
5
+ * - `coordinateRefreshFreshness`: collects `>= t` verified `"SMW1_FRESH"` signatures, assembles
6
+ * a quorum `StoredFreshCertDto`, and optionally propagates it to all witnesses.
7
+ * - `coordinateCloseCooperative`: signs/forwards owner or device `"SMW1_CLOSE"` auth, collects
8
+ * `>= t` verified witness close signatures sorted by `witness_index` for `buildClosePocketCooperativeOp`.
9
+ *
10
+ * Every witness response is cryptographically verified against the caller's pinned `witnesses`
11
+ * set and locally recomputed canonical digest before acceptance (`AGENTS.md` §1.1 & §1.6).
12
+ */
13
+ import type { EpochGenesisCert, IndexedWitnessSignature } from "./wire.js";
14
+ import { WitnessClient, type StoredFreshCertDto, type WitnessClientOptions } from "./witnessClient.js";
15
+ import { TokenResolver, type NetworkHint, type WireAddress, type WireToken } from "./xdr.js";
16
+ export type WitnessClientInput = WitnessClient | string;
17
+ export interface WitnessCallFailure {
18
+ readonly endpoint: string;
19
+ readonly reason: string;
20
+ }
21
+ export interface CoordinateInitGenesisParams {
22
+ /** Witness stations (`WitnessClient` instances or base URLs like `"https://witness.outpost.cash/w1"`). */
23
+ readonly witnessClients: readonly WitnessClientInput[];
24
+ readonly witnessClientOptions?: WitnessClientOptions;
25
+ readonly networkHint: NetworkHint;
26
+ readonly networkPassphrase?: string;
27
+ readonly factoryVer: number;
28
+ readonly owner: WireAddress | string;
29
+ readonly vaultId: string | WireAddress | Uint8Array;
30
+ readonly pocketId: number;
31
+ readonly epoch: number;
32
+ readonly token: WireToken;
33
+ readonly tokenResolver?: TokenResolver;
34
+ readonly devicePubkey: Uint8Array | string;
35
+ /** Strictly ascending unique 32B witness Ed25519 pubkeys (`sortWitnesses()`). */
36
+ readonly witnesses: readonly (Uint8Array | string)[];
37
+ readonly witnessThreshold: number;
38
+ readonly epochTotalDeposited: bigint;
39
+ readonly exitDelaySecs: bigint | number;
40
+ /** Monotonic L1 ledger sequence (e.g. deposit confirmation ledger or current latest ledger). */
41
+ readonly targetLedgerSeq: number;
42
+ /** Monotonic L1 ledger close timestamp in unix seconds. */
43
+ readonly targetTs: bigint | number;
44
+ /**
45
+ * When `true` (default), performs a second best-effort pass pushing the assembled quorum `cert_0`
46
+ * and `genesis_sigs` back to all witnesses so every station caches full quorum `cert_0`.
47
+ */
48
+ readonly propagateCert0?: boolean;
49
+ }
50
+ export interface CoordinateInitGenesisResult {
51
+ readonly cert0: EpochGenesisCert;
52
+ readonly cert0Bytes: Uint8Array;
53
+ readonly cert0Hex: string;
54
+ readonly genesisDigest: Uint8Array;
55
+ readonly syncedLedgerSeq: number;
56
+ readonly syncedAtTs: bigint;
57
+ readonly verifiedWitnessIndices: number[];
58
+ readonly propagatedCount: number;
59
+ readonly failures: readonly WitnessCallFailure[];
60
+ }
61
+ /**
62
+ * Coordinate `POST /init-genesis` across a pocket's witnesses, cryptographically verifying each
63
+ * `"SMW1_GENESIS"` signature against the locally computed digest and pinned `witnesses` set,
64
+ * assembling canonical `cert_0`, and optionally propagating quorum `cert_0` back to all witnesses.
65
+ */
66
+ export declare function coordinateInitGenesis(params: CoordinateInitGenesisParams): Promise<CoordinateInitGenesisResult>;
67
+ export interface CoordinateRefreshFreshnessParams {
68
+ readonly witnessClients: readonly WitnessClientInput[];
69
+ readonly witnessClientOptions?: WitnessClientOptions;
70
+ readonly networkHint: NetworkHint;
71
+ readonly networkPassphrase?: string;
72
+ readonly vaultId: string | WireAddress | Uint8Array;
73
+ readonly pocketId: number;
74
+ readonly epoch: number;
75
+ readonly witnesses: readonly (Uint8Array | string)[];
76
+ readonly witnessThreshold: number;
77
+ readonly targetLedgerSeq: number;
78
+ readonly targetTs: bigint | number;
79
+ /** When `true` (default), pushes the assembled quorum `fresh_cert` back to all witnesses. */
80
+ readonly propagateFreshCert?: boolean;
81
+ }
82
+ export interface CoordinateRefreshFreshnessResult {
83
+ readonly freshCert: StoredFreshCertDto;
84
+ readonly freshDigest: Uint8Array;
85
+ readonly syncedLedgerSeq: number;
86
+ readonly syncedAtTs: bigint;
87
+ readonly verifiedWitnessIndices: number[];
88
+ readonly propagatedCount: number;
89
+ readonly failures: readonly WitnessCallFailure[];
90
+ }
91
+ /**
92
+ * Coordinate `POST /refresh-freshness` across a pocket's witnesses, cryptographically verifying
93
+ * each `"SMW1_FRESH"` signature, assembling a quorum `StoredFreshCertDto` (directly passable to
94
+ * `OfflineWallet.refreshAnchor`), and optionally propagating it back to all witnesses.
95
+ */
96
+ export declare function coordinateRefreshFreshness(params: CoordinateRefreshFreshnessParams): Promise<CoordinateRefreshFreshnessResult>;
97
+ export interface CoordinateCloseCooperativeParams {
98
+ readonly witnessClients: readonly WitnessClientInput[];
99
+ readonly witnessClientOptions?: WitnessClientOptions;
100
+ readonly networkHint: NetworkHint;
101
+ readonly networkPassphrase?: string;
102
+ readonly vaultId: string | WireAddress | Uint8Array;
103
+ readonly pocketId: number;
104
+ readonly epoch: number;
105
+ readonly witnesses: readonly (Uint8Array | string)[];
106
+ readonly witnessThreshold: number;
107
+ /** Optional `G...` or `C...` owner StrKey forwarded to witnesses. */
108
+ readonly owner?: WireAddress | string;
109
+ /** Classic `G...` owner 32-byte Ed25519 secret key (automatically signs `"SMW1_CLOSE"`). */
110
+ readonly ownerSecretKey?: Uint8Array;
111
+ /** Pre-computed 64-byte Ed25519 signature by classic `G...` owner over `"SMW1_CLOSE"`. */
112
+ readonly ownerSig?: Uint8Array | string;
113
+ /** Smart-account `C...` pocket device 32-byte Ed25519 secret key (automatically signs `"SMW1_CLOSE"`). */
114
+ readonly deviceSecretKey?: Uint8Array;
115
+ /** Pre-computed 64-byte Ed25519 signature by pocket device key over `"SMW1_CLOSE"`. */
116
+ readonly deviceSig?: Uint8Array | string;
117
+ /** Optional `SMESHC1...` latest certificate to sync lagging witnesses before closing. */
118
+ readonly latestCert?: string;
119
+ }
120
+ export interface CoordinateCloseCooperativeResult {
121
+ readonly closeDigest: Uint8Array;
122
+ /** Strictly ascending unique witness signatures ready for `buildClosePocketCooperativeOp`. */
123
+ readonly witnessSigs: readonly IndexedWitnessSignature[];
124
+ readonly verifiedWitnessIndices: number[];
125
+ readonly failures: readonly WitnessCallFailure[];
126
+ }
127
+ /**
128
+ * Coordinate `POST /close-cooperative` across a pocket's witnesses, verifying each `"SMW1_CLOSE"`
129
+ * witness signature and returning sorted `witnessSigs` ready for `buildClosePocketCooperativeOp`.
130
+ */
131
+ export declare function coordinateCloseCooperative(params: CoordinateCloseCooperativeParams): Promise<CoordinateCloseCooperativeResult>;