@neuraiproject/neurai-rpc 0.4.3 → 0.4.5
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_EXAMPLES.md +271 -0
- package/README.md +49 -4
- package/depin.ts +294 -0
- package/dist/index.cjs +458 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.mjs +457 -1
- package/dist/index.mjs.map +1 -1
- package/dist/types.d.ts +74 -1
- package/dist/types.d.ts.map +1 -1
- package/docs.json +13 -0
- package/docs.ts +399 -0
- package/index.ts +9 -0
- package/neurai_methods.md +4936 -0
- package/package.json +4 -4
- package/test-depin.ts +187 -0
- package/tsconfig.json +26 -0
- package/test-getpubkey.js +0 -149
|
@@ -0,0 +1,271 @@
|
|
|
1
|
+
# DePIN RPC Examples
|
|
2
|
+
|
|
3
|
+
This file demonstrates how to use the DePIN messaging functionality in neurai-rpc.
|
|
4
|
+
|
|
5
|
+
## Basic Setup
|
|
6
|
+
|
|
7
|
+
```javascript
|
|
8
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
9
|
+
|
|
10
|
+
// You need a function that can sign messages with your Neurai address
|
|
11
|
+
// This example uses neurai-cli via the standard RPC
|
|
12
|
+
import { getRPC, methods } from "@neuraiproject/neurai-rpc";
|
|
13
|
+
|
|
14
|
+
const standardRpc = getRPC("user", "password", "http://localhost:19001");
|
|
15
|
+
|
|
16
|
+
async function signMessage(message) {
|
|
17
|
+
// Sign using neurai-cli via RPC
|
|
18
|
+
return await standardRpc(methods.signmessage, ["NXyouraddress...", message]);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
// Create DePIN RPC client
|
|
22
|
+
const depinRpc = getDePinRPC("http://localhost:19002", {
|
|
23
|
+
token: "MYTOKEN",
|
|
24
|
+
address: "NXyouraddress...",
|
|
25
|
+
signMessage: signMessage,
|
|
26
|
+
mode: "SEND"
|
|
27
|
+
});
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
## Example 1: Send a DePIN Message
|
|
31
|
+
|
|
32
|
+
```javascript
|
|
33
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
34
|
+
|
|
35
|
+
async function sendDePinMessage() {
|
|
36
|
+
const depinRpc = getDePinRPC("http://localhost:19002", {
|
|
37
|
+
token: "MYTOKEN",
|
|
38
|
+
address: "NXsenderAddress...",
|
|
39
|
+
signMessage: async (msg) => {
|
|
40
|
+
// Use your signing method
|
|
41
|
+
return await yourWallet.signMessage(msg);
|
|
42
|
+
},
|
|
43
|
+
mode: "SEND"
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
try {
|
|
47
|
+
const result = await depinRpc("depinsendmsg", [
|
|
48
|
+
"MYTOKEN", // token
|
|
49
|
+
"localhost", // server (use "localhost" for local pool)
|
|
50
|
+
"Hello DePIN!", // message
|
|
51
|
+
"NXsenderAddress..." // from address
|
|
52
|
+
]);
|
|
53
|
+
|
|
54
|
+
console.log("Message sent successfully:", result);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
console.error("Failed to send message:", error);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
## Example 2: Retrieve DePIN Messages
|
|
62
|
+
|
|
63
|
+
```javascript
|
|
64
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
65
|
+
|
|
66
|
+
async function getDePinMessages() {
|
|
67
|
+
const depinRpc = getDePinRPC("http://localhost:19002", {
|
|
68
|
+
token: "MYTOKEN",
|
|
69
|
+
address: "NXreceiverAddress...",
|
|
70
|
+
signMessage: async (msg) => {
|
|
71
|
+
return await yourWallet.signMessage(msg);
|
|
72
|
+
},
|
|
73
|
+
mode: "RECEIVE"
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
try {
|
|
77
|
+
const messages = await depinRpc("depingetmsg", [
|
|
78
|
+
"MYTOKEN", // token
|
|
79
|
+
"localhost", // server or address
|
|
80
|
+
"NXreceiverAddress..." // your address
|
|
81
|
+
]);
|
|
82
|
+
|
|
83
|
+
console.log("Received messages:", messages);
|
|
84
|
+
|
|
85
|
+
messages.forEach(msg => {
|
|
86
|
+
console.log(`From: ${msg.sender}`);
|
|
87
|
+
console.log(`Message: ${msg.message}`);
|
|
88
|
+
console.log(`Time: ${new Date(msg.timestamp * 1000).toLocaleString()}`);
|
|
89
|
+
});
|
|
90
|
+
} catch (error) {
|
|
91
|
+
console.error("Failed to get messages:", error);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
## Example 3: Submit Pre-encrypted Message
|
|
97
|
+
|
|
98
|
+
```javascript
|
|
99
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
100
|
+
|
|
101
|
+
async function submitPreEncryptedMessage() {
|
|
102
|
+
const depinRpc = getDePinRPC("http://localhost:19002", {
|
|
103
|
+
token: "MYTOKEN",
|
|
104
|
+
address: "NXsenderAddress...",
|
|
105
|
+
signMessage: async (msg) => {
|
|
106
|
+
return await yourWallet.signMessage(msg);
|
|
107
|
+
},
|
|
108
|
+
mode: "SEND"
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
try {
|
|
112
|
+
// Assume you have a pre-encrypted and signed message in hex format
|
|
113
|
+
const hexMessage = "0a1b2c3d..."; // Your encrypted message hex
|
|
114
|
+
|
|
115
|
+
const result = await depinRpc("depinsubmitmsg", [hexMessage]);
|
|
116
|
+
|
|
117
|
+
console.log("Pre-encrypted message submitted:", result);
|
|
118
|
+
} catch (error) {
|
|
119
|
+
console.error("Failed to submit message:", error);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## Example 4: Using with Browser Wallet
|
|
125
|
+
|
|
126
|
+
```javascript
|
|
127
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
128
|
+
|
|
129
|
+
// Example with a hypothetical browser wallet extension
|
|
130
|
+
async function useBrowserWallet() {
|
|
131
|
+
// Check if wallet is available
|
|
132
|
+
if (!window.neuraiWallet) {
|
|
133
|
+
throw new Error("Neurai wallet extension not found");
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// Request wallet connection
|
|
137
|
+
const accounts = await window.neuraiWallet.connect();
|
|
138
|
+
const address = accounts[0];
|
|
139
|
+
|
|
140
|
+
// Create DePIN RPC client with wallet signing
|
|
141
|
+
const depinRpc = getDePinRPC("http://localhost:19002", {
|
|
142
|
+
token: "MYTOKEN",
|
|
143
|
+
address: address,
|
|
144
|
+
signMessage: async (msg) => {
|
|
145
|
+
// Use wallet extension to sign
|
|
146
|
+
return await window.neuraiWallet.signMessage(address, msg);
|
|
147
|
+
},
|
|
148
|
+
mode: "SEND"
|
|
149
|
+
});
|
|
150
|
+
|
|
151
|
+
// Send message
|
|
152
|
+
const result = await depinRpc("depinsendmsg", [
|
|
153
|
+
"MYTOKEN",
|
|
154
|
+
"localhost",
|
|
155
|
+
"Hello from browser!",
|
|
156
|
+
address
|
|
157
|
+
]);
|
|
158
|
+
|
|
159
|
+
console.log("Message sent:", result);
|
|
160
|
+
}
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
## Example 5: Manual Challenge Handling
|
|
164
|
+
|
|
165
|
+
```javascript
|
|
166
|
+
import { requestDePinChallenge } from "@neuraiproject/neurai-rpc";
|
|
167
|
+
|
|
168
|
+
async function manualChallengeFlow() {
|
|
169
|
+
// Request a challenge manually
|
|
170
|
+
const challengeData = await requestDePinChallenge("http://localhost:19002", {
|
|
171
|
+
token: "MYTOKEN",
|
|
172
|
+
address: "NXyourAddress...",
|
|
173
|
+
signMessage: async () => "", // Not used in requestChallenge
|
|
174
|
+
mode: "SEND"
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
console.log("Challenge:", challengeData.challenge);
|
|
178
|
+
console.log("Expires in:", challengeData.timeout, "seconds");
|
|
179
|
+
console.log("Message to sign:", challengeData.messageToSign);
|
|
180
|
+
|
|
181
|
+
// Now you can sign this message manually
|
|
182
|
+
const signature = await yourSigningFunction(challengeData.messageToSign);
|
|
183
|
+
|
|
184
|
+
console.log("Signature:", signature);
|
|
185
|
+
}
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
## Example 6: Error Handling
|
|
189
|
+
|
|
190
|
+
```javascript
|
|
191
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
192
|
+
|
|
193
|
+
async function robustDePinCall() {
|
|
194
|
+
const depinRpc = getDePinRPC("http://localhost:19002", {
|
|
195
|
+
token: "MYTOKEN",
|
|
196
|
+
address: "NXyourAddress...",
|
|
197
|
+
signMessage: async (msg) => {
|
|
198
|
+
try {
|
|
199
|
+
return await yourWallet.signMessage(msg);
|
|
200
|
+
} catch (error) {
|
|
201
|
+
throw new Error(`Signing failed: ${error.message}`);
|
|
202
|
+
}
|
|
203
|
+
},
|
|
204
|
+
mode: "SEND"
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
try {
|
|
208
|
+
const result = await depinRpc("depinsendmsg", [
|
|
209
|
+
"MYTOKEN",
|
|
210
|
+
"localhost",
|
|
211
|
+
"Test message",
|
|
212
|
+
"NXyourAddress..."
|
|
213
|
+
]);
|
|
214
|
+
|
|
215
|
+
return { success: true, result };
|
|
216
|
+
} catch (error) {
|
|
217
|
+
// Handle different error types
|
|
218
|
+
if (error.type === 'DePinRequestError') {
|
|
219
|
+
console.error("DePIN request failed:", error.error);
|
|
220
|
+
console.error("Description:", error.description);
|
|
221
|
+
} else if (error.error?.message?.includes('challenge')) {
|
|
222
|
+
console.error("Challenge error:", error.error.message);
|
|
223
|
+
} else if (error.error?.message?.includes('signature')) {
|
|
224
|
+
console.error("Signature verification failed");
|
|
225
|
+
} else {
|
|
226
|
+
console.error("Unknown error:", error);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
return { success: false, error: error.error };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
## Example 7: Connecting to Remote DePIN Node
|
|
235
|
+
|
|
236
|
+
```javascript
|
|
237
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
238
|
+
|
|
239
|
+
async function connectToRemoteNode() {
|
|
240
|
+
const depinRpc = getDePinRPC("http://remote-node.example.com:19002", {
|
|
241
|
+
token: "MYTOKEN",
|
|
242
|
+
address: "NXyourAddress...",
|
|
243
|
+
signMessage: async (msg) => {
|
|
244
|
+
return await yourWallet.signMessage(msg);
|
|
245
|
+
},
|
|
246
|
+
mode: "SEND"
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
// The library handles challenge/response automatically
|
|
250
|
+
const result = await depinRpc("depinsendmsg", [
|
|
251
|
+
"MYTOKEN",
|
|
252
|
+
"remote-node.example.com:19002",
|
|
253
|
+
"Hello remote node!",
|
|
254
|
+
"NXyourAddress..."
|
|
255
|
+
]);
|
|
256
|
+
|
|
257
|
+
console.log("Sent to remote node:", result);
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
## Notes
|
|
262
|
+
|
|
263
|
+
1. **Challenge Expiry**: Challenges expire after 60 seconds. The library automatically handles expiry and retries with a new challenge.
|
|
264
|
+
|
|
265
|
+
2. **Signature Format**: The signature must be in base64 format as returned by Neurai's `signmessage` RPC command.
|
|
266
|
+
|
|
267
|
+
3. **Mode Selection**: Use `mode: "SEND"` for `depinsendmsg` and `depinsubmitmsg`, and `mode: "RECEIVE"` for `depingetmsg`.
|
|
268
|
+
|
|
269
|
+
4. **Port**: DePIN messaging uses port 19002 by default (configurable via `-depinmsgport`).
|
|
270
|
+
|
|
271
|
+
5. **Token Requirement**: You must hold the specified DePIN token to send or receive messages.
|
package/README.md
CHANGED
|
@@ -4,8 +4,10 @@ A package that will help you do RPC calls from Node.js to your Neurai node, that
|
|
|
4
4
|
|
|
5
5
|
URLs for locally installed Neurai nodes.
|
|
6
6
|
|
|
7
|
-
- http://127.0.0.1:19001 for mainnet
|
|
8
|
-
- http://127.0.0.1:
|
|
7
|
+
- http://127.0.0.1:19001 for mainnet (Standard RPC)
|
|
8
|
+
- http://127.0.0.1:19002 for mainnet (DePIN Messaging)
|
|
9
|
+
- http://127.0.0.1:19101 for testnet (Standard RPC)
|
|
10
|
+
- http://127.0.0.1:19102 for testnet (DePIN Messaging)
|
|
9
11
|
|
|
10
12
|
Neurai as a service, you don't need your own node
|
|
11
13
|
|
|
@@ -18,7 +20,9 @@ Neurai as a service, you don't need your own node
|
|
|
18
20
|
npm install @neuraiproject/neurai-rpc
|
|
19
21
|
```
|
|
20
22
|
|
|
21
|
-
#
|
|
23
|
+
# Standard RPC Usage
|
|
24
|
+
|
|
25
|
+
## Example using ES modules
|
|
22
26
|
|
|
23
27
|
This example uses Neurai as a service from https://rpc-main.neurai.org.
|
|
24
28
|
|
|
@@ -37,7 +41,7 @@ const params = [];
|
|
|
37
41
|
rpc(methods.getblockcount, params).then(console.log);
|
|
38
42
|
```
|
|
39
43
|
|
|
40
|
-
|
|
44
|
+
## Example using CommonJS
|
|
41
45
|
|
|
42
46
|
```
|
|
43
47
|
|
|
@@ -64,6 +68,47 @@ will print out
|
|
|
64
68
|
{ name: 'ELVIS', amount: 1, units: 8, reissuable: 1, has_ipfs: 0 }
|
|
65
69
|
```
|
|
66
70
|
|
|
71
|
+
# DePIN Messaging Usage
|
|
72
|
+
|
|
73
|
+
DePIN (Decentralized Physical Infrastructure Network) messaging uses port 19002 and requires cryptographic signature authentication instead of username/password.
|
|
74
|
+
|
|
75
|
+
## Basic DePIN Example
|
|
76
|
+
|
|
77
|
+
```javascript
|
|
78
|
+
import { getDePinRPC } from "@neuraiproject/neurai-rpc";
|
|
79
|
+
|
|
80
|
+
// Function to sign messages with your private key
|
|
81
|
+
async function signMessage(message) {
|
|
82
|
+
// Implement your signing logic here
|
|
83
|
+
// Return base64-encoded signature
|
|
84
|
+
return "signature_base64";
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const depinRPC = await getDePinRPC({
|
|
88
|
+
depinUrl: "http://localhost:19002",
|
|
89
|
+
address: "NYourAddressHere",
|
|
90
|
+
signMessage: signMessage
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
// Send a DePIN message
|
|
94
|
+
const result = await depinRPC("depinsendmsg", ["SEND", "ipfs_hash", 3600]);
|
|
95
|
+
console.log(result);
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
For complete DePIN examples including browser wallet integration, error handling, and advanced usage, see [DEPIN_EXAMPLES.md](./DEPIN_EXAMPLES.md).
|
|
99
|
+
|
|
100
|
+
## DePIN Authentication
|
|
101
|
+
|
|
102
|
+
Port 19002 uses a challenge-response authentication protocol:
|
|
103
|
+
|
|
104
|
+
1. Client requests a challenge from the server
|
|
105
|
+
2. Server returns a random challenge string with expiration time (60 seconds)
|
|
106
|
+
3. Client signs the challenge with their private key
|
|
107
|
+
4. Client sends RPC request with address and signature
|
|
108
|
+
5. Server verifies the signature against the address
|
|
109
|
+
|
|
110
|
+
The `getDePinRPC` function handles this authentication flow automatically, including challenge caching and automatic retry on expiration.
|
|
111
|
+
|
|
67
112
|
## Example list all generated addresses in a Wallet (Raven core)
|
|
68
113
|
|
|
69
114
|
Use method `listreceivedbyaddress` to receive a list of all generated addresses.
|
package/depin.ts
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
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.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
export interface DePinAuthOptions {
|
|
9
|
+
/** DePIN token name (e.g., "MYTOKEN") */
|
|
10
|
+
token: string;
|
|
11
|
+
|
|
12
|
+
/** Neurai address that will sign challenges */
|
|
13
|
+
address: string;
|
|
14
|
+
|
|
15
|
+
/** Function to sign messages (must return base64 signature) */
|
|
16
|
+
signMessage: (message: string) => Promise<string>;
|
|
17
|
+
|
|
18
|
+
/** Operation mode: SEND or RECEIVE (default: RECEIVE) */
|
|
19
|
+
mode?: 'SEND' | 'RECEIVE';
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export interface DePinChallenge {
|
|
23
|
+
/** Challenge string from server */
|
|
24
|
+
challenge: string;
|
|
25
|
+
|
|
26
|
+
/** Timeout in seconds */
|
|
27
|
+
timeout: number;
|
|
28
|
+
|
|
29
|
+
/** Complete message that needs to be signed */
|
|
30
|
+
messageToSign: string;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
interface DePinRPCContext {
|
|
34
|
+
url: string;
|
|
35
|
+
authOptions: DePinAuthOptions;
|
|
36
|
+
currentChallenge?: {
|
|
37
|
+
challenge: string;
|
|
38
|
+
expiresAt: number;
|
|
39
|
+
mode: 'SEND' | 'RECEIVE';
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Request a challenge from DePIN server
|
|
45
|
+
* Uses the simple protocol: AUTH|token|address|mode
|
|
46
|
+
*/
|
|
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
|
+
});
|
|
62
|
+
|
|
63
|
+
if (!response.ok) {
|
|
64
|
+
throw new Error(`Failed to request challenge: ${response.statusText}`);
|
|
65
|
+
}
|
|
66
|
+
|
|
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
|
+
}
|
|
73
|
+
|
|
74
|
+
const parts = responseText.split('|');
|
|
75
|
+
if (parts.length < 3) {
|
|
76
|
+
throw new Error(`Malformed challenge response: ${responseText}`);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const challenge = parts[1];
|
|
80
|
+
const timeout = parseInt(parts[2], 10);
|
|
81
|
+
|
|
82
|
+
if (!challenge || isNaN(timeout)) {
|
|
83
|
+
throw new Error(`Invalid challenge data: ${responseText}`);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// Construct the message that needs to be signed
|
|
87
|
+
const messageToSign = `DEPIN-${mode}|${authOptions.token}|${authOptions.address}|${challenge}`;
|
|
88
|
+
|
|
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
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Make authenticated JSON-RPC request to DePIN server
|
|
101
|
+
*/
|
|
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;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Get or refresh challenge if needed
|
|
122
|
+
*/
|
|
123
|
+
async function ensureValidChallenge(
|
|
124
|
+
context: DePinRPCContext,
|
|
125
|
+
requiredMode: 'SEND' | 'RECEIVE'
|
|
126
|
+
): 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;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Request new challenge
|
|
139
|
+
const authOptions = { ...context.authOptions, mode: requiredMode };
|
|
140
|
+
const challengeData = await requestChallenge(context.url, authOptions);
|
|
141
|
+
|
|
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
|
+
};
|
|
148
|
+
|
|
149
|
+
return challengeData.challenge;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
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
|
|
157
|
+
* @returns Async RPC function
|
|
158
|
+
*
|
|
159
|
+
* @example
|
|
160
|
+
* ```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..."
|
|
179
|
+
* ]);
|
|
180
|
+
* ```
|
|
181
|
+
*/
|
|
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');
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
const context: DePinRPCContext = {
|
|
197
|
+
url,
|
|
198
|
+
authOptions,
|
|
199
|
+
};
|
|
200
|
+
|
|
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);
|
|
211
|
+
|
|
212
|
+
// Build message to sign
|
|
213
|
+
const messageToSign = `DEPIN-${requiredMode}|${authOptions.token}|${authOptions.address}|${challenge}`;
|
|
214
|
+
|
|
215
|
+
// Sign the message
|
|
216
|
+
const signature = await authOptions.signMessage(messageToSign);
|
|
217
|
+
|
|
218
|
+
if (!signature) {
|
|
219
|
+
throw new Error('Signature function returned empty result');
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Add challenge and signature to params
|
|
223
|
+
const enhancedParams = [...params, challenge, signature];
|
|
224
|
+
|
|
225
|
+
// Build JSON-RPC request
|
|
226
|
+
const requestData = {
|
|
227
|
+
jsonrpc: '2.0',
|
|
228
|
+
id: Math.random(),
|
|
229
|
+
method,
|
|
230
|
+
params: enhancedParams,
|
|
231
|
+
};
|
|
232
|
+
|
|
233
|
+
// Make request
|
|
234
|
+
const response = await postDePinData(
|
|
235
|
+
url,
|
|
236
|
+
requestData,
|
|
237
|
+
challenge,
|
|
238
|
+
signature
|
|
239
|
+
);
|
|
240
|
+
|
|
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
|
+
});
|
|
272
|
+
}
|
|
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
|
+
});
|
|
280
|
+
}
|
|
281
|
+
});
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Helper function to request a challenge without making an RPC call
|
|
287
|
+
* Useful for testing or manual challenge handling
|
|
288
|
+
*/
|
|
289
|
+
export async function requestDePinChallenge(
|
|
290
|
+
url: string,
|
|
291
|
+
authOptions: DePinAuthOptions
|
|
292
|
+
): Promise<DePinChallenge> {
|
|
293
|
+
return requestChallenge(url, authOptions);
|
|
294
|
+
}
|