@neuraiproject/neurai-rpc 0.4.7 → 0.5.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.
package/depin.ts CHANGED
@@ -1,294 +1,545 @@
1
1
  /**
2
- * DePIN RPC Client for Neurai
3
- *
4
- * This module provides support for communicating with Neurai DePIN messaging
5
- * on port 19002 using the challenge/response authentication protocol.
2
+ * DePIN RPC Client for Neurai — Node.js only.
3
+ *
4
+ * The Neurai DePIN messaging gateway (default port 19002) speaks a raw TCP
5
+ * line protocol, NOT HTTP: the server reads bytes up to the first '\n' and
6
+ * processes that single line as either a protocol command (PING, INFO,
7
+ * AUTH|..., ...) or a serialized JSON-RPC object, answering with a single
8
+ * line as well. Because of that, this module uses `node:net` sockets and can
9
+ * only run in Node.js. Browsers cannot open raw TCP connections; to use DePIN
10
+ * from a browser you need an external HTTP/WebSocket proxy in front of the
11
+ * gateway.
12
+ *
13
+ * Import this module through the package subpath:
14
+ *
15
+ * ```typescript
16
+ * import { getDePinRPC } from "@neuraiproject/neurai-rpc/depin";
17
+ * ```
6
18
  */
7
19
 
20
+ import { createConnection } from "node:net";
21
+
22
+ /** Matches DEPIN_SOCKET_TIMEOUT in the node (seconds → ms). */
23
+ const DEPIN_SOCKET_TIMEOUT_MS = 30_000;
24
+
25
+ /** Matches DEPIN_MAX_PROTOCOL_SIZE in the node (10 MB) plus slack. */
26
+ const MAX_RESPONSE_BYTES = 10 * 1024 * 1024 + 1024;
27
+
28
+ /** Challenge type as issued by the gateway (AUTH|token|address|MODE). */
29
+ export type DePinChallengeMode = "SEND" | "RECEIVE" | "ADMIN";
30
+
31
+ export interface DePinTarget {
32
+ /** Gateway host, e.g. "127.0.0.1" */
33
+ host: string;
34
+
35
+ /** Gateway TCP port, e.g. 19002 */
36
+ port: number;
37
+
38
+ /**
39
+ * Socket timeout in milliseconds. Defaults to 30 000, matching the node's
40
+ * DEPIN_SOCKET_TIMEOUT.
41
+ */
42
+ timeoutMs?: number;
43
+ }
44
+
8
45
  export interface DePinAuthOptions {
9
- /** DePIN token name (e.g., "MYTOKEN") */
46
+ /** DePIN token name (must start with '&', e.g. "&MYTOKEN" or a section like "&MYTOKEN/GENERAL") */
10
47
  token: string;
11
-
48
+
12
49
  /** Neurai address that will sign challenges */
13
50
  address: string;
14
-
51
+
15
52
  /** Function to sign messages (must return base64 signature) */
16
53
  signMessage: (message: string) => Promise<string>;
17
-
18
- /** Operation mode: SEND or RECEIVE (default: RECEIVE) */
19
- mode?: 'SEND' | 'RECEIVE';
54
+
55
+ /**
56
+ * Challenge mode. Only honored by requestDePinChallenge(); getDePinRPC()
57
+ * derives the mode from the method being called and rejects a conflicting
58
+ * value here.
59
+ */
60
+ mode?: DePinChallengeMode;
20
61
  }
21
62
 
22
63
  export interface DePinChallenge {
23
64
  /** Challenge string from server */
24
65
  challenge: string;
25
-
66
+
26
67
  /** Timeout in seconds */
27
68
  timeout: number;
28
-
69
+
29
70
  /** Complete message that needs to be signed */
30
71
  messageToSign: string;
31
72
  }
32
73
 
