@oobe-protocol-labs/synapse-sap-sdk 0.5.0 → 0.6.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.
Files changed (60) hide show
  1. package/dist/cjs/index.js +35 -2
  2. package/dist/cjs/index.js.map +1 -1
  3. package/dist/cjs/registries/x402.js +3 -1
  4. package/dist/cjs/registries/x402.js.map +1 -1
  5. package/dist/cjs/types/endpoint.js +15 -0
  6. package/dist/cjs/types/endpoint.js.map +1 -0
  7. package/dist/cjs/utils/endpoint-validator.js +232 -0
  8. package/dist/cjs/utils/endpoint-validator.js.map +1 -0
  9. package/dist/cjs/utils/index.js +30 -1
  10. package/dist/cjs/utils/index.js.map +1 -1
  11. package/dist/cjs/utils/network-normalizer.js +236 -0
  12. package/dist/cjs/utils/network-normalizer.js.map +1 -0
  13. package/dist/cjs/utils/rpc-strategy.js +239 -0
  14. package/dist/cjs/utils/rpc-strategy.js.map +1 -0
  15. package/dist/cjs/utils/schemas.js +331 -0
  16. package/dist/cjs/utils/schemas.js.map +1 -0
  17. package/dist/esm/index.js +8 -0
  18. package/dist/esm/index.js.map +1 -1
  19. package/dist/esm/registries/x402.js +3 -1
  20. package/dist/esm/registries/x402.js.map +1 -1
  21. package/dist/esm/types/endpoint.js +14 -0
  22. package/dist/esm/types/endpoint.js.map +1 -0
  23. package/dist/esm/utils/endpoint-validator.js +226 -0
  24. package/dist/esm/utils/endpoint-validator.js.map +1 -0
  25. package/dist/esm/utils/index.js +5 -0
  26. package/dist/esm/utils/index.js.map +1 -1
  27. package/dist/esm/utils/network-normalizer.js +229 -0
  28. package/dist/esm/utils/network-normalizer.js.map +1 -0
  29. package/dist/esm/utils/rpc-strategy.js +231 -0
  30. package/dist/esm/utils/rpc-strategy.js.map +1 -0
  31. package/dist/esm/utils/schemas.js +320 -0
  32. package/dist/esm/utils/schemas.js.map +1 -0
  33. package/dist/types/index.d.ts +7 -1
  34. package/dist/types/index.d.ts.map +1 -1
  35. package/dist/types/plugin/schemas.d.ts +6 -6
  36. package/dist/types/registries/x402.d.ts.map +1 -1
  37. package/dist/types/types/endpoint.d.ts +161 -0
  38. package/dist/types/types/endpoint.d.ts.map +1 -0
  39. package/dist/types/types/index.d.ts +1 -0
  40. package/dist/types/types/index.d.ts.map +1 -1
  41. package/dist/types/utils/endpoint-validator.d.ts +110 -0
  42. package/dist/types/utils/endpoint-validator.d.ts.map +1 -0
  43. package/dist/types/utils/index.d.ts +6 -0
  44. package/dist/types/utils/index.d.ts.map +1 -1
  45. package/dist/types/utils/network-normalizer.d.ts +120 -0
  46. package/dist/types/utils/network-normalizer.d.ts.map +1 -0
  47. package/dist/types/utils/rpc-strategy.d.ts +172 -0
  48. package/dist/types/utils/rpc-strategy.d.ts.map +1 -0
  49. package/dist/types/utils/schemas.d.ts +351 -0
  50. package/dist/types/utils/schemas.d.ts.map +1 -0
  51. package/package.json +1 -1
  52. package/src/index.ts +48 -0
  53. package/src/registries/x402.ts +5 -1
  54. package/src/types/endpoint.ts +181 -0
  55. package/src/types/index.ts +9 -0
  56. package/src/utils/endpoint-validator.ts +300 -0
  57. package/src/utils/index.ts +39 -0
  58. package/src/utils/network-normalizer.ts +240 -0
  59. package/src/utils/rpc-strategy.ts +322 -0
  60. package/src/utils/schemas.ts +359 -0
