@openzeppelin/miden-multisig-client 0.16.1 → 0.16.2

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.
Files changed (84) hide show
  1. package/README.md +48 -4
  2. package/dist/client.d.ts +4 -0
  3. package/dist/client.d.ts.map +1 -1
  4. package/dist/client.js +5 -2
  5. package/dist/client.js.map +1 -1
  6. package/dist/client.test.js +7 -2
  7. package/dist/client.test.js.map +1 -1
  8. package/dist/index.d.ts +1 -0
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js.map +1 -1
  11. package/dist/multisig.d.ts +3 -1
  12. package/dist/multisig.d.ts.map +1 -1
  13. package/dist/multisig.js +18 -9
  14. package/dist/multisig.js.map +1 -1
  15. package/dist/multisig.test.js +1 -0
  16. package/dist/multisig.test.js.map +1 -1
  17. package/dist/prover/errors.d.ts +5 -0
  18. package/dist/prover/errors.d.ts.map +1 -1
  19. package/dist/prover/errors.js +7 -155
  20. package/dist/prover/errors.js.map +1 -1
  21. package/dist/prover/errors.test.js +5 -0
  22. package/dist/prover/errors.test.js.map +1 -1
  23. package/dist/prover/retry.d.ts +1 -6
  24. package/dist/prover/retry.d.ts.map +1 -1
  25. package/dist/prover/retry.js +5 -28
  26. package/dist/prover/retry.js.map +1 -1
  27. package/dist/prover/retry.test.js +1 -1
  28. package/dist/prover/retry.test.js.map +1 -1
  29. package/dist/prover/workflow.d.ts +1 -1
  30. package/dist/prover/workflow.d.ts.map +1 -1
  31. package/dist/prover/workflow.test.js +23 -0
  32. package/dist/prover/workflow.test.js.map +1 -1
  33. package/dist/retry/classify.d.ts +16 -0
  34. package/dist/retry/classify.d.ts.map +1 -0
  35. package/dist/retry/classify.js +187 -0
  36. package/dist/retry/classify.js.map +1 -0
  37. package/dist/retry/runtime.d.ts +13 -0
  38. package/dist/retry/runtime.d.ts.map +1 -0
  39. package/dist/retry/runtime.js +33 -0
  40. package/dist/retry/runtime.js.map +1 -0
  41. package/dist/rpc/config.d.ts +11 -0
  42. package/dist/rpc/config.d.ts.map +1 -0
  43. package/dist/rpc/config.js +17 -0
  44. package/dist/rpc/config.js.map +1 -0
  45. package/dist/rpc/config.test.d.ts +2 -0
  46. package/dist/rpc/config.test.d.ts.map +1 -0
  47. package/dist/rpc/config.test.js +24 -0
  48. package/dist/rpc/config.test.js.map +1 -0
  49. package/dist/rpc/errors.d.ts +2 -0
  50. package/dist/rpc/errors.d.ts.map +1 -0
  51. package/dist/rpc/errors.js +11 -0
  52. package/dist/rpc/errors.js.map +1 -0
  53. package/dist/rpc/errors.test.d.ts +2 -0
  54. package/dist/rpc/errors.test.d.ts.map +1 -0
  55. package/dist/rpc/errors.test.js +34 -0
  56. package/dist/rpc/errors.test.js.map +1 -0
  57. package/dist/rpc/retry.d.ts +4 -0
  58. package/dist/rpc/retry.d.ts.map +1 -0
  59. package/dist/rpc/retry.js +6 -0
  60. package/dist/rpc/retry.js.map +1 -0
  61. package/dist/rpc/retry.test.d.ts +2 -0
  62. package/dist/rpc/retry.test.d.ts.map +1 -0
  63. package/dist/rpc/retry.test.js +98 -0
  64. package/dist/rpc/retry.test.js.map +1 -0
  65. package/package.json +2 -2
  66. package/src/client.test.ts +8 -2
  67. package/src/client.ts +11 -0
  68. package/src/index.ts +1 -0
  69. package/src/multisig.test.ts +1 -0
  70. package/src/multisig.ts +39 -8
  71. package/src/prover/errors.test.ts +8 -0
  72. package/src/prover/errors.ts +7 -175
  73. package/src/prover/retry.test.ts +1 -1
  74. package/src/prover/retry.ts +10 -35
  75. package/src/prover/workflow.test.ts +32 -1
  76. package/src/prover/workflow.ts +1 -1
  77. package/src/retry/classify.ts +220 -0
  78. package/src/retry/runtime.ts +45 -0
  79. package/src/rpc/config.test.ts +45 -0
  80. package/src/rpc/config.ts +30 -0
  81. package/src/rpc/errors.test.ts +69 -0
  82. package/src/rpc/errors.ts +12 -0
  83. package/src/rpc/retry.test.ts +144 -0
  84. package/src/rpc/retry.ts +12 -0