74
+ /**
75
+ * Message-to-sign prefix per challenge mode, as verified by the node:
76
+ * DEPIN-SEND (depinsendmsg), DEPIN-GET (RECEIVE challenges) and
77
+ * DEPIN-CLEAR (ADMIN challenges for depinclearmsg).
78
+ */
79
+ const SIGN_PREFIX: Record<DePinChallengeMode, string> = {
80
+ SEND: "DEPIN-SEND",
81
+ RECEIVE: "DEPIN-GET",
82
+ ADMIN: "DEPIN-CLEAR",
83
+ };
84
+
85
+ /**
86
+ * Gateway authentication requirements per JSON-RPC method.
87
+ *
88
+ * - SEND: challenge/signature appended to params; the gateway validates and
89
+ * trims them before dispatching.
90
+ * - ADMIN: depinclearmsg only — the gateway expects
91
+ * [mode, address, challenge, signature] or
92
+ * [mode, scope, address, challenge, signature].
93
+ * - BLOCKED: depingetmsg over the gateway is blocked by a node-side bug (the
94
+ * gateway reads fromaddress from params[3], where depingetmsg carries it at
95
+ * index 1 or 2 and only accepts up to 3 arguments).
96
+ *
97
+ * Every other method is dispatched by the gateway without authentication and
98
+ * must be sent with its params untouched.
99
+ */
100
+ const METHOD_AUTH: Record<string, "SEND" | "ADMIN" | "BLOCKED"> = {
101
+ depinsendmsg: "SEND",
102
+ depinclearmsg: "ADMIN",
103
+ depingetmsg: "BLOCKED",
104
+ };
105
+
33
106
  interface DePinRPCContext {
34
- url: string;
35
- authOptions: DePinAuthOptions;
36
- currentChallenge?: {
37
- challenge: string;
38
- expiresAt: number;
39
- mode: 'SEND' | 'RECEIVE';
40
- };
107
+ target: DePinTarget;
108
+ authOptions?: DePinAuthOptions;
109
+ }
110
+
111
+ function validateTarget(target: DePinTarget): void {
112
+ if (typeof target === "string") {
113
+ throw new Error(
114
+ "getDePinRPC no longer accepts a URL string. The DePIN gateway speaks " +
115
+ "raw TCP, not HTTP: pass an object { host, port }, e.g. " +
116
+ '{ host: "127.0.0.1", port: 19002 }'
117
+ );
118
+ }
119
+ if (!target || typeof target !== "object") {
120
+ throw new Error("A target object { host, port } is required for DePIN RPC");
121
+ }
122
+ if (!target.host || typeof target.host !== "string") {
123
+ throw new Error("target.host must be a non-empty string");
124
+ }
125
+ if (
126
+ typeof target.port !== "number" ||
127
+ !Number.isInteger(target.port) ||
128
+ target.port < 1 ||
129
+ target.port > 65535
130
+ ) {
131
+ throw new Error("target.port must be an integer between 1 and 65535");
132
+ }
133
+ if (
134
+ target.timeoutMs !== undefined &&
135
+ (typeof target.timeoutMs !== "number" || target.timeoutMs <= 0)
136
+ ) {
137
+ throw new Error("target.timeoutMs must be a positive number");
138
+ }
139
+ }
140
+
141
+ function validateAuthOptions(authOptions: DePinAuthOptions): void {
142
+ if (!authOptions.token) {
143
+ throw new Error("Token is required for DePIN authentication");
144
+ }
145
+ if (!authOptions.address) {
146
+ throw new Error("Address is required for DePIN authentication");
147
+ }
148
+ if (
149
+ !authOptions.signMessage ||
150
+ typeof authOptions.signMessage !== "function"
151
+ ) {
152
+ throw new Error("signMessage function is required for DePIN authentication");
153
+ }
41
154
  }
42
155
 
43
156
  /**
44
- * Request a challenge from DePIN server
45
- * Uses the simple protocol: AUTH|token|address|mode
157
+ * Send one line over TCP and read one line back.
158
+ *
159
+ * The gateway protocol is strictly one request line, one response line, one
160
+ * connection per request (the server closes after answering). Bytes are
161
+ * accumulated as Buffers and only decoded once the newline is seen, so a
162
+ * multi-byte UTF-8 character split across 'data' events cannot be corrupted.
46
163
  */
