-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.js
More file actions
1002 lines (884 loc) · 35 KB
/
example.js
File metadata and controls
1002 lines (884 loc) · 35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* SailBE SDK API Example - JavaScript/Node.js
*
* This script demonstrates how to:
* 1. Authenticate using direct or SIWE wallet signatures
* 2. Use JWT tokens for subsequent API requests
* 3. Call all available SDK endpoints
*
* Requirements:
* npm install ethers axios form-data
* or
* yarn add ethers axios form-data
*/
const { ethers } = require('ethers');
const axios = require('axios');
const fs = require('fs');
const FormData = require('form-data');
require('dotenv').config();
// ============================================================================
// CONFIGURATION
// ============================================================================
// Base URL of the Sail API server
// Production API URL: https://app.sail.money/prod
const BASE_URL = process.env.SAIL_API_URL || 'https://app.sail.money/prod';
// Project and Page IDs
// Default values for Sail production
const PROJECT_ID = process.env.SAIL_PROJECT_ID || 'sail';
const PAGE_ID = process.env.SAIL_PAGE_ID || 'home';
// Wallet configuration
// IMPORTANT: Never commit private keys to version control!
// Get your private key from: https://sail.money/manage-wallet/7702
// Use environment variables or secure key management in production
const PRIVATE_KEY = process.env.SAIL_PRIVATE_KEY || ('0x' + '0'.repeat(64)); // Replace with your private key
let WALLET_ADDRESS = null; // Will be derived from private key
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/**
* Sign a message using Ethereum private key.
*
* @param {string} message - The message to sign
* @param {string} privateKey - Private key in hex format (with or without 0x prefix)
* @returns {Promise<string>} Signature in hex format
*/
async function signMessage(message, privateKey) {
// Create wallet from private key
const wallet = new ethers.Wallet(privateKey);
// Sign message
const signature = await wallet.signMessage(message);
return signature;
}
/**
* Get wallet address from private key.
*
* @param {string} privateKey - Private key in hex format
* @returns {string} Wallet address in hex format
*/
function getWalletAddress(privateKey) {
const wallet = new ethers.Wallet(privateKey);
return wallet.address;
}
// ============================================================================
// API CLIENT CLASS
// ============================================================================
class SailAPIClient {
/**
* Initialize the API client.
*
* @param {string} baseUrl - Base URL of the API server
* @param {string} projectId - Project ID
* @param {string} pageId - Page ID
* @param {string|null} token - Optional JWT token (if already authenticated)
*/
constructor(baseUrl, projectId, pageId, token = null) {
this.baseUrl = baseUrl.replace(/\/$/, '');
this.projectId = projectId;
this.pageId = pageId;
this.token = token;
this.basePath = `/api/v1/projects/${projectId}/pages/${pageId}`;
}
/**
* Get request headers with authentication.
*
* @returns {Object} Headers object
*/
_getHeaders() {
const headers = {
'Content-Type': 'application/json'
};
if (this.token) {
headers['Authorization'] = `Bearer ${this.token}`;
}
return headers;
}
/**
* Make an API request.
*
* @param {string} method - HTTP method (GET, POST, PUT, etc.)
* @param {string} endpoint - API endpoint path
* @param {Object} options - Additional options (params, data, headers, etc.)
* @returns {Promise<Object>} Response JSON as object
*/
async _request(method, endpoint, options = {}) {
const url = `${this.baseUrl}${this.basePath}${endpoint}`;
const headers = this._getHeaders();
if (options.headers) {
Object.assign(headers, options.headers);
}
const config = {
method,
url,
headers,
...options
};
const response = await axios(config);
return response.data;
}
// ========================================================================
// AUTHENTICATION
// ========================================================================
/**
* Authenticate using wallet signature.
*
* @param {string} walletAddress - Wallet address
* @param {string} signature - Signature of the authentication message
* @returns {Promise<Object>} Authentication response with token
*/
async authenticate(walletAddress, signature = null, authPayload = null, domain = null) {
const url = `${this.baseUrl}${this.basePath}/authenticate`;
const payload = {
walletAddress
};
if (signature) payload.signature = signature;
if (authPayload) payload.payload = authPayload;
if (domain) payload.domain = domain;
const response = await axios.post(url, payload);
// Store token for future requests
if (response.data.token) {
this.token = response.data.token;
}
return response.data;
}
/**
* Request the unique direct-auth payload for a smart account wallet.
*
* @param {string} walletAddress - Smart account wallet address
* @param {string|null} domain - Optional SIWE domain override
* @returns {Promise<{payload: string, instructionMessage?: string}>} Direct-auth payload response
*/
async requestDirectAuthPayload(walletAddress, domain = null) {
return this.authenticate(walletAddress, null, null, domain);
}
/**
* Complete direct authentication with the signed direct-auth payload.
*
* @param {string} walletAddress - Smart account wallet address
* @param {string} signature - Signature over the direct-auth payload
* @param {string} authPayload - Payload returned by `requestDirectAuthPayload`
* @param {string|null} domain - Optional SIWE domain override
* @returns {Promise<Object>} Authentication response with token
*/
async completeDirectAuth(walletAddress, signature, authPayload, domain = null) {
return this.authenticate(walletAddress, signature, authPayload, domain);
}
/**
* Start custom SIWE authentication.
*
* @param {string} address - Admin signer wallet address
* @param {number} chainId - Chain ID used to render the SIWE message
* @param {string|null} domain - Optional SIWE domain override
* @param {"byWallet"|"byUser"} identityMode - Identity mode (`byWallet` recommended, `byUser` legacy only)
* @returns {Promise<{sessionId: string, message: string}>} SIWE auth session
*/
async initiateSiweAuth(address, chainId = 8453, domain = null, identityMode = 'byWallet') {
const url = `${this.baseUrl}${this.basePath}/auth/initiate`;
const payload = {
method: 'siwe',
address,
chainId,
identityMode
};
if (domain) {
payload.domain = domain;
}
const response = await axios.post(url, payload);
return response.data;
}
/**
* Complete custom SIWE authentication.
*
* @param {string} sessionId - Session ID returned by `initiateSiweAuth`
* @param {string} signature - Signature over the SIWE message
* @param {string} walletAddress - Admin signer wallet address
* @param {"byWallet"|"byUser"} identityMode - Identity mode used during initiation
* @returns {Promise<Object>} Authentication response with token
*/
async completeSiweAuth(sessionId, signature, walletAddress, identityMode = 'byWallet') {
const url = `${this.baseUrl}${this.basePath}/auth/complete`;
const payload = {
method: 'siwe',
sessionId,
signature,
walletAddress,
identityMode
};
const response = await axios.post(url, payload);
this.token = response.data.token;
return response.data;
}
// ========================================================================
// BALANCE
// ========================================================================
/**
* Get balance for a wallet.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @returns {Promise<Object>} Balance information
*/
async getBalance(tokenAddress = null, chainId = null) {
const params = {};
if (tokenAddress) params.tokenAddress = tokenAddress;
if (chainId) params.chainId = chainId;
return this._request('GET', '/balance', { params });
}
// ========================================================================
// METRICS
// ========================================================================
/**
* Execute a configured metrics endpoint.
*
* @param {string} endpointId - Metrics endpoint ID
* @param {Object|null} params - Optional query params passed through to the configured tool/graph
* @returns {Promise<Object>} Metrics response shaped like { message, result }
*/
async getMetrics(endpointId, params = null) {
return this._request('GET', `/metrics/${endpointId}`, { params: params || {} });
}
async getMetricsBalance(params = null) {
return this.getMetrics('balance', params);
}
async getMetricsEarnings(params = null) {
return this.getMetrics('earnings', params);
}
async getMetricsHistory(params = null) {
return this.getMetrics('history', params);
}
async getMetricsPortfolio(params = null) {
return this.getMetrics('portfolio', params);
}
async getMetricsUserMetrics(params = null) {
return this.getMetrics('user-metrics', params);
}
async getMetricsYield(params = null) {
return this.getMetrics('yield', params);
}
// ========================================================================
// DEPOSIT
// ========================================================================
/**
* Deposit funds.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} amount - Amount to deposit (human-readable format, e.g., '1' for 1 ETH, '10' for 10 USDC)
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @returns {Promise<Object>} Deposit response
*/
async deposit(amount, tokenAddress = null, chainId = null) {
const payload = {
amount
};
if (tokenAddress) payload.tokenAddress = tokenAddress;
if (chainId) payload.chainId = chainId;
return this._request('POST', '/deposit', { data: payload });
}
/**
* Get deposit information.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Deposit info including balance, permitted tokens, etc.
*/
async getDepositInfo() {
return this._request('GET', '/deposit-info');
}
/**
* Execute pre-deposit hooks.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} amount - Amount to deposit (human-readable format, e.g., '1' for 1 ETH, '10' for 10 USDC)
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @returns {Promise<Object>} Pre-deposit hooks response
*/
async preDepositHooks(amount, tokenAddress = null, chainId = null) {
const payload = {
amount
};
if (tokenAddress) payload.tokenAddress = tokenAddress;
if (chainId) payload.chainId = chainId;
return this._request('POST', '/deposit/pre-hooks', { data: payload });
}
/**
* Execute post-deposit hooks.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} amount - Amount that was deposited (human-readable format, e.g., '1' for 1 ETH, '10' for 10 USDC)
* @param {string} txHash - Transaction hash
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @param {string} status - Transaction status ("success" or "error")
* @returns {Promise<Object>} Post-deposit hooks response
*/
async postDepositHooks(amount, txHash, tokenAddress = null, chainId = null, status = 'success') {
const payload = {
amount,
txHash,
status
};
if (tokenAddress) payload.tokenAddress = tokenAddress;
if (chainId) payload.chainId = chainId;
return this._request('POST', '/deposit/post-hooks', { data: payload });
}
// ========================================================================
// WITHDRAW
// ========================================================================
/**
* Withdraw funds.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} amount - Amount to withdraw (human-readable format, e.g., '1' for 1 ETH, '10' for 10 USDC)
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @returns {Promise<Object>} Withdraw response
*/
async withdraw(amount, tokenAddress = null, chainId = null) {
const payload = {
amount
};
if (tokenAddress) payload.tokenAddress = tokenAddress;
if (chainId) payload.chainId = chainId;
return this._request('POST', '/withdraw', { data: payload });
}
/**
* Get withdraw information.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Withdraw info including balance, permitted tokens, etc.
*/
async getWithdrawInfo() {
return this._request('GET', '/withdraw-info');
}
/**
* Execute pre-withdraw hooks.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} amount - Amount to withdraw (human-readable format, e.g., '1' for 1 ETH, '10' for 10 USDC)
* @param {string} recipient - Recipient address for the withdrawal
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @returns {Promise<Object>} Pre-withdraw hooks response
*/
async preWithdrawHooks(amount, recipient, tokenAddress = null, chainId = null) {
const payload = {
amount,
recipient
};
if (tokenAddress) payload.tokenAddress = tokenAddress;
if (chainId) payload.chainId = chainId;
return this._request('POST', '/withdraw/pre-hooks', { data: payload });
}
/**
* Execute post-withdraw hooks.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} amount - Amount that was withdrawn (human-readable format, e.g., '1' for 1 ETH, '10' for 10 USDC)
* @param {string} txHash - Transaction hash
* @param {string} recipient - Recipient address for the withdrawal
* @param {string|null} tokenAddress - Optional token address
* @param {number|null} chainId - Optional chain ID
* @param {string} status - Transaction status ("success" or "error")
* @returns {Promise<Object>} Post-withdraw hooks response
*/
async postWithdrawHooks(amount, txHash, recipient, tokenAddress = null, chainId = null, status = 'success') {
const payload = {
amount,
txHash,
recipient,
status
};
if (tokenAddress) payload.tokenAddress = tokenAddress;
if (chainId) payload.chainId = chainId;
return this._request('POST', '/withdraw/post-hooks', { data: payload });
}
// ========================================================================
// PORTFOLIO
// ========================================================================
/**
* Get total portfolio balance.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Total portfolio balance
*/
async getPortfolioTotalBalance() {
return this._request('GET', '/portfolio/total-balance');
}
/**
* Get portfolio token balances.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} List of token balances
*/
async getPortfolioTokens() {
return this._request('GET', '/portfolio/tokens');
}
// ========================================================================
// SESSION KEYS
// ========================================================================
/**
* Sign permitted session keys.
*
* @param {string} walletAddress - Smart account address
* @param {Object<string, string>} signatures - Dictionary mapping sessionKeyId to signature
* @param {Object<string, Object>} sessionSpecs - Dictionary mapping sessionKeyId to sessionSpec
* @param {string|null} ownerEOA - Optional EOA owner address (for ERC-7702)
* @param {Object<string, string>|null} backendWalletTransactionHashes - Optional transaction hashes
* @param {Object<string, string>|null} approvalTransactionHashes - Optional approval transaction hashes
* @param {Array<Object>|null} approvals - Optional list of approvals
* @returns {Promise<Object>} Sign permitted keys response
*/
async signPermittedKeys(
walletAddress,
signatures,
sessionSpecs,
ownerEOA = null,
backendWalletTransactionHashes = null,
approvalTransactionHashes = null,
approvals = null
) {
const payload = {
walletAddress,
signatures,
sessionSpecs
};
if (ownerEOA) payload.ownerEOA = ownerEOA;
if (backendWalletTransactionHashes) payload.backendWalletTransactionHashes = backendWalletTransactionHashes;
if (approvalTransactionHashes) payload.approvalTransactionHashes = approvalTransactionHashes;
if (approvals) payload.approvals = approvals;
return this._request('POST', '/sign-permitted-keys', { data: payload });
}
/**
* Get permitted keys available for signing.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Permitted keys information
*/
async getPermittedKeysForSigning() {
return this._request('GET', '/get-permitted-keys-for-signing');
}
/**
* Check remaining authorizations.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Remaining authorizations information
*/
async checkRemainingAuthorizations() {
return this._request('GET', '/check-remaining-authorizations');
}
/**
* Get session keys display information.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Session keys display information
*/
async getSessionKeysDisplay() {
return this._request('GET', '/session-keys-display');
}
/**
* Enable delegation.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {number} chainId - Chain ID
* @param {string} delegationData - Encoded enableDelegation transaction data (hex string with 0x prefix)
* @returns {Promise<Object>} Enable delegation response
*/
async enableDelegation(chainId, delegationData) {
const payload = {
chainId,
delegationData
};
return this._request('POST', '/enable-delegation', { data: payload });
}
/**
* Check bulk authorization status for session keys.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {Array<string>} sessionKeyIds - List of session key IDs
* @returns {Promise<Object>} Bulk authorization status
*/
async checkBulkAuthorizationStatus(sessionKeyIds) {
const url = `${this.baseUrl}/api/v1/session-key/check-bulk-authorization-status`;
const payload = {
sessionKeyIds
};
const response = await axios.post(url, payload, { headers: this._getHeaders() });
return response.data;
}
// ========================================================================
// AUTOMATION
// ========================================================================
/**
* Get automation job status.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Automation status
*/
async getAutomationStatus() {
return this._request('GET', '/automation/status');
}
/**
* Start automation job.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} graphId - Graph ID to run
* @param {string} prompt - Prompt/message for the graph
* @param {Object|null} paramValues - Optional parameter values
* @param {number} iterations - Number of iterations
* @param {string|null} branchId - Optional branch ID
* @returns {Promise<Object>} Start automation response
*/
async startAutomation(graphId, prompt, paramValues = null, iterations = 1, branchId = null) {
const payload = {
graphId,
prompt,
iterations
};
if (paramValues) payload.paramValues = paramValues;
if (branchId) payload.branchId = branchId;
return this._request('POST', '/automation/start', { data: payload });
}
/**
* Pause automation job.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Pause automation response
*/
async pauseAutomation() {
return this._request('POST', '/automation/pause');
}
/**
* Resume automation job.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Resume automation response
*/
async resumeAutomation() {
return this._request('POST', '/automation/resume');
}
/**
* Stop automation job.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Stop automation response
*/
async stopAutomation() {
return this._request('POST', '/automation/stop');
}
// ========================================================================
// CHATBOT
// ========================================================================
/**
* Get list of chatbots.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} List of chatbots
*/
async getChatbots() {
return this._request('GET', '/chatbots');
}
/**
* Get chatbot memories.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} graphId - Graph ID (chatbot graph ID)
* @param {number} page - Page number (default: 1)
* @param {number} limit - Items per page (default: 20)
* @returns {Promise<Object>} Chatbot memories
*/
async getChatbotMemories(graphId, page = 1, limit = 20) {
const params = {
graphId,
page,
limit
};
return this._request('GET', '/chatbot-memories', { params });
}
// ========================================================================
// GRAPH
// ========================================================================
/**
* Run a graph execution.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} graphId - Graph ID
* @param {string} prompt - User prompt/message
* @param {Object|null} paramValues - Optional parameter values
* @param {number} iterations - Number of iterations (default: 1)
* @param {string|null} branchId - Optional branch ID
* @param {boolean} includeContextReport - Include context report
* @param {Object|null} contextData - Optional context data
* @returns {Promise<Object>} Graph execution results
*/
async runGraph(
graphId,
prompt,
paramValues = null,
iterations = 1,
branchId = null,
includeContextReport = false,
contextData = null
) {
const payload = {
id: graphId,
prompt,
iterations,
includeContextReport
};
if (paramValues) payload.paramValues = paramValues;
if (branchId) payload.branchId = branchId;
if (contextData) payload.contextData = contextData;
return this._request('POST', '/run-graph', { data: payload });
}
// ========================================================================
// PROFILE
// ========================================================================
/**
* Get user profile.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} User profile
*/
async getProfile() {
return this._request('GET', '/profile');
}
/**
* Update user profile.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {Object} profileData - Profile data to update
* @returns {Promise<Object>} Updated profile
*/
async updateProfile(profileData) {
return this._request('PUT', '/profile', { data: profileData });
}
/**
* Upload profile avatar.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} filePath - Path to image file
* @returns {Promise<Object>} Upload response
*/
async uploadProfileAvatar(filePath) {
const url = `${this.baseUrl}${this.basePath}/profile/avatar`;
const formData = new FormData();
formData.append('file', fs.createReadStream(filePath));
const response = await axios.post(url, formData, {
headers: {
...this._getHeaders(),
'Content-Type': 'multipart/form-data'
}
});
return response.data;
}
/**
* Upload profile banner.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} filePath - Path to image file
* @returns {Promise<Object>} Upload response
*/
async uploadProfileBanner(filePath) {
const url = `${this.baseUrl}${this.basePath}/profile/banner`;
const formData = new FormData();
formData.append('file', fs.createReadStream(filePath));
const response = await axios.post(url, formData, {
headers: {
...this._getHeaders(),
'Content-Type': 'multipart/form-data'
}
});
return response.data;
}
// ========================================================================
// PAGE
// ========================================================================
/**
* Get page information.
*
* @returns {Promise<Object>} Page data including title, project info, authConfig, themeConfig
*/
async getPage() {
return this._request('GET', '/page');
}
/**
* Get list of pages.
*
* @param {string|null} projectId - Optional project ID filter
* @param {number} limit - Maximum number of results (default: 100)
* @param {number} offset - Offset for pagination (default: 0)
* @returns {Promise<Object>} List of pages
*/
async getPages(projectId = null, limit = 100, offset = 0) {
const params = { limit, offset };
if (projectId) params.projectId = projectId;
const url = `${this.baseUrl}/api/v1/pages`;
const response = await axios.get(url, {
params,
headers: this._getHeaders()
});
return response.data;
}
// ========================================================================
// TIER
// ========================================================================
/**
* Get tier information.
* Wallet address is extracted from JWT token, not from parameters.
*
* @returns {Promise<Object>} Tier information including user tier, eligible tiers, etc.
*/
async getTierInfo() {
return this._request('GET', '/tier');
}
// ========================================================================
// CUSTOM
// ========================================================================
/**
* Call custom GET API endpoint.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} apiId - Custom API ID
* @param {Object|null} params - Optional query parameters
* @returns {Promise<Object>} Custom API response
*/
async getCustomAPI(apiId, params = null) {
const queryParams = {};
if (params) Object.assign(queryParams, params);
return this._request('GET', `/custom/${apiId}`, { params: queryParams });
}
/**
* Call custom POST API endpoint.
* Wallet address is extracted from JWT token, not from parameters.
*
* @param {string} apiId - Custom API ID
* @param {Object} payload - Request payload (will be wrapped in a "params" object)
* @returns {Promise<Object>} Custom API response
*/
async postCustomAPI(apiId, payload) {
// Custom APIs require parameters to be nested in a "params" field
return this._request('POST', `/custom/${apiId}`, { data: { params: payload } });
}
}
// ============================================================================
// MAIN EXAMPLE
// ============================================================================
async function main() {
// Initialize wallet
if (!PRIVATE_KEY || PRIVATE_KEY === '0x' + '0'.repeat(64)) {
console.error('ERROR: Please set PRIVATE_KEY in the configuration section');
return;
}
const walletAddress = getWalletAddress(PRIVATE_KEY);
console.log(`Wallet Address: ${walletAddress}`);
// Initialize API client
const client = new SailAPIClient(BASE_URL, PROJECT_ID, PAGE_ID);
// Step 1: Authenticate
console.log('\n=== Step 1: Authentication ===');
const directAuthPayload = await client.requestDirectAuthPayload(walletAddress);
const signature = await signMessage(directAuthPayload.payload, PRIVATE_KEY);
console.log('Requested direct-auth payload from /authenticate');
console.log(`Signing payload: ${directAuthPayload.payload.substring(0, 80)}...`);
console.log(`Signature: ${signature.substring(0, 20)}...`);
try {
const authResponse = await client.completeDirectAuth(
walletAddress,
signature,
directAuthPayload.payload
);
console.log('Authentication successful!');
console.log(`Token: ${authResponse.token.substring(0, 20)}...`);
console.log(`User ID: ${authResponse.user_id}`);
console.log(`Is New User: ${authResponse.is_new_user}`);
} catch (error) {
console.error(`Authentication failed: ${error.message}`);
if (error.response) {
console.error(`Response: ${JSON.stringify(error.response.data, null, 2)}`);
}
return;
}
// Step 2: Get Balance
console.log('\n=== Step 2: Get Balance ===');
try {
const balance = await client.getBalance();
console.log(`Balance: ${balance.balance}`);
console.log(`Balance Formatted: ${balance.balanceFormatted}`);
} catch (error) {
console.error(`Get balance failed: ${error.message}`);
}
// Step 3: Get Deposit Info
console.log('\n=== Step 3: Get Metrics Balance ===');
try {
const metricsBalance = await client.getMetricsBalance();
console.log(`Metrics Message: ${metricsBalance.message}`);
console.log(`Metrics Result: ${JSON.stringify(metricsBalance.result)}`);
} catch (error) {
console.error(`Get metrics balance failed: ${error.message}`);
}
// Step 4: Get Deposit Info
console.log('\n=== Step 4: Get Deposit Info ===');
try {
const depositInfo = await client.getDepositInfo();
console.log(`Current Balance: ${depositInfo.currentBalance}`);
console.log(`Eligible Tier IDs: ${depositInfo.eligibleTierIds}`);
} catch (error) {
console.error(`Get deposit info failed: ${error.message}`);
}
// Step 5: Get Portfolio Total Balance
console.log('\n=== Step 5: Get Portfolio Total Balance ===');
try {
const portfolioBalance = await client.getPortfolioTotalBalance();
console.log(`Total Balance: ${portfolioBalance.balance}`);
console.log(`Balance Formatted: ${portfolioBalance.balanceFormatted}`);
} catch (error) {
console.error(`Get portfolio balance failed: ${error.message}`);
}
// Step 6: Get Page Info
console.log('\n=== Step 6: Get Page Info ===');
try {
const pageInfo = await client.getPage();
console.log(`Page Title: ${pageInfo.title}`);
console.log(`Project Title: ${pageInfo.projectTitle}`);
} catch (error) {
console.error(`Get page info failed: ${error.message}`);
}
// Step 7: Get Tier Info
console.log('\n=== Step 7: Get Tier Info ===');
try {
const tierInfo = await client.getTierInfo();
console.log(`User Tier: ${JSON.stringify(tierInfo.userTier)}`);
console.log(`User Balance: ${tierInfo.userBalance}`);
} catch (error) {
console.error(`Get tier info failed: ${error.message}`);
}
// Step 8: Get Chatbots
console.log('\n=== Step 8: Get Chatbots ===');
try {
const chatbots = await client.getChatbots();
console.log(`Found ${chatbots.chatbots.length} chatbot(s)`);
chatbots.chatbots.forEach(bot => {
console.log(` - ${bot.name} (ID: ${bot.id})`);
});
} catch (error) {
console.error(`Get chatbots failed: ${error.message}`);
}
// Step 9: Get Automation Status
console.log('\n=== Step 9: Get Automation Status ===');
try {
const automationStatus = await client.getAutomationStatus();
console.log(`Has Job: ${automationStatus.hasJob}`);
console.log(`Status: ${automationStatus.status}`);
} catch (error) {
console.error(`Get automation status failed: ${error.message}`);
}
console.log('\n=== Example Complete ===');
console.log('\nNote: Many endpoints require specific configurations on the SailBE server.');
console.log('Some endpoints may fail if the required tools, graphs, or configurations are not set up.');
console.log('Refer to the README files for more detailed usage examples.');
}
// Run the example
if (require.main === module) {
main().catch(console.error);
}