@@ -1,178 +1,10 @@
1
- type ErrorRecord = {
2
- cause?: unknown;
3
- code?: unknown;
4
- status?: unknown;
5
- statusCode?: unknown;
6
- message?: unknown;
7
- };
8
-
9
- type StructuredEvidence = 'transient' | 'permanent' | 'indeterminate';
10
-
11
- const TRANSIENT_GRPC = new Set([
12
- 'cancelled',
13
- 'canceled',
14
- 'deadlineexceeded',
15
- 'unavailable',
16
- 'resourceexhausted',
17
- ]);
18
-
19
- const PERMANENT_GRPC = new Set([
20
- 'invalidargument',
21
- 'failedprecondition',
22
- 'permissiondenied',
23
- 'unauthenticated',
24
- 'notfound',
25
- 'alreadyexists',
26
- 'outofrange',
27
- 'unimplemented',
28
- 'aborted',
29
- 'internal',
30
- 'dataloss',
31
- ]);
32
-
33
- const TRANSIENT_HTTP = new Set([408, 429, 502, 503, 504]);
34
- const NUMERIC_GRPC_CODES = new Map<number, string>([
35
- [0, 'ok'],
36
- [1, 'cancelled'],
37
- [2, 'unknown'],
38
- [3, 'invalidargument'],
39
- [4, 'deadlineexceeded'],
40
- [5, 'notfound'],
41
- [6, 'alreadyexists'],
42
- [7, 'permissiondenied'],
43
- [8, 'resourceexhausted'],
44
- [9, 'failedprecondition'],
45
- [10, 'aborted'],
46
- [11, 'outofrange'],
47
- [12, 'unimplemented'],
48
- [13, 'internal'],
49
- [14, 'unavailable'],
50
- [15, 'dataloss'],
51
- [16, 'unauthenticated'],
52
- ]);
53
-
54
- function normalizeCode(value: unknown): string | undefined {
55
- if (typeof value === 'number') {
56
- return NUMERIC_GRPC_CODES.get(value);
57
- }
58
- return typeof value === 'string' ? value.replaceAll(/[\s_-]/g, '').toLowerCase() : undefined;
59
- }
60
-
61
- function grpcEvidence(value: unknown): StructuredEvidence | undefined {
62
- const code = normalizeCode(value);
63
- if (code === undefined) {
64
- return undefined;
65
- }
66
- if (TRANSIENT_GRPC.has(code)) {
67
- return 'transient';
68
- }
69
- if (PERMANENT_GRPC.has(code)) {
70
- return 'permanent';
71
- }
72
- if (code === 'unknown' || code === 'ok') {
73
- return 'indeterminate';
74
- }
75
- return undefined;
76
- }
77
-
78
- function httpEvidence(value: unknown): StructuredEvidence | undefined {
79
- if (typeof value !== 'number' || !Number.isInteger(value) || value < 400 || value > 599) {
80
- return undefined;
81
- }
82
- return TRANSIENT_HTTP.has(value) ? 'transient' : 'permanent';
83
- }
84
-
85
- function httpMessageEvidence(message: string): StructuredEvidence | undefined {
86
- let hasTransient = false;
87
- for (const match of message.matchAll(
88
- /(?:\bhttp(?:\s+status)?|\bstatus\s*:?)\s*(\d{3})\b/g,
89
- )) {
90
- const evidence = httpEvidence(Number(match[1]));
91
- if (evidence === 'permanent') {
92
- return 'permanent';
93
- }
94
- hasTransient ||= evidence === 'transient';
95
- }
96
- return hasTransient ? 'transient' : undefined;
97
- }
98
-
99
- function flattenedTransient(message: string): boolean {
100
- return [
101
- 'cancelled',
102
- 'canceled',
103
- 'deadline exceeded',
104
- 'timeout',
105
- 'unavailable',
106
- 'resource exhausted',
107
- 'request timeout',
108
- 'too many requests',
109
- 'rate limited',
110
- 'rate limit',
111
- 'bad gateway',
112
- 'service unavailable',
113
- 'gateway timeout',
114
- 'i/o timeout',
115
- 'io timeout',
116
- 'connection reset',
117
- 'broken pipe',
118
- ].some((signal) => message.includes(signal));
119
- }
120
-
121
- function asRecord(value: unknown): ErrorRecord | undefined {
122
- return typeof value === 'object' && value !== null ? value as ErrorRecord : undefined;
123
- }
1
+ import { isTransientError } from '../retry/classify.js';
124
2
 