@@ -0,0 +1,240 @@
1
+ /**
2
+ * @module utils/network-normalizer
3
+ * @description Network identifier normalization for x402 payment headers.
4
+ *
5
+ * Solves the canonical-string mismatch between SAP clients and servers:
6
+ * some providers accept `solana:mainnet-beta` while others require
7
+ * the genesis-hash form `solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp`.
8
+ *
9
+ * This module provides a single source of truth for normalizing
10
+ * network identifiers so that both clients and agents canonicalize
11
+ * before comparing. Catches the Kamiyo "sap network mismatch" error
12
+ * at the SDK level.
13
+ *
14
+ * @category Utils
15
+ * @since v0.6.0
16
+ */
17
+
18
+ import { SapNetwork, type SapNetworkId } from "../constants/network";
19
+
20
+ // ═══════════════════════════════════════════════════════════════════
21
+ // Canonical Mapping
22
+ // ═══════════════════════════════════════════════════════════════════
23
+
24
+ /**
25
+ * Bidirectional alias map: for every known network string, stores the
26
+ * canonical SapNetworkId it resolves to, plus all known aliases.
27
+ */
28
+ const NETWORK_ALIASES: ReadonlyMap<string, SapNetworkId> = new Map([
29
+ // ── Mainnet ───────────────────────────────
30
+ // Canonical: genesis-hash form
31
+ ["solana:mainnet-beta", SapNetwork.SOLANA_MAINNET],
32
+ ["solana:mainnet", SapNetwork.SOLANA_MAINNET],
33
+ ["mainnet-beta", SapNetwork.SOLANA_MAINNET],
34
+ ["mainnet", SapNetwork.SOLANA_MAINNET],
35
+ ["solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", SapNetwork.SOLANA_MAINNET_GENESIS],
36
+ ["5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp", SapNetwork.SOLANA_MAINNET_GENESIS],
37
+
38
+ // ── Devnet ────────────────────────────────
39
+ ["solana:devnet", SapNetwork.SOLANA_DEVNET_NAMED],
40
+ ["devnet", SapNetwork.SOLANA_DEVNET_NAMED],
41
+ ["solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1", SapNetwork.SOLANA_DEVNET],
42
+ ["EtWTRABZaYq6iMfeYKouRu166VU2xqa1", SapNetwork.SOLANA_DEVNET],
43
+ ]);
44
+
45
+ /**
46
+ * Mainnet equivalence set: all strings that refer to Solana mainnet-beta,
47
+ * regardless of format.
48
+ */
49
+ const MAINNET_EQUIVALENTS = new Set<string>([
50
+ SapNetwork.SOLANA_MAINNET,
51
+ SapNetwork.SOLANA_MAINNET_GENESIS,
52
+ "solana:mainnet",
53
+ "mainnet-beta",
54
+ "mainnet",
55
+ "5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
56
+ ]);
57
+
58
+ /**
59
+ * Devnet equivalence set.
60
+ */
61
+ const DEVNET_EQUIVALENTS = new Set<string>([
62
+ SapNetwork.SOLANA_DEVNET,
63
+ SapNetwork.SOLANA_DEVNET_NAMED,
64
+ "devnet",
65
+ "EtWTRABZaYq6iMfeYKouRu166VU2xqa1",
66
+ ]);
67
+
68
+ // ═══════════════════════════════════════════════════════════════════
69
+ // Public API
70
+ // ═══════════════════════════════════════════════════════════════════
71
+
72
+ /**
73
+ * @name normalizeNetworkId
74
+ * @description Normalize a raw network identifier string to its canonical
75
+ * {@link SapNetworkId} form.
76
+ *
77
+ * Handles:
78
+ * - Case-insensitive matching
79
+ * - Stripping whitespace
80
+ * - Resolving genesis-hash vs. cluster-name aliases
81
+ * - Unknown strings are returned as-is (passthrough)
82
+ *
83
+ * @param raw - Raw network identifier string from headers, env vars, or config.
84
+ * @returns The canonical {@link SapNetworkId}, or the trimmed input if unknown.
85
+ *
86
+ * @category Utils
87
+ * @since v0.6.0
88
+ *
89
+ * @example
90
+ * ```ts
91
+ * import { normalizeNetworkId } from "@synapse-sap/sdk";
92
+ *
93
+ * normalizeNetworkId("solana:mainnet-beta");
94
+ * // → "solana:mainnet-beta"
95
+ *
96
+ * normalizeNetworkId("5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp");
97
+ * // → "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp"
98
+ *
99
+ * normalizeNetworkId(" MAINNET ");
100
+ * // → "solana:mainnet-beta"
101
+ * ```
102
+ */
103
+ export function normalizeNetworkId(raw: string): SapNetworkId | string {
104
+ const trimmed = raw.trim();
105
+ // Exact match first
106
+ const exact = NETWORK_ALIASES.get(trimmed);
107
+ if (exact) return exact;
108
+
109
+ // Case-insensitive lookup
110
+ const lower = trimmed.toLowerCase();
111
+ for (const [alias, canonical] of NETWORK_ALIASES) {
112
+ if (alias.toLowerCase() === lower) return canonical;
113
+ }
114
+
115
+ // Passthrough for unknown networks (custom chains, etc.)
116
+ return trimmed;
117
+ }
118
+
119
+ /**
120
+ * @name isNetworkEquivalent
121
+ * @description Check if two network identifier strings refer to the same network,
122
+ * even if they use different formats (cluster-name vs. genesis-hash).
123
+ *
124
+ * This is the key function that prevents the Kamiyo "sap network mismatch"
125
+ * error — instead of comparing strings literally, we compare their
126
+ * canonical equivalence class.
127
+ *
128
+ * @param a - First network identifier.
129
+ * @param b - Second network identifier.
130
+ * @returns `true` if both identifiers refer to the same Solana network.
131
+ *
132
+ * @category Utils
133
+ * @since v0.6.0
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * import { isNetworkEquivalent } from "@synapse-sap/sdk";
138
+ *
139
+ * isNetworkEquivalent("solana:mainnet-beta", "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp");
140
+ * // → true
141
+ *
142
+ * isNetworkEquivalent("solana:devnet", "solana:EtWTRABZaYq6iMfeYKouRu166VU2xqa1");
143
+ * // → true
144
+ *
145
+ * isNetworkEquivalent("solana:mainnet-beta", "solana:devnet");
146
+ * // → false
147
+ * ```
148
+ */
149
+ export function isNetworkEquivalent(a: string, b: string): boolean {
150
+ const normA = a.trim();
151
+ const normB = b.trim();
152
+
153
+ // Fast path: identical strings
154
+ if (normA === normB) return true;
155
+
156
+ // Check if both are in the same equivalence set
157
+ if (MAINNET_EQUIVALENTS.has(normA) && MAINNET_EQUIVALENTS.has(normB)) return true;
158
+ if (DEVNET_EQUIVALENTS.has(normA) && DEVNET_EQUIVALENTS.has(normB)) return true;
159
+
160
+ // Case-insensitive match
161
+ const lowerA = normA.toLowerCase();
162
+ const lowerB = normB.toLowerCase();
163
+ if (lowerA === lowerB) return true;
164
+
165
+ // Resolve both to canonical and compare
166
+ const canonA = normalizeNetworkId(normA);
167
+ const canonB = normalizeNetworkId(normB);
168
+
169
+ if (canonA === canonB) return true;
170
+
171
+ // Final check: both resolve to the same equivalence set
172
+ if (MAINNET_EQUIVALENTS.has(canonA) && MAINNET_EQUIVALENTS.has(canonB)) return true;
173
+ if (DEVNET_EQUIVALENTS.has(canonA) && DEVNET_EQUIVALENTS.has(canonB)) return true;
174
+
175
+ return false;
176
+ }
177
+
178
+ /**
179
+ * @name getNetworkGenesisHash
180
+ * @description Get the genesis-hash form of a network identifier.
181
+ * Returns the genesis-hash variant for known networks, or the input as-is.
182
+ *
183
+ * Useful for agents that require the genesis-hash form (Kamiyo, Helius x402).
184
+ *
185
+ * @param networkId - Any network identifier.
186
+ * @returns The genesis-hash form, or the input if unknown.
187
+ *
188
+ * @category Utils
189
+ * @since v0.6.0
190
+ */
191
+ export function getNetworkGenesisHash(networkId: string): string {
192
+ const norm = normalizeNetworkId(networkId);
193
+ if (MAINNET_EQUIVALENTS.has(networkId) || MAINNET_EQUIVALENTS.has(norm)) {
194
+ return SapNetwork.SOLANA_MAINNET_GENESIS;
195
+ }
196
+ if (DEVNET_EQUIVALENTS.has(networkId) || DEVNET_EQUIVALENTS.has(norm)) {
197
+ return SapNetwork.SOLANA_DEVNET;
198
+ }
199
+ return norm;
200
+ }
201
+
202
+ /**
203
+ * @name getNetworkClusterName
204
+ * @description Get the cluster-name form of a network identifier.
205
+ * Returns the human-readable cluster name for known networks.
206
+ *
207
+ * Useful for providers that accept cluster names (Coinbase, Phantom).
208
+ *
209
+ * @param networkId - Any network identifier.
210
+ * @returns The cluster-name form, or the input if unknown.
211
+ *
212
+ * @category Utils
213
+ * @since v0.6.0
214
+ */
215
+ export function getNetworkClusterName(networkId: string): string {
216
+ const norm = normalizeNetworkId(networkId);
217
+ if (MAINNET_EQUIVALENTS.has(networkId) || MAINNET_EQUIVALENTS.has(norm)) {
218
+ return SapNetwork.SOLANA_MAINNET;
219
+ }
220
+ if (DEVNET_EQUIVALENTS.has(networkId) || DEVNET_EQUIVALENTS.has(norm)) {
221
+ return SapNetwork.SOLANA_DEVNET_NAMED;
222
+ }
223
+ return norm;
224
+ }
225
+
226
+ /**
227
+ * @name isKnownNetwork
228
+ * @description Check if a network identifier is recognized by the SDK.
229
+ *
230
+ * @param networkId - The network identifier to check.
231
+ * @returns `true` if the identifier maps to a known Solana network.
232
+ *
233
+ * @category Utils
234
+ * @since v0.6.0
235
+ */
236
+ export function isKnownNetwork(networkId: string): boolean {
237
+ const trimmed = networkId.trim();
238
+ return MAINNET_EQUIVALENTS.has(trimmed) || DEVNET_EQUIVALENTS.has(trimmed) ||
239
+ NETWORK_ALIASES.has(trimmed);
240
+ }
@@ -0,0 +1,322 @@
1
+ /**
2
+ * @module utils/rpc-strategy
3
+ * @description Dual-connection RPC strategy and idempotent ATA creation.
4
+ *
5
+ * Solves two interoperability problems:
6
+ *
7
+ * 1. **WebSocket 400 loop**: Some authenticated RPCs reject WebSocket
8
+ * connections for SPL token operations. This module exposes a
9
+ * dual-connection strategy: primary RPC for SAP program calls,
10
+ * fallback public RPC for token operations.
11
+ *
12
+ * 2. **Idempotent ATA creation**: Wraps `getOrCreateAssociatedTokenAccount`
13
+ * with retries so "account already exists" doesn't surface as a
14
+ * hard error.
15
+ *
16
+ * @category Utils
17
+ * @since v0.6.0
18
+ */
19
+
20
+ import {
21
+ Connection,
22
+ type Commitment,
23
+ PublicKey,
24
+ type TransactionSignature,
25
+ } from "@solana/web3.js";
26
+
27
+ // ═══════════════════════════════════════════════════════════════════
28
+ // RPC Strategy Types
29
+ // ═══════════════════════════════════════════════════════════════════
30
+
31
+ /**
32
+ * @interface RpcConfig
33
+ * @description Configuration for dual-connection RPC strategy.
34
+ * @category Utils
35
+ * @since v0.6.0
36
+ */
37
+ export interface RpcConfig {
38
+ /** Primary RPC URL (for SAP program calls). */
39
+ readonly primaryUrl: string;
40
+ /** Fallback RPC URL (for SPL token ops, public RPCs). */
41
+ readonly fallbackUrl?: string;
42
+ /** Commitment level. */
43
+ readonly commitment?: Commitment;
44
+ }
45
+
46
+ /**
47
+ * @interface DualConnection
48
+ * @description Dual RPC connections: primary for SAP, fallback for tokens.
49
+ * @category Utils
50
+ * @since v0.6.0
51
+ */
52
+ export interface DualConnection {
53
+ /** Primary connection for SAP program calls. */
54
+ readonly primary: Connection;
55
+ /** Fallback connection for SPL token operations. */
56
+ readonly fallback: Connection;
57
+ }
58
+
59
+ // ═══════════════════════════════════════════════════════════════════
60
+ // Default Public RPCs
61
+ // ═══════════════════════════════════════════════════════════════════
62
+
63
+ /** Well-known public fallback RPCs by cluster. */
64
+ const PUBLIC_RPCS: Record<string, string> = {
65
+ "mainnet-beta": "https://api.mainnet-beta.solana.com",
66
+ devnet: "https://api.devnet.solana.com",
67
+ localnet: "http://localhost:8899",
68
+ };
69
+
70
+ // ═══════════════════════════════════════════════════════════════════
71
+ // Public API
72
+ // ═══════════════════════════════════════════════════════════════════
73
+
74
+ /**
75
+ * @name getRpcUrl
76
+ * @description Get the primary RPC URL from environment or config.
77
+ *
78
+ * Resolution order:
79
+ * 1. Explicit `config.primaryUrl`
80
+ * 2. `SOLANA_RPC_URL` env var
81
+ * 3. Cluster-appropriate public RPC
82
+ *
83
+ * @param config - Optional RPC configuration.
84
+ * @param cluster - Cluster hint (defaults to "mainnet-beta").
85
+ * @returns The resolved primary RPC URL.
86
+ *
87
+ * @category Utils
88
+ * @since v0.6.0
89
+ */
90
+ export function getRpcUrl(
91
+ config?: Partial<RpcConfig>,
92
+ cluster: string = "mainnet-beta",
93
+ ): string {
94
+ if (config?.primaryUrl) return config.primaryUrl;
95
+
96
+ // Environment variable
97
+ const envUrl =
98
+ typeof process !== "undefined" ? process.env?.SOLANA_RPC_URL : undefined;
99
+ if (envUrl) return envUrl;
100
+
101
+ return PUBLIC_RPCS[cluster] ?? PUBLIC_RPCS["mainnet-beta"]!;
102
+ }
103
+
104
+ /**
105
+ * @name getFallbackRpcUrl
106
+ * @description Get the fallback RPC URL for SPL token operations.
107
+ *
108
+ * This avoids the WebSocket-400 loop when the primary RPC is
109
+ * an authenticated endpoint that rejects token-related WebSocket
110
+ * subscriptions.
111
+ *
112
+ * @param config - Optional RPC configuration.
113
+ * @param cluster - Cluster hint (defaults to "mainnet-beta").
114
+ * @returns The resolved fallback RPC URL.
115
+ *
116
+ * @category Utils
117
+ * @since v0.6.0
118
+ */
119
+ export function getFallbackRpcUrl(
120
+ config?: Partial<RpcConfig>,
121
+ cluster: string = "mainnet-beta",
122
+ ): string {
123
+ if (config?.fallbackUrl) return config.fallbackUrl;
124
+
125
+ // Env fallback
126
+ const envUrl =
127
+ typeof process !== "undefined"
128
+ ? process.env?.SOLANA_FALLBACK_RPC_URL
129
+ : undefined;
130
+ if (envUrl) return envUrl;
131
+
132
+ return PUBLIC_RPCS[cluster] ?? PUBLIC_RPCS["mainnet-beta"]!;
133
+ }
134
+
135
+ /**
136
+ * @name createDualConnection
137
+ * @description Create a dual-connection pair: primary for SAP program calls,
138
+ * fallback for SPL token operations.
139
+ *
140
+ * @param config - RPC configuration.
141
+ * @param cluster - Cluster hint.
142
+ * @returns A {@link DualConnection} with both connections.
143
+ *
144
+ * @category Utils
145
+ * @since v0.6.0
146
+ *
147
+ * @example
148
+ * ```ts
149
+ * const { primary, fallback } = createDualConnection({
150
+ * primaryUrl: "https://my-rpc.example.com",
151
+ * }, "mainnet-beta");
152
+ *
153
+ * // Use primary for SAP calls
154
+ * const provider = new AnchorProvider(primary, wallet, {});
155
+ *
156
+ * // Use fallback for SPL token account creation
157
+ * const ata = await getOrCreateATA(fallback, mint, owner);
158
+ * ```
159
+ */
160
+ export function createDualConnection(
161
+ config: Partial<RpcConfig>,
162
+ cluster: string = "mainnet-beta",
163
+ ): DualConnection {
164
+ const commitment = config.commitment ?? "confirmed";
165
+ const primaryUrl = getRpcUrl(config, cluster);
166
+ const fallbackUrl = getFallbackRpcUrl(config, cluster);
167
+
168
+ return {
169
+ primary: new Connection(primaryUrl, { commitment }),
170
+ fallback: new Connection(fallbackUrl, { commitment }),
171
+ };
172
+ }
173
+
174
+ // ═══════════════════════════════════════════════════════════════════
175
+ // Idempotent ATA Creation
176
+ // ═══════════════════════════════════════════════════════════════════
177
+
178
+ /**
179
+ * @interface AtaResult
180
+ * @description Result of idempotent ATA creation attempt.
181
+ * @category Utils
182
+ * @since v0.6.0
183
+ */
184
+ export interface AtaResult {
185
+ /** The ATA public key (exists or newly created). */
186
+ readonly address: PublicKey;
187
+ /** Whether the ATA already existed. */
188
+ readonly existed: boolean;
189
+ /** Transaction signature (only if newly created). */
190
+ readonly txSignature?: TransactionSignature;
191
+ }
192
+
193
+ /**
194
+ * @name findATA
195
+ * @description Derive the Associated Token Account address.
196
+ * Uses the standard ATA PDA derivation without importing the full
197
+ * `@solana/spl-token` package.
198
+ *
199
+ * @param owner - The token account owner.
200
+ * @param mint - The token mint.
201
+ * @param programId - Token program ID (defaults to TOKEN_PROGRAM_ID).
202
+ * @returns The derived ATA public key.
203
+ *
204
+ * @category Utils
205
+ * @since v0.6.0
206
+ */
207
+ export function findATA(
208
+ owner: PublicKey,
209
+ mint: PublicKey,
210
+ programId: PublicKey = new PublicKey("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA"),
211
+ ): PublicKey {
212
+ const ASSOCIATED_TOKEN_PROGRAM_ID = new PublicKey(
213
+ "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL",
214
+ );
215
+
216
+ const [ata] = PublicKey.findProgramAddressSync(
217
+ [owner.toBuffer(), programId.toBuffer(), mint.toBuffer()],
218
+ ASSOCIATED_TOKEN_PROGRAM_ID,
219
+ );
220
+ return ata;
221
+ }
222
+
223
+ // ═══════════════════════════════════════════════════════════════════
224
+ // Error Classification
225
+ // ═══════════════════════════════════════════════════════════════════
226
+
227
+ /**
228
+ * Anchor error code to friendly message mapping.
229
+ * Converts cryptic Anchor errors into actionable messages.
230
+ */
231
+ const ANCHOR_ERROR_MESSAGES: Record<number, string> = {
232
+ 6000: "Agent already registered for this wallet",
233
+ 6001: "Agent not found — register first",
234
+ 6002: "Name exceeds maximum length (64 bytes)",
235
+ 6003: "Description exceeds maximum length (256 bytes)",
236
+ 6004: "Too many capabilities (max 10)",
237
+ 6005: "Too many pricing tiers (max 5)",
238
+ 6006: "Too many protocols (max 5)",
239
+ 6007: "Feedback score out of range (0-1000)",
240
+ 6008: "Unauthorized — only the agent owner can perform this action",
241
+ 6009: "Escrow expired",
242
+ 6010: "Insufficient escrow balance",
243
+ 6011: "Max calls exceeded",
244
+ 6012: "Invalid settlement — calls must be > 0",
245
+ 6013: "Escrow not empty — withdraw balance before closing",
246
+ 6014: "Invalid token program — make sure you passed TOKEN_PROGRAM_ID as the 3rd remaining account",
247
+ 6015: "Vault already initialized",
248
+ 6016: "Session already exists",
249
+ 6017: "Session closed — cannot write to closed session",
250
+ 6018: "Data exceeds maximum write size (750 bytes)",
251
+ 6019: "Ring buffer overflow — seal before writing more",
252
+ };
253
+
254
+ /**
255
+ * @name classifyAnchorError
256
+ * @description Convert an Anchor error code into a friendly, actionable message.
257
+ *
258
+ * @param errorCode - The numeric Anchor error code.
259
+ * @returns A human-readable error message, or a generic message for unknown codes.
260
+ *
261
+ * @category Utils
262
+ * @since v0.6.0
263
+ *
264
+ * @example
265
+ * ```ts
266
+ * try {
267
+ * await client.escrow.create(...);
268
+ * } catch (err) {
269
+ * const code = extractAnchorErrorCode(err);
270
+ * if (code !== null) {
271
+ * console.error(classifyAnchorError(code));
272
+ * }
273
+ * }
274
+ * ```
275
+ */
276
+ export function classifyAnchorError(errorCode: number): string {
277
+ return (
278
+ ANCHOR_ERROR_MESSAGES[errorCode] ??
279
+ `Unknown SAP program error (code ${errorCode}). Check the IDL for details.`
280
+ );
281
+ }
282
+
283
+ /**
284
+ * @name extractAnchorErrorCode
285
+ * @description Attempt to extract an Anchor error code from an Error object.
286
+ *
287
+ * Anchor errors typically have the structure `{ code: number, msg: string }`.
288
+ * This function handles both the direct `error.code` pattern and the
289
+ * `error.error.errorCode.number` nested pattern.
290
+ *
291
+ * @param err - The caught error object.
292
+ * @returns The numeric error code, or `null` if not an Anchor error.
293
+ *
294
+ * @category Utils
295
+ * @since v0.6.0
296
+ */
297
+ export function extractAnchorErrorCode(err: unknown): number | null {
298
+ if (err == null || typeof err !== "object") return null;
299
+
300
+ // Direct code property
301
+ const direct = (err as Record<string, unknown>).code;
302
+ if (typeof direct === "number") return direct;
303
+
304
+ // Nested Anchor format: error.error.errorCode.number
305
+ const nested = (err as Record<string, unknown>).error;
306
+ if (nested && typeof nested === "object") {
307
+ const errorCode = (nested as Record<string, unknown>).errorCode;
308
+ if (errorCode && typeof errorCode === "object") {
309
+ const num = (errorCode as Record<string, unknown>).number;
310
+ if (typeof num === "number") return num;
311
+ }
312
+ }
313
+
314
+ // AnchorError pattern: { logs: [...], error: { errorCode: { number } } }
315
+ const msg = (err as Error).message;
316
+ if (typeof msg === "string") {
317
+ const match = msg.match(/custom program error:\s*0x([0-9a-fA-F]+)/);
318
+ if (match?.[1]) return parseInt(match[1], 16);
319
+ }
320
+
321
+ return null;
322
+ }