@wasit-dev/core 0.1.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,70 @@
1
+ /**
2
+ * The result shape shared by every conformance check, across protocols.
3
+ */
4
+ import { type CheckError } from "./errors.js";
5
+ export interface CheckResult {
6
+ /** Stable catalogue identifier, e.g. "MPP-11". Must match docs/CHECKS.md. */
7
+ id: string;
8
+ name: string;
9
+ /** False when the check ran and the target did not conform. */
10
+ pass: boolean;
11
+ detail: string;
12
+ /**
13
+ * True when the check did not run. A skipped check is neither a pass nor a
14
+ * failure: `pass` is false so it can never be counted as conformance, and
15
+ * reporters must render it separately rather than as a defect.
16
+ */
17
+ skipped?: boolean;
18
+ /** Why the check was skipped. Required whenever `skipped` is true. */
19
+ skipReason?: string;
20
+ /**
21
+ * True when running this check permanently alters the target's state.
22
+ * Destructive checks are skipped unless the operator explicitly opts in,
23
+ * and may only be run against a target the operator owns or is authorised
24
+ * to test. See docs/CHECKS.md and SECURITY.md.
25
+ */
26
+ destructive?: boolean;
27
+ /**
28
+ * Set when the check produced no verdict about the target — it could not
29
+ * connect, or the run is misconfigured, or the harness itself failed.
30
+ * `pass` is false so an errored check can never be counted as conformance,
31
+ * but reporters must not present it as a defect in the target.
32
+ */
33
+ error?: CheckError;
34
+ }
35
+ /** How a single result should be rendered and counted. */
36
+ export type CheckStatus = "PASS" | "FAIL" | "ERROR" | "SKIP";
37
+ /**
38
+ * Classifies one result.
39
+ *
40
+ * Order matters: a skipped check never ran, and an errored check produced no
41
+ * verdict, so both are decided before `pass` is consulted at all.
42
+ */
43
+ export declare function checkStatus(result: CheckResult): CheckStatus;
44
+ export interface RunSummary {
45
+ readonly passed: number;
46
+ readonly failed: number;
47
+ readonly errored: number;
48
+ readonly skipped: number;
49
+ /** 0 = everything conformed, 1 = conformance failure, 2 = no verdict. */
50
+ readonly exitCode: 0 | 1 | 2;
51
+ }
52
+ /**
53
+ * Reduces a run to its counts and outcome.
54
+ *
55
+ * Lives in core rather than in a front end so the CLI's exit code and the MCP
56
+ * server's reported outcome can never disagree about the same results.
57
+ */
58
+ export declare function summarize(results: CheckResult[]): RunSummary;
59
+ /** Builds the result for a destructive check that was not opted into. */
60
+ export declare function skippedDestructive(id: string, name: string, reason: string): CheckResult;
61
+ /**
62
+ * Builds the result for a check that threw.
63
+ *
64
+ * A malformed response becomes an ordinary failure — the target answered and
65
+ * the answer was wrong. Everything else becomes an errored result, which is
66
+ * reported and exit-coded separately from conformance failures.
67
+ */
68
+ export declare function errored(id: string, name: string, error: unknown): CheckResult;
69
+ /** Builds the result for a check that was not run, for a non-destructive reason. */
70
+ export declare function skipped(id: string, name: string, reason: string): CheckResult;
package/dist/check.js ADDED
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The result shape shared by every conformance check, across protocols.
3
+ */
4
+ import { classifyCheckError } from "./errors.js";
5
+ /**
6
+ * Classifies one result.
7
+ *
8
+ * Order matters: a skipped check never ran, and an errored check produced no
9
+ * verdict, so both are decided before `pass` is consulted at all.
10
+ */
11
+ export function checkStatus(result) {
12
+ if (result.skipped)
13
+ return "SKIP";
14
+ if (result.error !== undefined)
15
+ return "ERROR";
16
+ return result.pass ? "PASS" : "FAIL";
17
+ }
18
+ /**
19
+ * Reduces a run to its counts and outcome.
20
+ *
21
+ * Lives in core rather than in a front end so the CLI's exit code and the MCP
22
+ * server's reported outcome can never disagree about the same results.
23
+ */
24
+ export function summarize(results) {
25
+ let passed = 0;
26
+ let failed = 0;
27
+ let errored = 0;
28
+ let skipped = 0;
29
+ for (const result of results) {
30
+ switch (checkStatus(result)) {
31
+ case "PASS":
32
+ passed += 1;
33
+ break;
34
+ case "FAIL":
35
+ failed += 1;
36
+ break;
37
+ case "ERROR":
38
+ errored += 1;
39
+ break;
40
+ case "SKIP":
41
+ skipped += 1;
42
+ break;
43
+ }
44
+ }
45
+ // A real finding outranks a missing one, so a run with both exits 1.
46
+ const exitCode = failed > 0 ? 1 : errored > 0 ? 2 : 0;
47
+ return { passed, failed, errored, skipped, exitCode };
48
+ }
49
+ /** Builds the result for a destructive check that was not opted into. */
50
+ export function skippedDestructive(id, name, reason) {
51
+ return {
52
+ id,
53
+ name,
54
+ pass: false,
55
+ skipped: true,
56
+ destructive: true,
57
+ skipReason: reason,
58
+ detail: `Skipped (destructive): ${reason}`,
59
+ };
60
+ }
61
+ /**
62
+ * Builds the result for a check that threw.
63
+ *
64
+ * A malformed response becomes an ordinary failure — the target answered and
65
+ * the answer was wrong. Everything else becomes an errored result, which is
66
+ * reported and exit-coded separately from conformance failures.
67
+ */
68
+ export function errored(id, name, error) {
69
+ const classified = classifyCheckError(error);
70
+ if (classified.kind === "malformed-response") {
71
+ return {
72
+ id,
73
+ name,
74
+ pass: false,
75
+ detail: `Connected, but the response did not conform: ${classified.message}`,
76
+ };
77
+ }
78
+ return {
79
+ id,
80
+ name,
81
+ pass: false,
82
+ error: classified,
83
+ detail: `Check could not run (${classified.kind}): ${classified.message}`,
84
+ };
85
+ }
86
+ /** Builds the result for a check that was not run, for a non-destructive reason. */
87
+ export function skipped(id, name, reason) {
88
+ return {
89
+ id,
90
+ name,
91
+ pass: false,
92
+ skipped: true,
93
+ skipReason: reason,
94
+ detail: `Skipped: ${reason}`,
95
+ };
96
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * Error taxonomy for conformance checks.
3
+ *
4
+ * The distinction that matters to an operator is whether a check produced a
5
+ * verdict about the target at all. A malformed response IS a verdict: the
6
+ * service answered, and what it answered did not conform. An unreachable host,
7
+ * a bad RPC endpoint, or a misconfigured run produce no verdict, and reporting
8
+ * those as conformance failures tells an operator their service is broken when
9
+ * it may be perfectly correct.
10
+ *
11
+ * Errors are classified where they are thrown, not where they are caught.
12
+ * Third-party throw sites (the mppx challenge parser, the Stellar SDK) have no
13
+ * documented error types, so sniffing at the catch site would be guesswork;
14
+ * the call site knows what it was doing and wraps accordingly.
15
+ */
16
+ /** Why a check could not produce a verdict about the target. */
17
+ export type CheckErrorKind = "unreachable" | "configuration" | "harness";
18
+ /** A check that did not run. Never a statement about the target's conformance. */
19
+ export interface CheckError {
20
+ readonly kind: CheckErrorKind;
21
+ readonly message: string;
22
+ /** Transport-level code, when one was recoverable, e.g. "ECONNREFUSED". */
23
+ readonly code?: string;
24
+ }
25
+ /** A check that ran: the target answered, and the answer was wrong. */
26
+ export interface MalformedResponseFinding {
27
+ readonly kind: "malformed-response";
28
+ readonly message: string;
29
+ }
30
+ export type ClassifiedError = CheckError | MalformedResponseFinding;
31
+ /**
32
+ * The target was reached and replied, but the reply violates the spec.
33
+ * This is a conformance finding, not an operational error.
34
+ */
35
+ export declare class MalformedResponseError extends Error {
36
+ constructor(message: string);
37
+ }
38
+ /** The run itself is misconfigured. Nothing can be concluded about the target. */
39
+ export declare class ConfigurationError extends Error {
40
+ constructor(message: string);
41
+ }
42
+ /** No HTTP conversation took place: the connection never succeeded. */
43
+ export declare class TargetUnreachableError extends Error {
44
+ readonly target: string;
45
+ readonly code: string | undefined;
46
+ /** The original throw, kept for diagnostics without relying on Error.cause. */
47
+ readonly reason: unknown;
48
+ constructor(target: string, reason: unknown);
49
+ }
50
+ /**
51
+ * Rejects anything that is not an absolute HTTP(S) URL.
52
+ *
53
+ * Exported because the suite validates the target once up front: a bad URL is
54
+ * wrong for every check, and reporting it per check buries the one real cause
55
+ * under N identical copies.
56
+ */
57
+ export declare function assertHttpUrl(target: string): void;
58
+ /**
59
+ * Performs a request against the target, distinguishing "never connected"
60
+ * from every other failure. Use this instead of bare `fetch` for anything
61
+ * addressed at the service under test.
62
+ */
63
+ export declare function fetchTarget(target: string, init?: Parameters<typeof fetch>[1]): Promise<Awaited<ReturnType<typeof fetch>>>;
64
+ /** Maps a thrown value onto the taxonomy. */
65
+ export declare function classifyCheckError(error: unknown): ClassifiedError;
package/dist/errors.js ADDED
@@ -0,0 +1,127 @@
1
+ /**
2
+ * Error taxonomy for conformance checks.
3
+ *
4
+ * The distinction that matters to an operator is whether a check produced a
5
+ * verdict about the target at all. A malformed response IS a verdict: the
6
+ * service answered, and what it answered did not conform. An unreachable host,
7
+ * a bad RPC endpoint, or a misconfigured run produce no verdict, and reporting
8
+ * those as conformance failures tells an operator their service is broken when
9
+ * it may be perfectly correct.
10
+ *
11
+ * Errors are classified where they are thrown, not where they are caught.
12
+ * Third-party throw sites (the mppx challenge parser, the Stellar SDK) have no
13
+ * documented error types, so sniffing at the catch site would be guesswork;
14
+ * the call site knows what it was doing and wraps accordingly.
15
+ */
16
+ /**
17
+ * The target was reached and replied, but the reply violates the spec.
18
+ * This is a conformance finding, not an operational error.
19
+ */
20
+ export class MalformedResponseError extends Error {
21
+ constructor(message) {
22
+ super(message);
23
+ this.name = "MalformedResponseError";
24
+ }
25
+ }
26
+ /** The run itself is misconfigured. Nothing can be concluded about the target. */
27
+ export class ConfigurationError extends Error {
28
+ constructor(message) {
29
+ super(message);
30
+ this.name = "ConfigurationError";
31
+ }
32
+ }
33
+ /** No HTTP conversation took place: the connection never succeeded. */
34
+ export class TargetUnreachableError extends Error {
35
+ target;
36
+ code;
37
+ /** The original throw, kept for diagnostics without relying on Error.cause. */
38
+ reason;
39
+ constructor(target, reason) {
40
+ const code = connectionErrorCode(reason);
41
+ const detail = reason instanceof Error ? reason.message : String(reason);
42
+ super(`Could not connect to ${target}${code ? ` (${code})` : ""}: ${detail}`);
43
+ this.name = "TargetUnreachableError";
44
+ this.target = target;
45
+ this.code = code;
46
+ this.reason = reason;
47
+ }
48
+ }
49
+ /**
50
+ * Walks the cause chain for a transport error code.
51
+ *
52
+ * Node's fetch reports every transport failure as `TypeError: fetch failed`
53
+ * and hangs the real error off `.cause`, which is where `ECONNREFUSED`,
54
+ * `ENOTFOUND` and the TLS codes actually live.
55
+ */
56
+ function connectionErrorCode(reason) {
57
+ const seen = new Set();
58
+ let current = reason;
59
+ while (current !== null && current !== undefined && !seen.has(current)) {
60
+ seen.add(current);
61
+ const record = current;
62
+ if (typeof record.code === "string")
63
+ return record.code;
64
+ current = record.cause;
65
+ }
66
+ return undefined;
67
+ }
68
+ /**
69
+ * Rejects anything that is not an absolute HTTP(S) URL.
70
+ *
71
+ * Exported because the suite validates the target once up front: a bad URL is
72
+ * wrong for every check, and reporting it per check buries the one real cause
73
+ * under N identical copies.
74
+ */
75
+ export function assertHttpUrl(target) {
76
+ let url;
77
+ try {
78
+ url = new URL(target);
79
+ }
80
+ catch {
81
+ throw new ConfigurationError(`"${target}" is not a valid absolute URL. Include the scheme, ` +
82
+ `e.g. http://localhost:3003/data.`);
83
+ }
84
+ // A bare host:port parses cleanly — "localhost:3003/data" becomes scheme
85
+ // "localhost:" with path "3003/data" — so a valid-URL check alone lets it
86
+ // through to fetch, where it resurfaces as a transport failure and gets
87
+ // misreported as the target being unreachable.
88
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
89
+ throw new ConfigurationError(`"${target}" is not an HTTP(S) URL — it parses with scheme ` +
90
+ `"${url.protocol}". If you meant a local service, write the scheme ` +
91
+ `explicitly, e.g. http://${target}.`);
92
+ }
93
+ }
94
+ /**
95
+ * Performs a request against the target, distinguishing "never connected"
96
+ * from every other failure. Use this instead of bare `fetch` for anything
97
+ * addressed at the service under test.
98
+ */
99
+ export async function fetchTarget(target, init) {
100
+ assertHttpUrl(target);
101
+ try {
102
+ return await fetch(target, init);
103
+ }
104
+ catch (error) {
105
+ throw new TargetUnreachableError(target, error);
106
+ }
107
+ }
108
+ /** Maps a thrown value onto the taxonomy. */
109
+ export function classifyCheckError(error) {
110
+ if (error instanceof MalformedResponseError) {
111
+ return { kind: "malformed-response", message: error.message };
112
+ }
113
+ if (error instanceof TargetUnreachableError) {
114
+ return {
115
+ kind: "unreachable",
116
+ message: error.message,
117
+ ...(error.code ? { code: error.code } : {}),
118
+ };
119
+ }
120
+ if (error instanceof ConfigurationError) {
121
+ return { kind: "configuration", message: error.message };
122
+ }
123
+ return {
124
+ kind: "harness",
125
+ message: error instanceof Error ? error.message : String(error),
126
+ };
127
+ }
@@ -0,0 +1,8 @@
1
+ export { checkStatus, errored, skipped, skippedDestructive, summarize } from "./check.js";
2
+ export type { CheckResult, CheckStatus, RunSummary } from "./check.js";
3
+ export * from "./errors.js";
4
+ export * from "./x402/simulator.js";
5
+ export * from "./mpp/channel.js";
6
+ export * from "./mpp/charge.js";
7
+ export * from "./mpp/charge-suite.js";
8
+ export * from "./mpp/suite.js";
package/dist/index.js ADDED
@@ -0,0 +1,7 @@
1
+ export { checkStatus, errored, skipped, skippedDestructive, summarize } from "./check.js";
2
+ export * from "./errors.js";
3
+ export * from "./x402/simulator.js";
4
+ export * from "./mpp/channel.js";
5
+ export * from "./mpp/charge.js";
6
+ export * from "./mpp/charge-suite.js";
7
+ export * from "./mpp/suite.js";
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Manual commitment signing for the one-way-channel contract.
3
+ *
4
+ * The official client SDK always signs against its own local baseline, which
5
+ * makes a fresh client single-use per channel. Conformance checks need to target
6
+ * an explicit cumulative amount — including deliberately invalid ones — so this
7
+ * module reproduces the server's own commitment-derivation path.
8
+ *
9
+ * Mirrors `verifyCommitmentSignature` in @stellar/mpp channel/server: simulate
10
+ * `prepare_commitment(amount)` read-only, take the returned Bytes, and sign them
11
+ * with the raw ed25519 commitment key. No transaction is submitted, no fee paid.
12
+ */
13
+ import { Keypair } from "@stellar/stellar-sdk";
14
+ export declare class CommitmentSimulationError extends Error {
15
+ readonly cause?: unknown;
16
+ constructor(message: string, cause?: unknown);
17
+ }
18
+ export interface PrepareCommitmentParams {
19
+ /** Channel contract address (C...). */
20
+ readonly channelContract: string;
21
+ /** Cumulative amount in base units. */
22
+ readonly amount: bigint;
23
+ readonly networkPassphrase: string;
24
+ readonly rpcUrl: string;
25
+ readonly simulationTimeoutMs?: number;
26
+ }
27
+ export interface SignChannelCommitmentParams extends PrepareCommitmentParams {
28
+ /** Raw ed25519 seed as a 64-char hex string (NOT a Stellar S... secret). */
29
+ readonly commitmentSecretHex: string;
30
+ }
31
+ /**
32
+ * Builds a Keypair from the raw ed25519 seed used for channel commitments.
33
+ * This is deliberately not a Stellar secret key: the contract verifies the
34
+ * signature with `env.crypto().ed25519_verify`.
35
+ */
36
+ export declare function commitmentKeypairFromHex(secretHex: string): Keypair;
37
+ /**
38
+ * The exact amount the server will accept next, given the cumulative it
39
+ * currently holds and the price of this request.
40
+ *
41
+ * Server rule (cumulativeMonotonicityError):
42
+ * commitmentAmount > previousCumulative
43
+ * commitmentAmount >= previousCumulative + requestedAmount
44
+ *
45
+ * Since requestedAmount is always positive, the second condition subsumes the
46
+ * first, and the minimum accepted value is their sum.
47
+ */
48
+ export declare function nextValidCumulative(previousCumulative: bigint, requestedAmount: bigint): bigint;
49
+ /**
50
+ * Reads the channel contract's `withdrawn` getter: the cumulative amount already
51
+ * paid out to the recipient. After a close this must equal the commitment that
52
+ * was closed with.
53
+ */
54
+ export declare function readChannelWithdrawn(parameters: {
55
+ readonly channelContract: string;
56
+ readonly networkPassphrase: string;
57
+ readonly rpcUrl: string;
58
+ readonly simulationTimeoutMs?: number;
59
+ }): Promise<bigint>;
60
+ /**
61
+ * Simulates `prepare_commitment(amount)` and returns the bytes to be signed.
62
+ */
63
+ export declare function prepareCommitmentBytes(params: PrepareCommitmentParams): Promise<Buffer>;
64
+ /**
65
+ * Signs a channel commitment for an explicit cumulative amount.
66
+ *
67
+ * @returns The raw 64-byte ed25519 signature, hex-encoded, ready to be placed
68
+ * in the credential payload's `signature` field.
69
+ */
70
+ export declare function signChannelCommitment(params: SignChannelCommitmentParams): Promise<string>;
@@ -0,0 +1,195 @@
1
+ /**
2
+ * Manual commitment signing for the one-way-channel contract.
3
+ *
4
+ * The official client SDK always signs against its own local baseline, which
5
+ * makes a fresh client single-use per channel. Conformance checks need to target
6
+ * an explicit cumulative amount — including deliberately invalid ones — so this
7
+ * module reproduces the server's own commitment-derivation path.
8
+ *
9
+ * Mirrors `verifyCommitmentSignature` in @stellar/mpp channel/server: simulate
10
+ * `prepare_commitment(amount)` read-only, take the returned Bytes, and sign them
11
+ * with the raw ed25519 commitment key. No transaction is submitted, no fee paid.
12
+ */
13
+ import { Account, Contract, Keypair, TransactionBuilder, nativeToScVal, rpc, scValToNative, } from "@stellar/stellar-sdk";
14
+ /**
15
+ * Format-valid all-zero account used purely as a simulation source. It need not
16
+ * exist on the ledger: read-only simulation never touches the source account.
17
+ * Matches ALL_ZEROS in @stellar/mpp constants.
18
+ */
19
+ const SIMULATION_SOURCE_ACCOUNT = "GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF";
20
+ /** Base fee in stroops. Never charged — the transaction is only simulated. */
21
+ const SIMULATION_FEE = "100";
22
+ const DEFAULT_SIMULATION_TIMEOUT_MS = 10_000;
23
+ const COMMITMENT_SEED_BYTES = 32;
24
+ const ED25519_SIGNATURE_BYTES = 64;
25
+ export class CommitmentSimulationError extends Error {
26
+ cause;
27
+ constructor(message, cause) {
28
+ super(message);
29
+ this.cause = cause;
30
+ this.name = "CommitmentSimulationError";
31
+ }
32
+ }
33
+ /**
34
+ * Builds a Keypair from the raw ed25519 seed used for channel commitments.
35
+ * This is deliberately not a Stellar secret key: the contract verifies the
36
+ * signature with `env.crypto().ed25519_verify`.
37
+ */
38
+ export function commitmentKeypairFromHex(secretHex) {
39
+ const seed = Buffer.from(secretHex, "hex");
40
+ if (seed.length !== COMMITMENT_SEED_BYTES) {
41
+ throw new CommitmentSimulationError(`Commitment secret must decode to ${COMMITMENT_SEED_BYTES} bytes, got ${seed.length}.`);
42
+ }
43
+ return Keypair.fromRawEd25519Seed(seed);
44
+ }
45
+ /**
46
+ * The exact amount the server will accept next, given the cumulative it
47
+ * currently holds and the price of this request.
48
+ *
49
+ * Server rule (cumulativeMonotonicityError):
50
+ * commitmentAmount > previousCumulative
51
+ * commitmentAmount >= previousCumulative + requestedAmount
52
+ *
53
+ * Since requestedAmount is always positive, the second condition subsumes the
54
+ * first, and the minimum accepted value is their sum.
55
+ */
56
+ export function nextValidCumulative(previousCumulative, requestedAmount) {
57
+ return previousCumulative + requestedAmount;
58
+ }
59
+ async function withTimeout(promise, timeoutMs, label) {
60
+ let timer;
61
+ try {
62
+ return await Promise.race([
63
+ promise,
64
+ new Promise((_resolve, reject) => {
65
+ timer = setTimeout(() => reject(new CommitmentSimulationError(`${label} timed out after ${timeoutMs}ms.`)), timeoutMs);
66
+ }),
67
+ ]);
68
+ }
69
+ finally {
70
+ if (timer !== undefined)
71
+ clearTimeout(timer);
72
+ }
73
+ }
74
+ /**
75
+ * Simulates a read-only contract call and returns its raw return value.
76
+ *
77
+ * Read-only simulation costs nothing and touches no ledger state, so the source
78
+ * account need only be well-formed, not funded or even existent.
79
+ */
80
+ async function simulateRead(parameters) {
81
+ const { contractId, method, args, networkPassphrase, rpcUrl, simulationTimeoutMs } = parameters;
82
+ const server = new rpc.Server(rpcUrl);
83
+ const contract = new Contract(contractId);
84
+ const source = new Account(SIMULATION_SOURCE_ACCOUNT, "0");
85
+ const transaction = new TransactionBuilder(source, {
86
+ fee: SIMULATION_FEE,
87
+ networkPassphrase,
88
+ })
89
+ .addOperation(contract.call(method, ...args))
90
+ .setTimeout(Math.ceil(simulationTimeoutMs / 1000))
91
+ .build();
92
+ let simulation;
93
+ try {
94
+ simulation = await withTimeout(server.simulateTransaction(transaction), simulationTimeoutMs, `${method} simulation`);
95
+ }
96
+ catch (error) {
97
+ if (error instanceof CommitmentSimulationError)
98
+ throw error;
99
+ throw new CommitmentSimulationError(`${method} simulation failed at transport level: ${error instanceof Error ? error.message : String(error)}`, error);
100
+ }
101
+ if (rpc.Api.isSimulationError(simulation)) {
102
+ throw new CommitmentSimulationError(`${method} simulation returned an error: ${simulation.error}`);
103
+ }
104
+ // Checked BEFORE isSimulationSuccess: the restore response type structurally
105
+ // extends the success type, so a success check alone would swallow it.
106
+ if (rpc.Api.isSimulationRestore(simulation)) {
107
+ throw new CommitmentSimulationError(`Contract ${contractId} requires a storage restore before it can be read. ` +
108
+ "Extend its TTL first.");
109
+ }
110
+ if (!rpc.Api.isSimulationSuccess(simulation)) {
111
+ throw new CommitmentSimulationError(`${method} simulation returned an unrecognised response shape.`);
112
+ }
113
+ const returnValue = simulation.result?.retval;
114
+ if (!returnValue) {
115
+ throw new CommitmentSimulationError(`${method} returned no value.`);
116
+ }
117
+ return returnValue;
118
+ }
119
+ /**
120
+ * Reads the channel contract's `withdrawn` getter: the cumulative amount already
121
+ * paid out to the recipient. After a close this must equal the commitment that
122
+ * was closed with.
123
+ */
124
+ export async function readChannelWithdrawn(parameters) {
125
+ const value = await simulateRead({
126
+ contractId: parameters.channelContract,
127
+ method: "withdrawn",
128
+ args: [],
129
+ networkPassphrase: parameters.networkPassphrase,
130
+ rpcUrl: parameters.rpcUrl,
131
+ simulationTimeoutMs: parameters.simulationTimeoutMs ?? DEFAULT_SIMULATION_TIMEOUT_MS,
132
+ });
133
+ return BigInt(scValToNative(value));
134
+ }
135
+ /**
136
+ * Simulates `prepare_commitment(amount)` and returns the bytes to be signed.
137
+ */
138
+ export async function prepareCommitmentBytes(params) {
139
+ const { channelContract, amount, networkPassphrase, rpcUrl, simulationTimeoutMs = DEFAULT_SIMULATION_TIMEOUT_MS, } = params;
140
+ const server = new rpc.Server(rpcUrl);
141
+ const contract = new Contract(channelContract);
142
+ const operation = contract.call("prepare_commitment", nativeToScVal(amount, { type: "i128" }));
143
+ const source = new Account(SIMULATION_SOURCE_ACCOUNT, "0");
144
+ const transaction = new TransactionBuilder(source, {
145
+ fee: SIMULATION_FEE,
146
+ networkPassphrase,
147
+ })
148
+ .addOperation(operation)
149
+ .setTimeout(Math.ceil(simulationTimeoutMs / 1000))
150
+ .build();
151
+ let simulation;
152
+ try {
153
+ simulation = await withTimeout(server.simulateTransaction(transaction), simulationTimeoutMs, "prepare_commitment simulation");
154
+ }
155
+ catch (error) {
156
+ if (error instanceof CommitmentSimulationError)
157
+ throw error;
158
+ throw new CommitmentSimulationError(`prepare_commitment simulation failed at transport level: ${error instanceof Error ? error.message : String(error)}`, error);
159
+ }
160
+ if (rpc.Api.isSimulationError(simulation)) {
161
+ throw new CommitmentSimulationError(`prepare_commitment simulation returned an error: ${simulation.error}`);
162
+ }
163
+ // Checked BEFORE isSimulationSuccess: the restore response type structurally
164
+ // extends the success type, so a success check alone would swallow it. A
165
+ // restore preamble means the channel contract's storage has expired; Wasit
166
+ // reports that rather than silently restoring someone else's contract.
167
+ if (rpc.Api.isSimulationRestore(simulation)) {
168
+ throw new CommitmentSimulationError("Channel contract requires a storage restore before it can be simulated. " +
169
+ "Extend the contract's TTL before running channel checks.");
170
+ }
171
+ if (!rpc.Api.isSimulationSuccess(simulation)) {
172
+ throw new CommitmentSimulationError("prepare_commitment simulation returned an unrecognised response shape.");
173
+ }
174
+ const returnValue = simulation.result?.retval;
175
+ if (!returnValue) {
176
+ throw new CommitmentSimulationError("prepare_commitment returned no value.");
177
+ }
178
+ return Buffer.from(returnValue.bytes());
179
+ }
180
+ /**
181
+ * Signs a channel commitment for an explicit cumulative amount.
182
+ *
183
+ * @returns The raw 64-byte ed25519 signature, hex-encoded, ready to be placed
184
+ * in the credential payload's `signature` field.
185
+ */
186
+ export async function signChannelCommitment(params) {
187
+ const { commitmentSecretHex, ...prepareParams } = params;
188
+ const keypair = commitmentKeypairFromHex(commitmentSecretHex);
189
+ const commitmentBytes = await prepareCommitmentBytes(prepareParams);
190
+ const signature = keypair.sign(commitmentBytes);
191
+ if (signature.length !== ED25519_SIGNATURE_BYTES) {
192
+ throw new CommitmentSimulationError(`Expected a ${ED25519_SIGNATURE_BYTES}-byte signature, got ${signature.length}.`);
193
+ }
194
+ return signature.toString("hex");
195
+ }