3
+ /**
4
+ * Prover-policy classification: the shared classifier with no transport-text
5
+ * extras — a bare "connection error" from a prover is treated as its
6
+ * considered answer.
7
+ */
125
8
  export function isTransientProverError(error: unknown): boolean {
126
- const seen = new Set<object>();
127
- const messages: string[] = [];
128
- let hasTransient = false;
129
- let hasPermanent = false;
130
- let current: unknown = error;
131
-
132
- while (current !== undefined && current !== null) {
133
- const record = asRecord(current);
134
- if (record !== undefined) {
135
- if (seen.has(record)) {
136
- break;
137
- }
138
- seen.add(record);
139
- for (const evidence of [
140
- grpcEvidence(record.code),
141
- httpEvidence(record.status),
142
- httpEvidence(record.statusCode),
143
- ]) {
144
- hasTransient ||= evidence === 'transient';
145
- hasPermanent ||= evidence === 'permanent';
146
- }
147
- if (typeof record.message === 'string') {
148
- const message = record.message.toLowerCase();
149
- messages.push(message);
150
- const evidence = httpMessageEvidence(message);
151
- hasTransient ||= evidence === 'transient';
152
- hasPermanent ||= evidence === 'permanent';
153
- } else {
154
- const message = String(current).toLowerCase();
155
- messages.push(message);
156
- const evidence = httpMessageEvidence(message);
157
- hasTransient ||= evidence === 'transient';
158
- hasPermanent ||= evidence === 'permanent';
159
- }
160
- current = record.cause;
161
- } else {
162
- const message = String(current).toLowerCase();
163
- messages.push(message);
164
- const evidence = httpMessageEvidence(message);
165
- hasTransient ||= evidence === 'transient';
166
- hasPermanent ||= evidence === 'permanent';
167
- break;
168
- }
169
- }
170
-
171
- if (hasPermanent) {
172
- return false;
173
- }
174
- if (hasTransient) {
175
- return true;
176
- }
177
- return messages.some(flattenedTransient);
9
+ return isTransientError(error);
178
10
  }
@@ -1,6 +1,6 @@
1
1
  import { readFileSync } from 'node:fs';
2
2
  import { describe, expect, it } from 'vitest';
3
- import { retryDelay } from './retry.js';
3
+ import { retryDelay } from '../retry/runtime.js';
4
4
 