47
- async function requestChallenge(
48
- url: string,
49
- authOptions: DePinAuthOptions
50
- ): Promise<DePinChallenge> {
51
- const mode = authOptions.mode || 'RECEIVE';
52
- const authCommand = `AUTH|${authOptions.token}|${authOptions.address}|${mode}`;
53
-
54
- try {
55
- const response = await fetch(url, {
56
- method: 'POST',
57
- headers: {
58
- 'Content-Type': 'text/plain',
59
- },
60
- body: authCommand,
61
- });
164
+ function sendLine(target: DePinTarget, line: string): Promise<string> {
165
+ const timeoutMs = target.timeoutMs ?? DEPIN_SOCKET_TIMEOUT_MS;
166
+ return new Promise((resolve, reject) => {
167
+ const socket = createConnection({ host: target.host, port: target.port });
168
+ const chunks: Buffer[] = [];
169
+ let received = 0;
170
+ let settled = false;
62
171
 
63
- if (!response.ok) {
64
- throw new Error(`Failed to request challenge: ${response.statusText}`);
65
- }
172
+ const finish = (error: Error | null, response?: string) => {
173
+ if (settled) {
174
+ return;
175
+ }
176
+ settled = true;
177
+ socket.destroy();
178
+ if (error) {
179
+ reject(error);
180
+ } else {
181
+ resolve(response as string);
182
+ }
183
+ };
66
184
 
67
- const responseText = await response.text();
68
-
69
- // Parse response: CHALLENGE|<challenge>|<timeout>
70
- if (!responseText.startsWith('CHALLENGE|')) {
71
- throw new Error(`Invalid challenge response: ${responseText}`);
72
- }
185
+ socket.setTimeout(timeoutMs, () => {
186
+ finish(
187
+ new Error(
188
+ `DePIN request timed out after ${timeoutMs} ms (${target.host}:${target.port})`
189
+ )
190
+ );
191
+ });
73
192
 
74
- const parts = responseText.split('|');
75
- if (parts.length < 3) {
76
- throw new Error(`Malformed challenge response: ${responseText}`);
77
- }
193
+ socket.on("error", (e: Error) => {
194
+ finish(
195
+ new Error(
196
+ `Could not communicate with DePIN gateway at ${target.host}:${target.port}: ${e.message}`
197
+ )
198
+ );
199
+ });
78
200
 
79
- const challenge = parts[1];
80
- const timeout = parseInt(parts[2], 10);
201
+ socket.on("connect", () => {
202
+ socket.write(line.endsWith("\n") ? line : line + "\n");
203
+ });
81
204
 
82
- if (!challenge || isNaN(timeout)) {
83
- throw new Error(`Invalid challenge data: ${responseText}`);
84
- }
205
+ socket.on("data", (chunk: Buffer) => {
206
+ chunks.push(chunk);
207
+ received += chunk.length;
85
208
 
86
- // Construct the message that needs to be signed
87
- const messageToSign = `DEPIN-${mode}|${authOptions.token}|${authOptions.address}|${challenge}`;
209
+ if (received > MAX_RESPONSE_BYTES) {
210
+ finish(new Error("DePIN response exceeded the 10 MB protocol limit"));
211
+ return;
212
+ }
88
213
 
89
- return {
90
- challenge,
91
- timeout,
92
- messageToSign,
93
- };
94
- } catch (error: any) {
95
- throw new Error(`Failed to request DePIN challenge: ${error.message}`);
96
- }
214
+ if (chunk.includes(0x0a)) {
215
+ const all = Buffer.concat(chunks);
216
+ const nl = all.indexOf(0x0a);
217
+ finish(null, all.subarray(0, nl).toString("utf8"));
218
+ }
219
+ });
220
+
221
+ socket.on("close", () => {
222
+ finish(
223
+ new Error(
224
+ "DePIN gateway closed the connection before sending a complete response"
225
+ )
226
+ );
227
+ });
228
+ });
97
229
  }
98
230
 
99
231
  /**
100
- * Make authenticated JSON-RPC request to DePIN server
232
+ * Request a challenge from the DePIN gateway: AUTH|token|address|mode
101
233
  */
102
- async function postDePinData(
103
- url: string,
104
- data: any,
105
- challenge: string,
106
- signature: string
107
- ): Promise<Response> {
108
- const response = await fetch(url, {
109
- method: 'POST',
110
- mode: 'cors',
111
- headers: {
112
- 'Content-Type': 'application/json',
113
- },
114
- body: JSON.stringify(data),
115
- });
116
-
117
- return response;
234
+ async function requestChallenge(
235
+ target: DePinTarget,
236
+ token: string,
237
+ address: string,
238
+ mode: DePinChallengeMode
239
+ ): Promise<DePinChallenge> {
240
+ const responseText = await sendLine(
241
+ target,
242
+ `AUTH|${token}|${address}|${mode}`
243
+ );
244
+
245
+ // Parse response: CHALLENGE|<challenge>|<timeout>
246
+ if (!responseText.startsWith("CHALLENGE|")) {
247
+ throw new Error(`Invalid challenge response: ${responseText}`);
248
+ }
249
+
250
+ const parts = responseText.split("|");
251
+ if (parts.length < 3) {
252
+ throw new Error(`Malformed challenge response: ${responseText}`);
253
+ }
254
+
255
+ const challenge = parts[1];
256
+ const timeout = parseInt(parts[2], 10);
257
+
258
+ if (!challenge || isNaN(timeout)) {
259
+ throw new Error(`Invalid challenge data: ${responseText}`);
260
+ }
261
+
262
+ return {
263
+ challenge,
264
+ timeout,
265
+ messageToSign: `${SIGN_PREFIX[mode]}|${token}|${address}|${challenge}`,
266
+ };
118
267
  }
119
268
 
120
269
  /**
121
- * Get or refresh challenge if needed
270
+ * Request a fresh challenge for one authenticated call.
271
+ *
272
+ * Challenges are strictly single-use: the node erases the nonce from its map
273
+ * when it validates it (ValidateChallenge in depinmsgpoolnet.cpp), so they
274
+ * must never be cached or reused — a second request with the same nonce
275
+ * fails with "Challenge not found".
122
276
  */
123
- async function ensureValidChallenge(
277
+ async function freshChallenge(
124
278
  context: DePinRPCContext,
125
- requiredMode: 'SEND' | 'RECEIVE'
279
+ mode: DePinChallengeMode,
280
+ token: string
126
281
  ): Promise<string> {
127
- const now = Date.now();
128
-
129
- // Check if we have a valid cached challenge
130
- if (
131
- context.currentChallenge &&
132
- context.currentChallenge.mode === requiredMode &&
133
- context.currentChallenge.expiresAt > now
134
- ) {
135
- return context.currentChallenge.challenge;
282
+ const auth = context.authOptions as DePinAuthOptions;
283
+ const challengeData = await requestChallenge(
284
+ context.target,
285
+ token,
286
+ auth.address,
287
+ mode
288
+ );
289
+ return challengeData.challenge;
290
+ }
291
+
292
+ async function signChallenge(
293
+ auth: DePinAuthOptions,
294
+ mode: DePinChallengeMode,
295
+ token: string,
296
+ challenge: string
297
+ ): Promise<string> {
298
+ const messageToSign = `${SIGN_PREFIX[mode]}|${token}|${auth.address}|${challenge}`;
299
+ const signature = await auth.signMessage(messageToSign);
300
+ if (!signature) {
301
+ throw new Error("Signature function returned empty result");
136
302
  }
303
+ return signature;
304
+ }
137
305
 
138
- // Request new challenge
139
- const authOptions = { ...context.authOptions, mode: requiredMode };
140
- const challengeData = await requestChallenge(context.url, authOptions);
306
+ /**
307
+ * Build the params the gateway expects for an authenticated method, using a
308
+ * fresh single-use challenge.
309
+ */
310
+ async function buildAuthenticatedParams(
311
+ context: DePinRPCContext,
312
+ method: string,
313
+ params: any[]
314
+ ): Promise<{ params: any[]; mode: DePinChallengeMode; token: string }> {
315
+ const auth = context.authOptions as DePinAuthOptions;
141
316
 
142
- // Cache challenge (expires 5 seconds before actual timeout for safety)
143
- context.currentChallenge = {
144
- challenge: challengeData.challenge,
145
- expiresAt: now + (challengeData.timeout - 5) * 1000,
146
- mode: requiredMode,
147
- };
317
+ if (method === "depinsendmsg") {
318
+ // Gateway shape: [token, ip, message, fromaddress, (port), challenge, signature]
319
+ // It requires >= 4 params before the appended pair, reads fromaddress
320
+ // from params[3] and validates the challenge against (params[0], params[3]).
321
+ const sendParams = [...params];
322
+ if (sendParams.length === 3) {
323
+ // Fill in fromaddress with the authenticated address.
324
+ sendParams.push(auth.address);
325
+ }
326
+ if (sendParams.length < 4 || typeof sendParams[3] !== "string") {
327
+ throw new Error(
328
+ "depinsendmsg over the gateway needs [token, ip, message, fromaddress]"
329
+ );
330
+ }
331
+ if (sendParams[3] !== auth.address) {
332
+ throw new Error(
333
+ `depinsendmsg fromaddress (${sendParams[3]}) must be the authenticated address (${auth.address})`
334
+ );
335
+ }
336
+ const token = String(sendParams[0]);
337
+ const challenge = await freshChallenge(context, "SEND", token);
338
+ const signature = await signChallenge(auth, "SEND", token, challenge);
339
+ return {
340
+ params: [...sendParams, challenge, signature],
341
+ mode: "SEND",
342
+ token,
343
+ };
344
+ }
148
345
 
149
- return challengeData.challenge;
346
+ // depinclearmsg — ADMIN challenge, owner only. Caller shape: [] | [mode] |
347
+ // [mode, scope]. Gateway shape: [mode, address, challenge, signature] or
348
+ // [mode, scope, address, challenge, signature]. With a scope the challenge
349
+ // must have been issued FOR that scope token.
350
+ if (params.length > 2) {
351
+ throw new Error(
352
+ 'depinclearmsg accepts at most [mode, scope], e.g. ["all", "&TOKEN/GENERAL"]'
353
+ );
354
+ }
355
+ const mode = params.length >= 1 ? params[0] : null;
356
+ const scope = params.length === 2 ? params[1] : undefined;
357
+ if (scope !== undefined && typeof scope !== "string") {
358
+ throw new Error("depinclearmsg scope must be a string");
359
+ }
360
+ const token = scope || auth.token;
361
+ const challenge = await freshChallenge(context, "ADMIN", token);
362
+ const signature = await signChallenge(auth, "ADMIN", token, challenge);
363
+ return {
364
+ params:
365
+ scope === undefined
366
+ ? [mode, auth.address, challenge, signature]
367
+ : [mode, scope, auth.address, challenge, signature],
368
+ mode: "ADMIN",
369
+ token,
370
+ };
150
371
  }
151
372
 
152
373
  /**
153
- * Create a DePIN RPC client with challenge/response authentication
154
- *
155
- * @param url DePIN server URL (e.g., "http://localhost:19002")
156
- * @param authOptions Authentication options including token, address, and signing function
374
+ * Create a DePIN RPC client for the raw-TCP gateway. Node.js only.
375
+ *
376
+ * @param target Gateway address, e.g. { host: "127.0.0.1", port: 19002 }
377
+ * @param authOptions Optional authentication. Without it the client can call
378
+ * the unauthenticated gateway methods (depinreceivemsg, depinsubmitmsg,
379
+ * depingetmsginfo, depingetpoolcontent, depinpoolstats, depinmcpstatus,
380
+ * depinlistsections, depinpoolpkey); calling an authenticated method then
381
+ * fails with a clear error.
157
382
  * @returns Async RPC function
158
- *
383
+ *
159
384
  * @example
160
385
  * ```typescript
161
- * import { getDePinRPC } from "@neuraiproject/neurai-rpc";
162
- *
163
- * const depinRpc = getDePinRPC("http://localhost:19002", {
164
- * token: "MYTOKEN",
165
- * address: "NXmyaddress...",
166
- * signMessage: async (msg) => {
167
- * // Use your wallet to sign the message
168
- * return await wallet.signMessage(msg);
169
- * },
170
- * mode: "SEND"
171
- * });
172
- *
173
- * // Send a DePIN message
174
- * const result = await depinRpc("depinsendmsg", [
175
- * "MYTOKEN",
176
- * "localhost",
177
- * "Hello from DePIN!",
178
- * "NXmyaddress..."
386
+ * import { getDePinRPC } from "@neuraiproject/neurai-rpc/depin";
387
+ *
388
+ * const depinRpc = getDePinRPC(
389
+ * { host: "127.0.0.1", port: 19002 },
390
+ * {
391
+ * token: "&MYTOKEN",
392
+ * address: "NXmyaddress...",
393
+ * signMessage: async (msg) => wallet.signMessage(msg),
394
+ * }
395
+ * );
396
+ *
397
+ * // Authenticated send (challenge/signature handled automatically)
398
+ * await depinRpc("depinsendmsg", [
399
+ * "&MYTOKEN", "127.0.0.1", "Hello from DePIN!", "NXmyaddress...",
179
400
  * ]);
401
+ *
402
+ * // Unauthenticated query (params sent untouched)
403
+ * const info = await depinRpc("depingetmsginfo", []);
180
404
  * ```
181
405
  */
182
- export function getDePinRPC(url: string, authOptions: DePinAuthOptions) {
183
- if (!url) {
184
- throw new Error('URL is required for DePIN RPC');
185
- }
186
- if (!authOptions.token) {
187
- throw new Error('Token is required for DePIN authentication');
188
- }
189
- if (!authOptions.address) {
190
- throw new Error('Address is required for DePIN authentication');
191
- }
192
- if (!authOptions.signMessage || typeof authOptions.signMessage !== 'function') {
193
- throw new Error('signMessage function is required for DePIN authentication');
406
+ export function getDePinRPC(
407
+ target: DePinTarget,
408
+ authOptions?: DePinAuthOptions
409
+ ) {
410
+ validateTarget(target);
411
+ if (authOptions !== undefined) {
412
+ validateAuthOptions(authOptions);
194
413
  }
195
414
 
196
415
  const context: DePinRPCContext = {
197
- url,
416
+ target,
198
417
  authOptions,
199
418
  };
200
419
 
201
- return async function depinRpc(method: string, params: any[]) {
202
- return new Promise(async (resolve, reject) => {
203
- try {
204
- // Determine operation mode from method
205
- const requiredMode = method === 'depinsendmsg' || method === 'depinsubmitmsg'
206
- ? 'SEND'
207
- : 'RECEIVE';
208
-
209
- // Get valid challenge
210
- const challenge = await ensureValidChallenge(context, requiredMode);
420
+ async function depinRpc(
421
+ method: string,
422
+ params: any[],
423
+ isRetry: boolean = false
424
+ ): Promise<any> {
425
+ try {
426
+ const authKind = METHOD_AUTH[method];
211
427
 
212
- // Build message to sign
213
- const messageToSign = `DEPIN-${requiredMode}|${authOptions.token}|${authOptions.address}|${challenge}`;
428
+ if (authKind === "BLOCKED") {
429
+ throw new Error(
430
+ "depingetmsg over the DePIN gateway is blocked by a node-side bug " +
431
+ "(the gateway reads fromaddress from params[3], but depingetmsg " +
432
+ "carries it at index 1 or 2 and accepts at most 3 arguments). " +
433
+ "Use depinreceivemsg over the gateway, or call depingetmsg " +
434
+ "through the node RPC port instead."
435
+ );
436
+ }
214
437
 
215
- // Sign the message
216
- const signature = await authOptions.signMessage(messageToSign);
438
+ let mode: DePinChallengeMode | undefined;
439
+ let token: string | undefined;
440
+ let requestParams = params;
217
441
 
218
- if (!signature) {
219
- throw new Error('Signature function returned empty result');
442
+ if (authKind !== undefined) {
443
+ if (!context.authOptions) {
444
+ throw new Error(
445
+ `${method} requires authentication: create the client with ` +
446
+ "getDePinRPC(target, { token, address, signMessage })"
447
+ );
448
+ }
449
+ const derived: DePinChallengeMode =
450
+ authKind === "SEND" ? "SEND" : "ADMIN";
451
+ if (context.authOptions.mode && context.authOptions.mode !== derived) {
452
+ throw new Error(
453
+ `${method} needs a ${derived} challenge, which conflicts with ` +
454
+ `mode "${context.authOptions.mode}" in the auth options. The ` +
455
+ "mode option is only honored by requestDePinChallenge(); omit " +
456
+ "it here — getDePinRPC derives it per method."
457
+ );
220
458
  }
459
+ const built = await buildAuthenticatedParams(context, method, params);
460
+ requestParams = built.params;
461
+ mode = built.mode;
462
+ token = built.token;
463
+ }
221
464
 
222
- // Add challenge and signature to params
223
- const enhancedParams = [...params, challenge, signature];
465
+ const requestData = {
466
+ jsonrpc: "2.0",
467
+ id: Math.random(),
468
+ method,
469
+ params: requestParams,
470
+ };
224
471
 
225
- // Build JSON-RPC request
226
- const requestData = {
227
- jsonrpc: '2.0',
228
- id: Math.random(),
229
- method,
230
- params: enhancedParams,
231
- };
472
+ const responseText = await sendLine(
473
+ context.target,
474
+ JSON.stringify(requestData)
475
+ );
476
+
477
+ if (responseText.startsWith("ERROR|")) {
478
+ throw new Error(responseText.slice("ERROR|".length));
479
+ }
232
480
 
233
- // Make request
234
- const response = await postDePinData(
235
- url,
236
- requestData,
237
- challenge,
238
- signature
481
+ let responseData: any;
482
+ try {
483
+ responseData = JSON.parse(responseText);
484
+ } catch (e) {
485
+ throw new Error(
486
+ `Invalid JSON-RPC response from DePIN gateway: ${responseText.slice(0, 200)}`
239
487
  );
488
+ }
240
489
 
241
- if (response.ok) {
242
- const responseData = await response.json();
243
-
244
- if (responseData.error) {
245
- // Check if it's an expired challenge error
246
- if (
247
- responseData.error.message &&
248
- responseData.error.message.includes('expired')
249
- ) {
250
- // Clear cached challenge and retry once
251
- context.currentChallenge = undefined;
252
-
253
- // Retry the request with a new challenge
254
- return depinRpc(method, params).then(resolve).catch(reject);
255
- }
256
-
257
- reject({
258
- error: responseData.error,
259
- description: responseData.error.message || 'Unknown error',
260
- });
261
- } else {
262
- resolve(responseData.result);
263
- }
264
- } else {
265
- const errorData = await response.json().catch(() => ({}));
266
- reject({
267
- statusText: response.statusText,
268
- status: response.status,
269
- error: errorData.error,
270
- description: errorData.error?.message || 'Request failed',
271
- });
490
+ if (responseData.error) {
491
+ // On an expired challenge: retry once — the retry requests a fresh
492
+ // nonce, since every authenticated attempt does.
493
+ if (
494
+ !isRetry &&
495
+ mode !== undefined &&
496
+ token !== undefined &&
497
+ responseData.error.message &&
498
+ responseData.error.message.includes("expired")
499
+ ) {
500
+ return depinRpc(method, params, true);
272
501
  }
273
- } catch (error: any) {
274
- reject({
275
- originalError: error,
276
- type: 'DePinRequestError',
277
- error: error.message || 'Failed to communicate with DePIN server',
278
- description: 'Check that the DePIN server URL is correct and that the server is running',
279
- });
502
+
503
+ throw {
504
+ error: responseData.error,
505
+ description: responseData.error.message || "Unknown error",
506
+ };
280
507
  }
281
- });
282
- };
508
+
509
+ return responseData.result;
510
+ } catch (error: any) {
511
+ if (error && (error.error || error.description)) {
512
+ // Already a structured RPC error
513
+ throw error;
514
+ }
515
+ throw {
516
+ originalError: error,
517
+ type: "DePinRequestError",
518
+ error:
519
+ (error && error.message) ||
520
+ "Failed to communicate with DePIN gateway",
521
+ description:
522
+ "Check that the DePIN gateway host/port are correct and that the " +
523
+ "node is running with the gateway enabled",
524
+ };
525
+ }
526
+ }
527
+
528
+ return (method: string, params: any[]) => depinRpc(method, params);
283
529
  }
284
530
 
285
531
  /**
286
- * Helper function to request a challenge without making an RPC call
287
- * Useful for testing or manual challenge handling
532
+ * Request a challenge without making an RPC call. Useful for testing or
533
+ * manual challenge handling. Honors authOptions.mode ("SEND", "RECEIVE" or
534
+ * "ADMIN"; default "RECEIVE") and returns the exact message that must be
535
+ * signed for that mode (DEPIN-SEND|, DEPIN-GET| or DEPIN-CLEAR|).
288
536
  */
289
537
  export async function requestDePinChallenge(
290
- url: string,
538
+ target: DePinTarget,
291
539
  authOptions: DePinAuthOptions
292
540
  ): Promise<DePinChallenge> {
293
- return requestChallenge(url, authOptions);
541
+ validateTarget(target);
542
+ validateAuthOptions(authOptions);
543
+ const mode: DePinChallengeMode = authOptions.mode || "RECEIVE";
544
+ return requestChallenge(target, authOptions.token, authOptions.address, mode);
294
545
  }