-
Notifications
You must be signed in to change notification settings - Fork 0
/
pastel_inference_client.js
1672 lines (1563 loc) · 56.7 KB
/
pastel_inference_client.js
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
// pastel_inference_client.js
require("dotenv").config();
const axios = require("axios");
const {
signMessageWithPastelID,
checkSupernodeList,
getCurrentPastelBlockHeight,
} = require("./rpc_functions");
const {
UserMessage,
CreditPackPurchaseRequest,
CreditPackPurchaseRequestRejection,
CreditPackPurchaseRequestPreliminaryPriceQuote,
CreditPackPurchaseRequestPreliminaryPriceQuoteResponse,
CreditPackPurchaseRequestResponseTermination,
CreditPackPurchaseRequestResponse,
CreditPackPurchaseRequestConfirmation,
CreditPackPurchaseRequestConfirmationResponse,
CreditPackRequestStatusCheck,
CreditPackPurchaseRequestStatus,
CreditPackStorageRetryRequest,
CreditPackStorageRetryRequestResponse,
InferenceAPIUsageRequest,
InferenceAPIUsageResponse,
InferenceAPIOutputResult,
InferenceConfirmation,
} = require("./sequelize_data_models");
const {
userMessageSchema,
creditPackPurchaseRequestSchema,
creditPackPurchaseRequestRejectionSchema,
creditPackPurchaseRequestPreliminaryPriceQuoteSchema,
creditPackPurchaseRequestPreliminaryPriceQuoteResponseSchema,
creditPackPurchaseRequestResponseTerminationSchema,
creditPackPurchaseRequestResponseSchema,
creditPackPurchaseRequestConfirmationSchema,
creditPackPurchaseRequestConfirmationResponseSchema,
creditPackRequestStatusCheckSchema,
creditPackPurchaseRequestStatusSchema,
creditPackStorageRetryRequestSchema,
creditPackStorageRetryRequestResponseSchema,
inferenceAPIUsageRequestSchema,
inferenceAPIUsageResponseSchema,
inferenceAPIOutputResultSchema,
inferenceConfirmationSchema,
} = require("./validation_schemas");
const { logger, safeStringify } = require("./logger");
const {
filterSupernodes,
getNClosestSupernodesToPastelIDURLs,
computeSHA3256HashOfSQLModelResponseFields,
prepareModelForEndpoint,
prepareModelForValidation,
removeSequelizeFields,
pythonCompatibleStringify,
estimatedMarketPriceOfInferenceCreditsInPSLTerms,
logActionWithPayload,
transformCreditPackPurchaseRequestResponse,
} = require("./utility_functions");
const globals = require("./globals");
const MESSAGING_TIMEOUT_IN_SECONDS = process.env.MESSAGING_TIMEOUT_IN_SECONDS;
function getIsoStringWithMicroseconds() {
// Get the current time
const now = new Date();
// Convert the date to an ISO string and replace 'Z' with '+00:00' to match Python's format
// Ensure to remove any unwanted spaces directly in this step if they were somehow introduced
const isoString = now.toISOString().replace("Z", "+00:00").replace(/\s/g, "");
// Return the correctly formatted ISO string without any spaces
return isoString;
}
class PastelInferenceClient {
constructor(pastelID, passphrase) {
this.pastelID = pastelID;
this.passphrase = passphrase;
}
async requestAndSignChallenge(supernodeURL) {
try {
const response = await axios.get(
`${supernodeURL}/request_challenge/${this.pastelID}`,
{
timeout: 12000,
}
);
const { challenge, challenge_id } = response.data;
const challenge_signature = await signMessageWithPastelID(
this.pastelID,
challenge,
this.passphrase
);
return {
challenge,
challenge_id,
challenge_signature,
};
} catch (error) {
logger.error(
`Error requesting and signing challenge: ${safeStringify(
error.message
)}`
);
throw error;
}
}
async sendUserMessage(supernodeURL, userMessage) {
try {
const { error } = userMessageSchema.validate(userMessage);
if (error) {
throw new Error(`Invalid user message: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
}
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const payload = userMessage.toJSON();
const response = await axios.post(
`${supernodeURL}/send_user_message`,
{
user_message: payload,
challenge,
challenge_id,
challenge_signature,
},
{
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
}
);
const result = response.data;
const { resultError, value: validatedResult } =
await userMessageSchema.validate(result);
if (error) {
throw new Error(`Invalid user message: ${resultError.message}`);
}
const userMessageInstance = await UserMessage.create(validatedResult);
return userMessageInstance;
} catch (error) {
logger.error(`Error sending user message: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async getUserMessages(supernodeURL) {
try {
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const params = {
pastelid: this.pastelID,
challenge,
challenge_id,
challenge_signature,
};
const response = await axios.get(`${supernodeURL}/get_user_messages`, {
params,
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
});
const result = response.data;
const validatedResults = await Promise.all(
result.map((messageData) => userMessageSchema.validate(messageData))
);
const userMessageInstances = await UserMessage.bulkCreate(
validatedResults
);
return userMessageInstances;
} catch (error) {
logger.error(`Error retrieving user messages: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async getModelMenu() {
const minimumNumberOfResponses = 5; // Minimum number of valid responses needed
const retryLimit = 1; // Number of retries per supernode
try {
const { validMasternodeListFullDF } = await checkSupernodeList();
const closestSupernodes = await getNClosestSupernodesToPastelIDURLs(
60,
this.pastelID,
validMasternodeListFullDF
);
let validResponses = [];
// Custom promise to collect a specified minimum number of valid responses
await new Promise((resolve, reject) => {
let completedRequests = 0;
closestSupernodes.forEach(({ url }) => {
this.retryPromise(() => this.getModelMenuFromSupernode(url), retryLimit)
.then(response => {
logger.info(`Successful model menu response received from supernode at ${url}`);
validResponses.push({ response, url });
// Resolve promise when minimum number of valid responses are collected
if (validResponses.length >= minimumNumberOfResponses) {
resolve();
}
})
.catch(error => {
logger.error(`Error querying supernode at ${url}: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
completedRequests++;
// Check if it's still possible to get the minimum number of valid responses
if (completedRequests > closestSupernodes.length - minimumNumberOfResponses + validResponses.length) {
reject(new Error("Insufficient valid responses received from supernodes"));
}
});
});
});
// Determine the largest/longest response
const largestResponse = validResponses.reduce((prev, current) => {
return JSON.stringify(current.response).length > JSON.stringify(prev.response).length ? current : prev;
}).response;
return largestResponse;
} catch (error) {
logger.error(`Error in getModelMenu: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
throw error;
}
}
async getModelMenuFromSupernode(supernodeURL) {
try {
const response = await axios.get(
`${supernodeURL}/get_inference_model_menu`,
{
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
}
);
return response.data;
} catch (error) {
// Silently catch the error and return undefined, null, or a default value.
return null; // You can return null, undefined, or an empty object depending on your use case.
}
}
async retryPromise(promiseFunc, limit, count = 0) {
try {
return await promiseFunc();
} catch (error) {
if (count < limit) {
return this.retryPromise(promiseFunc, limit, count + 1);
} else {
throw error;
}
}
}
async getValidCreditPackTicketsForPastelID(supernodeURL) {
const useVerbose = false;
try {
if (!this.pastelID) {
return [];
}
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const payload = {
pastelid: this.pastelID,
challenge,
challenge_id,
challenge_signature,
};
if (useVerbose) {
logActionWithPayload(
"retrieving",
"valid credit pack tickets for PastelID",
payload
);
}
const response = await axios.post(
`${supernodeURL}/get_valid_credit_pack_tickets_for_pastelid`,
payload,
{
timeout: 6000,
}
);
if (response.status !== 200) {
if (useVerbose) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return [];
}
const validCreditPackTickets = response.data;
if (useVerbose && validCreditPackTickets.length) {
logger.info(
`Received ${validCreditPackTickets.length} valid credit pack tickets for PastelID ${this.pastelID}`
);
}
// Process the new format of returned results
const processedTickets = validCreditPackTickets.map(ticket => ({
credit_pack_registration_txid: ticket.credit_pack_registration_txid,
credit_purchase_request_confirmation_pastel_block_height: ticket.credit_purchase_request_confirmation_pastel_block_height,
requesting_end_user_pastelid: ticket.requesting_end_user_pastelid,
ticket_input_data_fully_parsed_sha3_256_hash: ticket.ticket_input_data_fully_parsed_sha3_256_hash,
txid_of_credit_purchase_burn_transaction: ticket.txid_of_credit_purchase_burn_transaction,
credit_usage_tracking_psl_address: ticket.credit_usage_tracking_psl_address,
psl_cost_per_credit: ticket.psl_cost_per_credit,
requested_initial_credits_in_credit_pack: ticket.requested_initial_credits_in_credit_pack,
credit_pack_current_credit_balance: ticket.credit_pack_current_credit_balance,
balance_as_of_datetime: ticket.balance_as_of_datetime,
number_of_confirmation_transactions: ticket.number_of_confirmation_transactions
}));
return processedTickets;
} catch (error) {
if (useVerbose) {
logger.error(
`Error retrieving valid credit pack tickets for PastelID: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
}
if (useVerbose) {
throw error;
}
return [];
}
}
async checkCreditPackBalance(supernodeURL, txid) {
try {
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const payload = {
credit_pack_ticket_txid: txid,
challenge,
challenge_id,
challenge_signature,
};
logActionWithPayload("checking", "credit pack balance", payload);
const response = await axios.post(
`${supernodeURL}/check_credit_pack_balance`,
payload,
{
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
}
);
if (response.status !== 200) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const balanceInfo = response.data;
logger.info(
`Received credit pack balance info for txid ${txid}: ${JSON.stringify(
balanceInfo
)}`
);
return balanceInfo;
} catch (error) {
logger.error(
`Error checking credit pack balance for txid ${txid}: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
throw error;
}
}
async getCreditPackTicketFromTxid(supernodeURL, txid) {
try {
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const params = {
txid,
pastelid: this.pastelID,
challenge,
challenge_id,
challenge_signature,
};
logActionWithPayload(
"retrieving",
"credit pack ticket from txid",
params
);
const response = await axios.get(
`${supernodeURL}/get_credit_pack_ticket_from_txid`,
{
params,
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
}
);
if (response.status !== 200) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const {
credit_pack_purchase_request_response,
credit_pack_purchase_request_confirmation,
} = response.data;
logActionWithPayload("received", "credit pack ticket from Supernode", {
credit_pack_purchase_request_response,
credit_pack_purchase_request_confirmation,
});
const { errorRequestResponse, value: validatedRequestResponse } =
creditPackPurchaseRequestResponseSchema.validate(
credit_pack_purchase_request_response
);
if (errorRequestResponse) {
throw new Error(
`Invalid credit pack request response: ${errorRequestResponse.message}`
);
}
const { errorRequestConfirmation, value: validatedRequestConfirmation } =
creditPackPurchaseRequestConfirmationSchema.validate(
credit_pack_purchase_request_confirmation
);
if (errorRequestConfirmation) {
throw new Error(
`Invalid credit pack request confirmation: ${errorRequestConfirmation.message}`
);
}
return {
creditPackPurchaseRequestResponse:
new CreditPackPurchaseRequestResponse(validatedRequestResponse),
creditPackPurchaseRequestConfirmation:
new CreditPackPurchaseRequestConfirmation(
validatedRequestConfirmation
),
};
} catch (error) {
logger.error(
`Error retrieving credit pack ticket from txid: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
throw error;
}
}
async creditPackTicketInitialPurchaseRequest(
supernodeURL,
creditPackRequest
) {
try {
// Validate the credit pack request using Joi
const { error, value: validatedCreditPackRequest } =
creditPackPurchaseRequestSchema.validate(creditPackRequest.toJSON());
if (error) {
throw new Error(`Invalid credit pack request: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`);
}
// Create the credit pack purchase request in the database
const _creditPackPurchaseRequestInstance =
await CreditPackPurchaseRequest.create(validatedCreditPackRequest);
logActionWithPayload(
"requesting",
"a new Pastel credit pack ticket",
validatedCreditPackRequest
);
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
let preparedCreditPackRequest = await prepareModelForEndpoint(
creditPackRequest
);
const response = await axios.post(
`${supernodeURL}/credit_purchase_initial_request`,
{
challenge,
challenge_id,
challenge_signature,
credit_pack_request: preparedCreditPackRequest,
},
{
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
}
);
const result = response.data;
if (result.rejection_reason_string) {
logger.error(
`Credit pack purchase request rejected: ${result.rejection_reason_string}`
);
let rejectionResponse = await prepareModelForValidation(result);
const { rejectionError, value: validatedRejection } =
await creditPackPurchaseRequestRejectionSchema.validateAsync(
rejectionResponse
);
if (rejectionError) {
throw new Error(
`Invalid credit pack purchase request rejection: ${rejectionError.message}`
);
}
const creditPackPurchaseRequestRejectionInstance =
await CreditPackPurchaseRequestRejection.create(validatedRejection);
return creditPackPurchaseRequestRejectionInstance;
} else {
logActionWithPayload(
"receiving",
"response to credit pack purchase request",
result
);
let preparedResult = await prepareModelForValidation(result);
const { priceQuoteError, value: validatedPriceQuote } =
await creditPackPurchaseRequestPreliminaryPriceQuoteSchema.validate(
preparedResult
);
if (priceQuoteError) {
throw new Error(
"Invalid credit pack request: " + priceQuoteError.message
);
}
const creditPackPurchaseRequestPreliminaryPriceQuoteInstance =
await CreditPackPurchaseRequestPreliminaryPriceQuote.create(
validatedPriceQuote
);
return creditPackPurchaseRequestPreliminaryPriceQuoteInstance;
}
} catch (error) {
logger.error(
`Error initiating credit pack ticket purchase: ${safeStringify(
error.message
)}`
);
throw error;
}
}
async calculatePriceDifferencePercentage(quotedPrice, estimatedPrice) {
if (estimatedPrice === 0) {
throw new Error("Estimated price cannot be zero.");
}
const differencePercentage =
Math.abs(quotedPrice - estimatedPrice) / estimatedPrice;
return differencePercentage;
}
async confirmPreliminaryPriceQuote(
preliminaryPriceQuote,
maximumTotalCreditPackPriceInPSL,
maximumPerCreditPriceInPSL
) {
if (!maximumTotalCreditPackPriceInPSL && !maximumPerCreditPriceInPSL) {
maximumPerCreditPriceInPSL =
process.env.MAXIMUM_PER_CREDIT_PRICE_IN_PSL_FOR_CLIENT;
}
const {
preliminary_quoted_price_per_credit_in_psl: quotedPricePerCredit,
preliminary_total_cost_of_credit_pack_in_psl: quotedTotalPrice,
credit_pack_purchase_request_fields_json_b64: requestFieldsB64,
} = preliminaryPriceQuote;
let requestFields = JSON.parse(atob(requestFieldsB64)); // Decode base64 string
const { requested_initial_credits_in_credit_pack: requestedCredits } =
requestFields;
if (!maximumTotalCreditPackPriceInPSL) {
maximumTotalCreditPackPriceInPSL =
maximumPerCreditPriceInPSL * requestedCredits;
} else if (!maximumPerCreditPriceInPSL) {
maximumPerCreditPriceInPSL =
maximumTotalCreditPackPriceInPSL / requestedCredits;
}
const estimatedPricePerCredit =
await estimatedMarketPriceOfInferenceCreditsInPSLTerms();
const priceDifferencePercentage =
await this.calculatePriceDifferencePercentage(
quotedPricePerCredit,
estimatedPricePerCredit
);
const numberFormat = new Intl.NumberFormat("en-US");
const percentageFormat = (value) => value.toFixed(2);
if (
quotedPricePerCredit <= maximumPerCreditPriceInPSL &&
quotedTotalPrice <= maximumTotalCreditPackPriceInPSL &&
priceDifferencePercentage <= parseFloat(process.env.MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING)
) {
logger.info(
`Preliminary price quote is within the acceptable range: ${numberFormat.format(
quotedPricePerCredit
)} PSL per credit, ${numberFormat.format(
quotedTotalPrice
)} PSL total, which is within the maximum of ${numberFormat.format(
maximumPerCreditPriceInPSL
)} PSL per credit and ${numberFormat.format(
maximumTotalCreditPackPriceInPSL
)} PSL total. The price difference from the estimated fair market price is ${percentageFormat(
priceDifferencePercentage * 100
)}%, which is within the allowed maximum of ${percentageFormat(
parseFloat(process.env.MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING) *
100
)}%. Please be patient while the new credit pack request is initialized.`
);
return true;
} else {
logger.warn(
`Preliminary price quote exceeds the maximum acceptable price or the price difference from the estimated fair price is too high! Quoted price: ${numberFormat.format(
quotedPricePerCredit
)} PSL per credit, ${numberFormat.format(
quotedTotalPrice
)} PSL total, maximum price: ${numberFormat.format(
maximumPerCreditPriceInPSL
)} PSL per credit, ${numberFormat.format(
maximumTotalCreditPackPriceInPSL
)} PSL total. The price difference from the estimated fair market price is ${percentageFormat(
priceDifferencePercentage * 100
)}%, which exceeds the allowed maximum of ${percentageFormat(
parseFloat(process.env.MAXIMUM_LOCAL_CREDIT_PRICE_DIFFERENCE_TO_ACCEPT_CREDIT_PRICING) *
100
)}%.`
);
return false;
}
}
async internalEstimateOfCreditPackTicketCostInPSL(
desiredNumberOfCredits,
priceCushionPercentage
) {
const estimatedPricePerCredit =
await estimatedMarketPriceOfInferenceCreditsInPSLTerms();
const estimatedTotalCostOfTicket =
Math.round(
desiredNumberOfCredits *
estimatedPricePerCredit *
(1 + priceCushionPercentage) *
100
) / 100;
return estimatedTotalCostOfTicket;
}
async creditPackTicketPreliminaryPriceQuoteResponse(
supernodeURL,
creditPackRequest,
preliminaryPriceQuote,
maximumTotalCreditPackPriceInPSL,
maximumPerCreditPriceInPSL
) {
try {
if (preliminaryPriceQuote instanceof CreditPackPurchaseRequestRejection) {
logger.error(
`Credit pack purchase request rejected: ${preliminaryPriceQuote.rejection_reason_string}`
);
return preliminaryPriceQuote;
}
const agreeWithPriceQuote = await this.confirmPreliminaryPriceQuote(
preliminaryPriceQuote,
maximumTotalCreditPackPriceInPSL,
maximumPerCreditPriceInPSL
);
logger.info(`Agree with price quote: ${agreeWithPriceQuote}; responding to preliminary price quote to Supernode at ${supernodeURL}...`);
const priceQuoteResponse =
CreditPackPurchaseRequestPreliminaryPriceQuoteResponse.build({
sha3_256_hash_of_credit_pack_purchase_request_fields:
creditPackRequest.sha3_256_hash_of_credit_pack_purchase_request_fields,
sha3_256_hash_of_credit_pack_purchase_request_preliminary_price_quote_fields:
preliminaryPriceQuote.sha3_256_hash_of_credit_pack_purchase_request_preliminary_price_quote_fields,
credit_pack_purchase_request_fields_json_b64:
preliminaryPriceQuote.credit_pack_purchase_request_fields_json_b64,
agree_with_preliminary_price_quote: agreeWithPriceQuote,
credit_usage_tracking_psl_address:
preliminaryPriceQuote.credit_usage_tracking_psl_address,
preliminary_quoted_price_per_credit_in_psl: parseFloat(
preliminaryPriceQuote.preliminary_quoted_price_per_credit_in_psl
),
preliminary_price_quote_response_timestamp_utc_iso_string:
getIsoStringWithMicroseconds(),
preliminary_price_quote_response_pastel_block_height: parseInt(
await getCurrentPastelBlockHeight(),
10
),
preliminary_price_quote_response_message_version_string: "1.0",
requesting_end_user_pastelid:
creditPackRequest.requesting_end_user_pastelid,
sha3_256_hash_of_credit_pack_purchase_request_preliminary_price_quote_response_fields:
"",
requesting_end_user_pastelid_signature_on_preliminary_price_quote_response_hash:
"",
});
// Compute hashes and signatures
priceQuoteResponse.sha3_256_hash_of_credit_pack_purchase_request_preliminary_price_quote_response_fields =
await computeSHA3256HashOfSQLModelResponseFields(priceQuoteResponse);
priceQuoteResponse.requesting_end_user_pastelid_signature_on_preliminary_price_quote_response_hash =
await signMessageWithPastelID(
creditPackRequest.requesting_end_user_pastelid,
priceQuoteResponse.sha3_256_hash_of_credit_pack_purchase_request_preliminary_price_quote_response_fields,
this.passphrase
);
// Validate the price quote response
const {
error: priceQuoteValidationError,
value: validatedPriceQuoteResponse,
} =
await creditPackPurchaseRequestPreliminaryPriceQuoteResponseSchema.validate(
priceQuoteResponse.toJSON()
);
if (priceQuoteValidationError) {
throw new Error(
`Invalid price quote response: ${priceQuoteValidationError.message}`
);
}
// Prepare model for endpoint before sending
let preparedPriceQuoteResponse = await prepareModelForEndpoint(
priceQuoteResponse
);
delete preparedPriceQuoteResponse["id"];
preparedPriceQuoteResponse["agree_with_preliminary_price_quote"] =
preparedPriceQuoteResponse["agree_with_preliminary_price_quote"]
? 1
: 0;
// Prepare and send the payload to the supernode
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const completePriceQuoteResponse = {
challenge,
challenge_id,
challenge_signature,
preliminary_price_quote_response: preparedPriceQuoteResponse,
};
const response = await axios.post(
`${supernodeURL}/credit_purchase_preliminary_price_quote_response`,
completePriceQuoteResponse,
{ timeout: 3 * MESSAGING_TIMEOUT_IN_SECONDS * 1000 }
);
const result = response.data;
if (result.termination_reason_string) {
logger.error(
`Credit pack purchase request response terminated: ${result.termination_reason_string}`
);
const terminationResponse = await prepareModelForValidation(result);
const { error: terminationError, value: validatedTermination } =
await creditPackPurchaseRequestResponseTerminationSchema.validateAsync(
terminationResponse
);
if (terminationError) {
throw new Error(
`Invalid credit pack purchase request response termination: ${terminationError.message}`
);
}
const terminationInstance =
await CreditPackPurchaseRequestResponseTermination.create(
validatedTermination
);
return terminationInstance;
} else {
let transformedResult = transformCreditPackPurchaseRequestResponse(
await prepareModelForValidation(result)
);
logActionWithPayload(
"receiving",
"response to credit pack purchase request",
transformedResult
);
const { error: resultError, value: validatedResponse } =
await creditPackPurchaseRequestResponseSchema.validate(
transformedResult
);
if (resultError) {
throw new Error(
`Invalid credit pack purchase request response: ${resultError.message}`
);
}
const responseInstance = await CreditPackPurchaseRequestResponse.create(
validatedResponse
);
return responseInstance;
}
} catch (error) {
logger.error(
`Error responding to preliminary price quote: ${safeStringify(
error.message
)}`
);
throw error;
}
}
async confirmCreditPurchaseRequest(
supernodeURL,
creditPackPurchaseRequestConfirmation
) {
try {
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
const payload = await prepareModelForEndpoint(
creditPackPurchaseRequestConfirmation
);
logActionWithPayload(
"confirming",
"credit pack purchase request",
payload
);
const response = await axios.post(
`${supernodeURL}/confirm_credit_purchase_request`,
{
confirmation: payload,
challenge,
challenge_id,
challenge_signature,
},
{
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 30 * 1000, // Need to be patient with the timeout here since it requires the transaction to be mined/confirmed
}
);
const result = response.data;
logActionWithPayload(
"receiving",
"response to credit pack purchase confirmation",
result
);
const { error: validationError, value: validatedResult } =
await creditPackPurchaseRequestConfirmationResponseSchema.validate(
result
);
if (validationError) {
throw new Error(
`Invalid credit pack purchase request confirmation response: ${validationError.message}`
);
}
const creditPackPurchaseRequestConfirmationResponseInstance =
await CreditPackPurchaseRequestConfirmationResponse.create(result);
return creditPackPurchaseRequestConfirmationResponseInstance;
} catch (error) {
logger.error(
`Error confirming credit pack purchase request: ${safeStringify(
error.message
)}`
);
throw error;
}
}
async checkStatusOfCreditPurchaseRequest(
supernodeURL,
creditPackPurchaseRequestHash
) {
try {
// Request challenge from the server
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
// Build and validate the status check model
const statusCheck = CreditPackRequestStatusCheck.build({
sha3_256_hash_of_credit_pack_purchase_request_fields:
creditPackPurchaseRequestHash,
requesting_end_user_pastelid: this.pastelID,
requesting_end_user_pastelid_signature_on_sha3_256_hash_of_credit_pack_purchase_request_fields:
await signMessageWithPastelID(
this.pastelID,
creditPackPurchaseRequestHash,
this.passphrase
),
});
const { error: validationError, value: validatedStatusCheck } =
await creditPackRequestStatusCheckSchema.validate(statusCheck.toJSON());
if (validationError) {
logger.error(
`Invalid credit pack request status check: ${validationError.message}`
);
throw new Error(
`Invalid credit pack request status check: ${validationError.message}`
);
}
delete validatedStatusCheck["id"];
logActionWithPayload(
"checking",
"status of credit pack purchase request",
validatedStatusCheck
);
// Send the request to the server
const response = await axios.post(
`${supernodeURL}/check_status_of_credit_purchase_request`,
{
credit_pack_request_status_check: validatedStatusCheck,
challenge,
challenge_id,
challenge_signature,
},
{
timeout: MESSAGING_TIMEOUT_IN_SECONDS * 1000,
}
);
// Check response status and handle any errors
if (response.status !== 200) {
throw new Error(
`HTTP error ${response.status}: ${response.statusText}`
);
}
logActionWithPayload(
"receiving",
"credit pack purchase request response from Supernode",
response.data
);
// Validate the received result
let transformedResult = await prepareModelForValidation(response.data);
delete transformedResult["id"];
const { error: resultError, value: validatedResult } =
await creditPackPurchaseRequestStatusSchema.validate(transformedResult);
if (resultError) {
throw new Error(
`Invalid credit pack purchase request status: ${resultError.message}`
);
}
// Create and return the status instance from the validated result
const statusInstance = await CreditPackPurchaseRequestStatus.create(
validatedResult
);
return statusInstance;
} catch (error) {
logger.error(
`Error checking status of credit purchase request: ${safeStringify(
error.message
)}`
);
throw error; // Rethrow to handle error upstream
}
}
async creditPackPurchaseCompletionAnnouncement(
supernodeURL,
creditPackPurchaseRequestConfirmation
) {
try {
// Validate the incoming data
const { error, value: validatedConfirmation } =
await creditPackPurchaseRequestConfirmationSchema.validate(
creditPackPurchaseRequestConfirmation.toJSON()
);
if (error) {
logger.error(
`Invalid credit pack purchase request confirmation: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
return; // Return early instead of throwing an error
}
// Request challenge from the server
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);
// Prepare the model for the endpoint
let payload = validatedConfirmation;
delete payload["id"]; // Removing the 'id' key as done in the Python method
// Send the request to the server with a shortened timeout
const response = await axios.post(
`${supernodeURL}/credit_pack_purchase_completion_announcement`,
{
confirmation: payload,
challenge,
challenge_id,
challenge_signature,
},
{
timeout: 2 * 1000, // Shortened timeout of 2 seconds
}
);
// Check response status and log any errors
if (response.status !== 200) {
logger.error(`HTTP error ${response.status}: ${response.statusText}`);
} else {
logger.info(
`Credit pack purchase completion announcement sent successfully to ${supernodeURL}`
);
}
} catch (error) {
// Log the error without rethrowing to prevent upstream disruption
if (error.response) {
logger.error(
`HTTP error sending credit pack purchase completion announcement to ${supernodeURL}: ${error.response.status} ${error.response.statusText}`
);
} else if (error.code === "ECONNABORTED") {
logger.error(
`Timeout error sending credit pack purchase completion announcement to ${supernodeURL}: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
} else {
logger.error(
`Error sending credit pack purchase completion announcement to ${supernodeURL}: ${error.message || error
}`
);
}
}
}
async creditPackStorageRetryRequest(
supernodeURL,
creditPackStorageRetryRequest
) {
try {
const { error, value: validatedRequest } =
await creditPackStorageRetryRequestSchema.validate(
creditPackStorageRetryRequest.toJSON()
);
if (error) {
throw new Error(
`Invalid credit pack storage retry request: ${error.message.slice(0, globals.MAX_CHARACTERS_TO_DISPLAY_IN_ERROR_MESSAGE)}`
);
}
const requestInstance = await CreditPackStorageRetryRequest.create(
validatedRequest
);
const { challenge, challenge_id, challenge_signature } =
await this.requestAndSignChallenge(supernodeURL);