5
5
  interface Fixtures {
6
6
  delays: Array<{ retryIndex: number; unitRandom: number; delayMs: number }>;
@@ -1,46 +1,21 @@
1
1
  import type { TransactionExecution, TransactionProof } from '@miden-sdk/miden-sdk';
2
2
  import type { ResolvedProverConfig } from './config.js';
3
3
  import { isTransientProverError } from './errors.js';
4
-
5
- const BASE_DELAY_MS = 500;
6
- const MAX_DELAY_MS = 8_000;
7
-
8
- export interface RetryRuntime {
9
- sleep(delayMs: number): Promise<void>;
10
- unitRandom(): number;
11
- }
12
-
13
- export const productionRetryRuntime: RetryRuntime = {
14
- sleep: (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),
15
- unitRandom: () => Math.random(),
16
- };
17
-
18
- export function retryDelay(retryIndex: number, unitRandom: number): number {
19
- const exponent = Math.min(retryIndex, 1023);
20
- const raw = BASE_DELAY_MS * 2 ** exponent;
21
- const finiteRandom = Number.isFinite(unitRandom) ? unitRandom : 0.5;
22
- const boundedRandom = Math.min(Math.max(finiteRandom, 0), 1 - Number.EPSILON);
23
- return Math.min(Math.floor(raw * (0.75 + boundedRandom * 0.5)), MAX_DELAY_MS);
24
- }
4
+ import type { RetryRuntime } from '../retry/runtime.js';
5
+ import { productionRetryRuntime, retryTransient } from '../retry/runtime.js';
25
6
 
26
7
  export async function proveWithRetry(
27
8
  execution: TransactionExecution,
28
9
  config: ResolvedProverConfig,
29
10
  runtime: RetryRuntime = productionRetryRuntime,
30
11
  ): Promise<TransactionProof> {
31
- for (let attempt = 0; attempt < config.maxAttempts; attempt += 1) {
32
- try {
12
+ return retryTransient(
13
+ async () => {
33
14
  const prover = config.createProver();
34
- return prover === undefined
35
- ? await execution.prove()
36
- : await execution.prove({ prover });
37
- } catch (error) {
38
- if (!isTransientProverError(error) || attempt + 1 >= config.maxAttempts) {
39
- throw error;
40
- }
41
- await runtime.sleep(retryDelay(attempt, runtime.unitRandom()));
42
- }
43
- }
44
-
45
- throw new Error('unreachable prover retry state');
15
+ return prover === undefined ? await execution.prove() : await execution.prove({ prover });
16
+ },
17
+ config.maxAttempts,
18
+ isTransientProverError,
19
+ runtime,
20
+ );
46
21
  }
@@ -6,7 +6,7 @@ import type {
6
6
  } from '@miden-sdk/miden-sdk';
7
7
  import { describe, expect, it, vi } from 'vitest';
8
8
  import type { ResolvedProverConfig } from './config.js';
9
- import type { RetryRuntime } from './retry.js';
9
+ import type { RetryRuntime } from '../retry/runtime.js';
10
10
  import { ProverWorkflow } from './workflow.js';
11
11
 
12
12
  function asType<T>(value: unknown): T {
@@ -89,6 +89,37 @@ describe('ProverWorkflow', () => {
89
89
  expect(runtime.sleep).toHaveBeenCalledTimes(1);
90
90
  });
91
91
 
92
+ it('never re-submits when submission fails with transient-looking wording', async () => {
93
+ const rateLimited = Object.assign(new Error('Too Many Requests!'), {
94
+ code: 'ResourceExhausted',
95
+ });
96
+ const submit = vi.fn().mockRejectedValue(rateLimited);
97
+ const prove = vi.fn().mockResolvedValue({ submit });
98
+ const client = {
99
+ transactions: { executeRequest: vi.fn().mockResolvedValue({ prove }) },
100
+ };
101
+ const runtime: RetryRuntime = {
102
+ sleep: vi.fn().mockResolvedValue(undefined),
103
+ unitRandom: () => 0.5,
104
+ };
105
+ const workflow = new ProverWorkflow(
106
+ asType<MidenClient>(client),
107
+ {
108
+ kind: 'remote',
109
+ maxAttempts: 5,
110
+ createProver: () => asType<TransactionProver>({}),
111
+ },
112
+ runtime,
113
+ );
114
+
115
+ await expect(
116
+ workflow.submit(asType<AccountId>({}), asType<TransactionRequest>({})),
117
+ ).rejects.toBe(rateLimited);
118
+ expect(prove).toHaveBeenCalledTimes(1);
119
+ expect(submit).toHaveBeenCalledTimes(1);
120
+ expect(runtime.sleep).not.toHaveBeenCalled();
121
+ });
122
+
92
123
  it('uses the injected prover directly when no cloneable remote override exists', async () => {
93
124
  const apply = vi.fn().mockResolvedValue({});
94
125
  const submit = vi.fn().mockResolvedValue({ apply });
@@ -1,6 +1,6 @@
1
1
  import type { AccountId, MidenClient, TransactionRequest } from '@miden-sdk/miden-sdk';
2
2
  import type { ResolvedProverConfig } from './config.js';
3
- import type { RetryRuntime } from './retry.js';
3
+ import type { RetryRuntime } from '../retry/runtime.js';
4
4
  import { proveWithRetry } from './retry.js';
5
5
 
6
6
  export class ProverWorkflow {
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Transient/permanent error classification shared by the prover and node-RPC
3
+ * retry policies, mirroring `is_transient_error_with` in the Rust
4
+ * `guardian-shared` crate: the whole cause chain is walked accumulating
5
+ * evidence, permanent evidence anywhere vetoes transient anywhere, and the
6
+ * transient-wording fallback fires only when no status-level evidence exists
7
+ * in any link. Behavior is pinned by the cross-SDK fixture corpus.
8
+ */
9
+
10
+ type ErrorRecord = {
11
+ cause?: unknown;
12
+ code?: unknown;
13
+ status?: unknown;
14
+ statusCode?: unknown;
15
+ message?: unknown;
16
+ };
17
+
18
+ type StructuredEvidence = 'transient' | 'permanent' | 'indeterminate';
19
+
20
+ const TRANSIENT_GRPC = new Set([
21
+ 'cancelled',
22
+ 'canceled',
23
+ 'deadlineexceeded',
24
+ 'unavailable',
25
+ 'resourceexhausted',
26
+ ]);
27
+
28
+ const PERMANENT_GRPC = new Set([
29
+ 'invalidargument',
30
+ 'failedprecondition',
31
+ 'permissiondenied',
32
+ 'unauthenticated',
33
+ 'notfound',
34
+ 'alreadyexists',
35
+ 'outofrange',
36
+ 'unimplemented',
37
+ 'aborted',
38
+ 'internal',
39
+ 'dataloss',
40
+ ]);
41
+
42
+ const TRANSIENT_HTTP = new Set([408, 429, 502, 503, 504]);
43
+ const NUMERIC_GRPC_CODES = new Map<number, string>([
44
+ [0, 'ok'],
45
+ [1, 'cancelled'],
46
+ [2, 'unknown'],
47
+ [3, 'invalidargument'],
48
+ [4, 'deadlineexceeded'],
49
+ [5, 'notfound'],
50
+ [6, 'alreadyexists'],
51
+ [7, 'permissiondenied'],
52
+ [8, 'resourceexhausted'],
53
+ [9, 'failedprecondition'],
54
+ [10, 'aborted'],
55
+ [11, 'outofrange'],
56
+ [12, 'unimplemented'],
57
+ [13, 'internal'],
58
+ [14, 'unavailable'],
59
+ [15, 'dataloss'],
60
+ [16, 'unauthenticated'],
61
+ ]);
62
+
63
+ const GRPC_MESSAGE_TOKENS: ReadonlyArray<{ token: string; evidence: StructuredEvidence }> = [
64
+ ...[...TRANSIENT_GRPC].map((code) => ({ token: `grpccode${code}`, evidence: 'transient' as const })),
65
+ ...[...PERMANENT_GRPC].map((code) => ({ token: `grpccode${code}`, evidence: 'permanent' as const })),
66
+ ];
67
+
68
+ function normalizeCode(value: unknown): string | undefined {
69
+ if (typeof value === 'number') {
70
+ return NUMERIC_GRPC_CODES.get(value);
71
+ }
72
+ return typeof value === 'string' ? value.replaceAll(/[\s_-]/g, '').toLowerCase() : undefined;
73
+ }
74
+
75
+ function grpcEvidence(value: unknown): StructuredEvidence | undefined {
76
+ const code = normalizeCode(value);
77
+ if (code === undefined) {
78
+ return undefined;
79
+ }
80
+ if (TRANSIENT_GRPC.has(code)) {
81
+ return 'transient';
82
+ }
83
+ if (PERMANENT_GRPC.has(code)) {
84
+ return 'permanent';
85
+ }
86
+ if (code === 'unknown' || code === 'ok') {
87
+ return 'indeterminate';
88
+ }
89
+ return undefined;
90
+ }
91
+
92
+ function httpEvidence(value: unknown): StructuredEvidence | undefined {
93
+ if (typeof value !== 'number' || !Number.isInteger(value) || value < 400 || value > 599) {
94
+ return undefined;
95
+ }
96
+ return TRANSIENT_HTTP.has(value) ? 'transient' : 'permanent';
97
+ }
98
+
99
+ function httpMessageEvidence(message: string): StructuredEvidence | undefined {
100
+ let hasTransient = false;
101
+ for (const match of message.matchAll(
102
+ /(?:\bhttp(?:\s+status)?|\bstatus)(?:\s+code)?\s*:?\s*(\d{3})\b/g,
103
+ )) {
104
+ const evidence = httpEvidence(Number(match[1]));
105
+ if (evidence === 'permanent') {
106
+ return 'permanent';
107
+ }
108
+ hasTransient ||= evidence === 'transient';
109
+ }
110
+ return hasTransient ? 'transient' : undefined;
111
+ }
112
+
113
+ function grpcMessageEvidence(message: string): StructuredEvidence | undefined {
114
+ const normalized = message.replaceAll(/[^a-z0-9]/g, '');
115
+ let hasTransient = false;
116
+ for (const { token, evidence } of GRPC_MESSAGE_TOKENS) {
117
+ if (normalized.includes(token)) {
118
+ if (evidence === 'permanent') {
119
+ return 'permanent';
120
+ }
121
+ hasTransient ||= evidence === 'transient';
122
+ }
123
+ }
124
+ return hasTransient ? 'transient' : undefined;
125
+ }
126
+
127
+ /**
128
+ * Last-resort transient wording, consulted only when the whole chain carried
129
+ * no status-level evidence. Guarded by the negative classification fixtures
130
+ * (server rejections must never match) — extend with care.
131
+ */
132
+ function flattenedTransient(message: string): boolean {
133
+ return [
134
+ 'cancelled',
135
+ 'canceled',
136
+ 'deadline exceeded',
137
+ 'timeout',
138
+ 'unavailable',
139
+ 'resource exhausted',
140
+ 'request timeout',
141
+ 'too many requests',
142
+ 'rate limited',
143
+ 'rate limit',
144
+ 'bad gateway',
145
+ 'service unavailable',
146
+ 'gateway timeout',
147
+ 'i/o timeout',
148
+ 'io timeout',
149
+ 'connection reset',
150
+ 'broken pipe',
151
+ ].some((signal) => message.includes(signal));
152
+ }
153
+
154
+ function asRecord(value: unknown): ErrorRecord | undefined {
155
+ return typeof value === 'object' && value !== null ? value as ErrorRecord : undefined;
156
+ }
157
+
158
+ /**
159
+ * Walks the error's cause chain and reports whether every piece of evidence
160
+ * points at a transient failure. `extraTransientSignals` extends the
161
+ * transient-wording fallback for one policy without leaking into others,
162
+ * under the same permanent-wins rule.
163
+ */
164
+ export function isTransientError(
165
+ error: unknown,
166
+ extraTransientSignals: readonly string[] = [],
167
+ ): boolean {
168
+ const seen = new Set<object>();
169
+ const messages: string[] = [];
170
+ let hasTransient = false;
171
+ let hasPermanent = false;
172
+ let current: unknown = error;
173
+
174
+ const recordMessage = (message: string): void => {
175
+ messages.push(message);
176
+ for (const evidence of [httpMessageEvidence(message), grpcMessageEvidence(message)]) {
177
+ hasTransient ||= evidence === 'transient';
178
+ hasPermanent ||= evidence === 'permanent';
179
+ }
180
+ };
181
+
182
+ while (current !== undefined && current !== null) {
183
+ const record = asRecord(current);
184
+ if (record !== undefined) {
185
+ if (seen.has(record)) {
186
+ break;
187
+ }
188
+ seen.add(record);
189
+ for (const evidence of [
190
+ grpcEvidence(record.code),
191
+ httpEvidence(record.status),
192
+ httpEvidence(record.statusCode),
193
+ ]) {
194
+ hasTransient ||= evidence === 'transient';
195
+ hasPermanent ||= evidence === 'permanent';
196
+ }
197
+ recordMessage(
198
+ typeof record.message === 'string'
199
+ ? record.message.toLowerCase()
200
+ : String(current).toLowerCase(),
201
+ );
202
+ current = record.cause;
203
+ } else {
204
+ recordMessage(String(current).toLowerCase());
205
+ break;
206
+ }
207
+ }
208
+
209
+ if (hasPermanent) {
210
+ return false;
211
+ }
212
+ if (hasTransient) {
213
+ return true;
214
+ }
215
+ return messages.some(
216
+ (message) =>
217
+ flattenedTransient(message) ||
218
+ extraTransientSignals.some((signal) => message.includes(signal)),
219
+ );
220
+ }
@@ -0,0 +1,45 @@
1
+ const BASE_DELAY_MS = 500;
2
+ const MAX_DELAY_MS = 8_000;
3
+
4
+ export interface RetryRuntime {
5
+ sleep(delayMs: number): Promise<void>;
6
+ unitRandom(): number;
7
+ }
8
+
9
+ export const productionRetryRuntime: RetryRuntime = {
10
+ sleep: (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs)),
11
+ unitRandom: () => Math.random(),
12
+ };
13
+
14
+ export function retryDelay(retryIndex: number, unitRandom: number): number {
15
+ const exponent = Math.min(retryIndex, 1023);
16
+ const raw = BASE_DELAY_MS * 2 ** exponent;
17
+ const finiteRandom = Number.isFinite(unitRandom) ? unitRandom : 0.5;
18
+ const boundedRandom = Math.min(Math.max(finiteRandom, 0), 1 - Number.EPSILON);
19
+ return Math.min(Math.floor(raw * (0.75 + boundedRandom * 0.5)), MAX_DELAY_MS);
20
+ }
21
+
22
+ /**
23
+ * Runs `operation` under an attempt budget: the budget is consulted before
24
+ * the error is classified, transient failures back off with `retryDelay`,
25
+ * and permanent failures or the final attempt rethrow the error unchanged.
26
+ */
27
+ export async function retryTransient<T>(
28
+ operation: () => Promise<T>,
29
+ maxAttempts: number,
30
+ isTransient: (error: unknown) => boolean,
31
+ runtime: RetryRuntime,
32
+ ): Promise<T> {
33
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
34
+ try {
35
+ return await operation();
36
+ } catch (error) {
37
+ if (attempt + 1 >= maxAttempts || !isTransient(error)) {
38
+ throw error;
39
+ }
40
+ await runtime.sleep(retryDelay(attempt, runtime.unitRandom()));
41
+ }
42
+ }
43
+
44
+ throw new Error('unreachable retry state');
45
+ }
@@ -0,0 +1,45 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { describe, expect, it } from 'vitest';
3
+ import { resolveRpcConfig } from './config.js';
4
+
5
+ interface Fixtures {
6
+ attemptBudgets: Array<{ input: number | null; normalized: number }>;
7
+ }
8
+
9
+ function fixtures(): Fixtures {
10
+ return JSON.parse(
11
+ readFileSync(
12
+ new URL(
13
+ '../../../../fixtures/miden-multisig-client/rpc-policy-fixtures.json',
14
+ import.meta.url,
15
+ ),
16
+ 'utf8',
17
+ ),
18
+ ) as Fixtures;
19
+ }
20
+
21
+ describe('resolveRpcConfig', () => {
22
+ it('matches shared attempt-budget vectors', () => {
23
+ for (const fixture of fixtures().attemptBudgets) {
24
+ const retry = fixture.input === null ? undefined : { maxAttempts: fixture.input };
25
+ expect(resolveRpcConfig({ retry }).maxAttempts).toBe(fixture.normalized);
26
+ }
27
+ });
28
+
29
+ it('defaults to one retry when no config is given', () => {
30
+ expect(resolveRpcConfig(undefined).maxAttempts).toBe(2);
31
+ });
32
+
33
+ it('treats an explicit single attempt as a full opt-out', () => {
34
+ expect(resolveRpcConfig({ retry: { maxAttempts: 1 } }).maxAttempts).toBe(1);
35
+ });
36
+
37
+ it.each([-1, 1.5, Number.NaN, Number.POSITIVE_INFINITY, 4_294_967_296])(
38
+ 'rejects invalid maxAttempts value %s',
39
+ (maxAttempts) => {
40
+ expect(() => resolveRpcConfig({ retry: { maxAttempts } })).toThrow(
41
+ 'rpc.retry.maxAttempts',
42
+ );
43
+ },
44
+ );
45
+ });
@@ -0,0 +1,30 @@
1
+ export interface RpcRetryPolicy {
2
+ maxAttempts?: number;
3
+ }
4
+
5
+ export interface RpcConfig {
6
+ retry?: RpcRetryPolicy;
7
+ }
8
+
9
+ export interface ResolvedRpcConfig {
10
+ readonly maxAttempts: number;
11
+ }
12
+
13
+ const DEFAULT_MAX_ATTEMPTS = 2;
14
+ const MAX_U32 = 4_294_967_295;
15
+
16
+ function normalizeMaxAttempts(value: number | undefined): number {
17
+ if (value === undefined) {
18
+ return DEFAULT_MAX_ATTEMPTS;
19
+ }
20
+ if (!Number.isFinite(value) || !Number.isInteger(value) || value < 0 || value > MAX_U32) {
21
+ throw new Error('rpc.retry.maxAttempts must be an integer between 0 and 4294967295');
22
+ }
23
+ return Math.max(1, value);
24
+ }
25
+
26
+ export function resolveRpcConfig(config: RpcConfig | undefined): ResolvedRpcConfig {
27
+ return {
28
+ maxAttempts: normalizeMaxAttempts(config?.retry?.maxAttempts),
29
+ };
30
+ }