@provablehq/sdk 0.9.2 → 0.9.4-offline-rc

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/mainnet/account.d.ts +36 -1
  2. package/dist/mainnet/browser.d.ts +5 -4
  3. package/dist/mainnet/browser.js +4415 -570
  4. package/dist/mainnet/browser.js.map +1 -1
  5. package/dist/mainnet/function-key-provider.d.ts +18 -0
  6. package/dist/mainnet/models/authorization.d.ts +6 -0
  7. package/dist/mainnet/models/inputID.d.ts +4 -0
  8. package/dist/mainnet/models/provingRequest.d.ts +6 -0
  9. package/dist/mainnet/models/provingResponse.d.ts +5 -0
  10. package/dist/mainnet/models/request.d.ts +14 -0
  11. package/dist/mainnet/network-client.d.ts +0 -14
  12. package/dist/mainnet/node-polyfill.js.map +1 -1
  13. package/dist/mainnet/node.js +2 -4
  14. package/dist/mainnet/node.js.map +1 -1
  15. package/dist/mainnet/offline-key-provider.d.ts +14 -0
  16. package/dist/mainnet/program-manager.d.ts +209 -6
  17. package/dist/mainnet/wasm.d.ts +1 -1
  18. package/dist/testnet/account.d.ts +36 -1
  19. package/dist/testnet/browser.d.ts +5 -4
  20. package/dist/testnet/browser.js +4415 -570
  21. package/dist/testnet/browser.js.map +1 -1
  22. package/dist/testnet/function-key-provider.d.ts +18 -0
  23. package/dist/testnet/models/authorization.d.ts +6 -0
  24. package/dist/testnet/models/inputID.d.ts +4 -0
  25. package/dist/testnet/models/provingRequest.d.ts +6 -0
  26. package/dist/testnet/models/provingResponse.d.ts +5 -0
  27. package/dist/testnet/models/request.d.ts +14 -0
  28. package/dist/testnet/network-client.d.ts +0 -14
  29. package/dist/testnet/node-polyfill.js.map +1 -1
  30. package/dist/testnet/node.js +2 -4
  31. package/dist/testnet/node.js.map +1 -1
  32. package/dist/testnet/offline-key-provider.d.ts +14 -0
  33. package/dist/testnet/program-manager.d.ts +209 -6
  34. package/dist/testnet/wasm.d.ts +1 -1
  35. package/package.json +2 -2
  36. package/dist/mainnet/managed-worker.d.ts +0 -3
  37. package/dist/mainnet/program-manager-B-18sj9m.js +0 -3458
  38. package/dist/mainnet/program-manager-B-18sj9m.js.map +0 -1
  39. package/dist/mainnet/worker.d.ts +0 -9
  40. package/dist/mainnet/worker.js +0 -78
  41. package/dist/mainnet/worker.js.map +0 -1
  42. package/dist/testnet/managed-worker.d.ts +0 -3
  43. package/dist/testnet/program-manager-BR5taTR7.js +0 -3458
  44. package/dist/testnet/program-manager-BR5taTR7.js.map +0 -1
  45. package/dist/testnet/worker.d.ts +0 -9
  46. package/dist/testnet/worker.js +0 -78
  47. package/dist/testnet/worker.js.map +0 -1
@@ -1,3458 +0,0 @@
1
- import { PrivateKey, RecordCiphertext, Program, Plaintext, Address, Transaction, Metadata, VerifyingKey, ProvingKey, ProgramManager as ProgramManager$1, RecordPlaintext, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
2
-
3
- function detectBrowser() {
4
- const userAgent = navigator.userAgent;
5
- if (/chrome|crios|crmo/i.test(userAgent) && !/edge|edg|opr/i.test(userAgent)) {
6
- return "chrome";
7
- }
8
- else if (/firefox|fxios/i.test(userAgent)) {
9
- return "firefox";
10
- }
11
- else if (/safari/i.test(userAgent) && !/chrome|crios|crmo|android/i.test(userAgent)) {
12
- return "safari";
13
- }
14
- else if (/edg/i.test(userAgent)) {
15
- return "edge";
16
- }
17
- else if (/opr\//i.test(userAgent)) {
18
- return "opera";
19
- }
20
- else {
21
- return "browser";
22
- }
23
- }
24
- function environment() {
25
- if ((typeof process !== 'undefined') &&
26
- (process.release?.name === 'node')) {
27
- return 'node';
28
- }
29
- else if (typeof window !== 'undefined') {
30
- return detectBrowser();
31
- }
32
- else {
33
- return 'unknown';
34
- }
35
- }
36
- function logAndThrow(message) {
37
- console.error(message);
38
- throw new Error(message);
39
- }
40
- function parseJSON(json) {
41
- function revive(key, value, context) {
42
- if (Number.isInteger(value)) {
43
- return BigInt(context.source);
44
- }
45
- else {
46
- return value;
47
- }
48
- }
49
- return JSON.parse(json, revive);
50
- }
51
- async function get(url, options) {
52
- const response = await fetch(url, options);
53
- if (!response.ok) {
54
- throw new Error(response.status + " could not get URL " + url);
55
- }
56
- return response;
57
- }
58
- async function post(url, options) {
59
- options.method = "POST";
60
- const response = await fetch(url, options);
61
- if (!response.ok) {
62
- throw new Error(response.status + " could not post URL " + url);
63
- }
64
- return response;
65
- }
66
- async function retryWithBackoff(fn, { maxAttempts = 5, baseDelay = 100, jitter, retryOnStatus = [], shouldRetry, } = {}) {
67
- for (let attempt = 1; attempt <= maxAttempts; attempt++) {
68
- try {
69
- return await fn();
70
- }
71
- catch (err) {
72
- const isLast = attempt === maxAttempts;
73
- const error = err;
74
- let retryable = false;
75
- if (typeof error.status === "number") {
76
- if (error.status >= 500) {
77
- retryable = true;
78
- }
79
- else if (error.status >= 400 && shouldRetry) {
80
- retryable = shouldRetry(error);
81
- }
82
- }
83
- else if (shouldRetry) {
84
- retryable = shouldRetry(error);
85
- }
86
- if (!retryable || isLast)
87
- throw error;
88
- const jitterAmount = jitter ?? baseDelay;
89
- const actualJitter = Math.floor(Math.random() * jitterAmount);
90
- const delay = baseDelay * 2 ** (attempt - 1) + actualJitter;
91
- console.warn(`Retry ${attempt}/${maxAttempts} failed. Retrying in ${delay}ms...`);
92
- await new Promise((res) => setTimeout(res, delay));
93
- }
94
- }
95
- throw new Error("retryWithBackoff: unreachable");
96
- }
97
-
98
- /**
99
- * Client library that encapsulates REST calls to publicly exposed endpoints of Aleo nodes. The methods provided in this
100
- * allow users to query public information from the Aleo blockchain and submit transactions to the network.
101
- *
102
- * @param {string} host
103
- * @example
104
- * // Connection to a local node.
105
- * const localNetworkClient = new AleoNetworkClient("http://0.0.0.0:3030", undefined, account);
106
- *
107
- * // Connection to a public beacon node
108
- * const account = Account.fromCiphertext(process.env.ciphertext, process.env.password);
109
- * const publicNetworkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined, account);
110
- */
111
- class AleoNetworkClient {
112
- host;
113
- headers;
114
- account;
115
- ctx;
116
- network;
117
- constructor(host, options) {
118
- this.host = host + "/mainnet";
119
- this.network = "mainnet";
120
- this.ctx = {};
121
- if (options && options.headers) {
122
- this.headers = options.headers;
123
- }
124
- else {
125
- this.headers = {
126
- // This is replaced by the actual version by a Rollup plugin
127
- "X-Aleo-SDK-Version": "0.9.2",
128
- "X-Aleo-environment": environment(),
129
- };
130
- }
131
- }
132
- /**
133
- * Set an account to use in networkClient calls
134
- *
135
- * @param {Account} account Set an account to use for record scanning functions.
136
- * @example
137
- * import { Account, AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
138
- *
139
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1");
140
- * const account = new Account();
141
- * networkClient.setAccount(account);
142
- */
143
- setAccount(account) {
144
- this.account = account;
145
- }
146
- /**
147
- * Return the Aleo account used in the networkClient
148
- *
149
- * @example
150
- * const account = networkClient.getAccount();
151
- */
152
- getAccount() {
153
- return this.account;
154
- }
155
- /**
156
- * Set a new host for the networkClient
157
- *
158
- * @param {string} host The address of a node hosting the Aleo API
159
- * @param host
160
- *
161
- * @example
162
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
163
- *
164
- * // Create a networkClient that connects to a local node.
165
- * const networkClient = new AleoNetworkClient("http://0.0.0.0:3030", undefined);
166
- *
167
- * // Set the host to a public node.
168
- * networkClient.setHost("http://api.explorer.provable.com/v1");
169
- */
170
- setHost(host) {
171
- this.host = host + "/mainnet";
172
- }
173
- /**
174
- * Set a header in the `AleoNetworkClient`s header map
175
- *
176
- * @param {string} headerName The name of the header to set
177
- * @param {string} value The header value
178
- *
179
- * @example
180
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
181
- *
182
- * // Create a networkClient
183
- * const networkClient = new AleoNetworkClient();
184
- *
185
- * // Set the value of the `Accept-Language` header to `en-US`
186
- * networkClient.setHeader('Accept-Language', 'en-US');
187
- */
188
- setHeader(headerName, value) {
189
- this.headers[headerName] = value;
190
- }
191
- /**
192
- * Remove a header from the `AleoNetworkClient`s header map
193
- *
194
- * @param {string} headerName The name of the header to be removed
195
- *
196
- * @example
197
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
198
- *
199
- * // Create a networkClient
200
- * const networkClient = new AleoNetworkClient();
201
- *
202
- * // Remove the default `X-Aleo-SDK-Version` header
203
- * networkClient.removeHeader('X-Aleo-SDK-Version');
204
- */
205
- removeHeader(headerName) {
206
- delete this.headers[headerName];
207
- }
208
- /**
209
- * Fetches data from the Aleo network and returns it as a JSON object.
210
- *
211
- * @param url The URL to fetch data from.
212
- */
213
- async fetchData(url = "/") {
214
- try {
215
- const raw = await this.fetchRaw(url);
216
- return parseJSON(raw);
217
- }
218
- catch (error) {
219
- throw new Error(`Error fetching data: ${error}`);
220
- }
221
- }
222
- /**
223
- * Fetches data from the Aleo network and returns it as an unparsed string.
224
- *
225
- * This method should be used when it is desired to reconstitute data returned
226
- * from the network into a WASM object.
227
- *
228
- * @param url
229
- */
230
- async fetchRaw(url = "/") {
231
- try {
232
- const ctx = { ...this.ctx };
233
- return await retryWithBackoff(async () => {
234
- const response = await get(this.host + url, {
235
- headers: {
236
- ...this.headers,
237
- ...ctx,
238
- },
239
- });
240
- return await response.text();
241
- });
242
- }
243
- catch (error) {
244
- throw new Error(`Error fetching data: ${error}`);
245
- }
246
- }
247
- /**
248
- * Wrapper around the POST helper to allow mocking in tests. Not meant for use in production.
249
- *
250
- * @param url The URL to POST to.
251
- * @param options The RequestInit options for the POST request.
252
- * @returns The Response object from the POST request.
253
- */
254
- async _sendPost(url, options) {
255
- return post(url, options);
256
- }
257
- /**
258
- * Attempt to find records in the Aleo blockchain.
259
- *
260
- * @param {number} startHeight - The height at which to start searching for unspent records
261
- * @param {number} endHeight - The height at which to stop searching for unspent records
262
- * @param {boolean} unspent - Whether to search for unspent records only
263
- * @param {string[]} programs - The program(s) to search for unspent records in
264
- * @param {number[]} amounts - The amounts (in microcredits) to search for (eg. [100, 200, 3000])
265
- * @param {number} maxMicrocredits - The maximum number of microcredits to search for
266
- * @param {string[]} nonces - The nonces of already found records to exclude from the search
267
- * @param {string | PrivateKey} privateKey - An optional private key to use to find unspent records.
268
- * @returns {Promise<Array<RecordPlaintext>>} An array of records belonging to the account configured in the network client.
269
- *
270
- * @example
271
- * import { Account, AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
272
- *
273
- * // Import an account from a ciphertext and password.
274
- * const account = Account.fromCiphertext(process.env.ciphertext, process.env.password);
275
- *
276
- * // Create a network client.
277
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
278
- * networkClient.setAccount(account);
279
- *
280
- * // Find specific amounts
281
- * const startHeight = 500000;
282
- * const amounts = [600000, 1000000];
283
- * const records = networkClient.findRecords(startHeight, undefined, true, ["credits.aleo"] amounts);
284
- *
285
- * // Find specific amounts with a maximum number of cumulative microcredits
286
- * const maxMicrocredits = 100000;
287
- * const records = networkClient.findRecords(startHeight, undefined, true, ["credits.aleo"] undefined, maxMicrocredits);
288
- */
289
- async findRecords(startHeight, endHeight, unspent = false, programs, amounts, maxMicrocredits, nonces, privateKey) {
290
- nonces = nonces || [];
291
- // Ensure start height is not negative
292
- if (startHeight < 0) {
293
- throw new Error("Start height must be greater than or equal to 0");
294
- }
295
- // Initialize search parameters
296
- const records = new Array();
297
- let start;
298
- let end;
299
- let resolvedPrivateKey;
300
- let failures = 0;
301
- let totalRecordValue = BigInt(0);
302
- let latestHeight;
303
- // Ensure a private key is present to find owned records
304
- if (typeof privateKey === "undefined") {
305
- if (typeof this.account === "undefined") {
306
- throw new Error("Private key must be specified in an argument to findOwnedRecords or set in the AleoNetworkClient");
307
- }
308
- else {
309
- resolvedPrivateKey = this.account._privateKey;
310
- }
311
- }
312
- else {
313
- try {
314
- resolvedPrivateKey =
315
- privateKey instanceof PrivateKey
316
- ? privateKey
317
- : PrivateKey.from_string(privateKey);
318
- }
319
- catch (error) {
320
- throw new Error("Error parsing private key provided.");
321
- }
322
- }
323
- const viewKey = resolvedPrivateKey.to_view_key();
324
- // Get the latest height to ensure the range being searched is valid
325
- try {
326
- const blockHeight = await this.getLatestHeight();
327
- if (typeof blockHeight === "number") {
328
- latestHeight = blockHeight;
329
- }
330
- else {
331
- throw new Error(`Error fetching latest block height: Expected type 'number' got '${typeof blockHeight}'`);
332
- }
333
- }
334
- catch (error) {
335
- throw new Error(`Error fetching latest block height: ${error}`);
336
- }
337
- // If no end height is specified or is greater than the latest height, set the end height to the latest height
338
- if (typeof endHeight === "number" && endHeight <= latestHeight) {
339
- end = endHeight;
340
- }
341
- else {
342
- end = latestHeight;
343
- }
344
- // If the starting is greater than the ending height, return an error
345
- if (startHeight > end) {
346
- throw new Error("Start height must be less than or equal to end height.");
347
- }
348
- // Iterate through blocks in reverse order in chunks of 50
349
- while (end > startHeight) {
350
- start = end - 50;
351
- if (start < startHeight) {
352
- start = startHeight;
353
- }
354
- try {
355
- // Get 50 blocks (or the difference between the start and end if less than 50)
356
- const blocks = await this.getBlockRange(start, end);
357
- end = start;
358
- // Iterate through blocks to find unspent records
359
- for (let i = 0; i < blocks.length; i++) {
360
- const block = blocks[i];
361
- const transactions = block.transactions;
362
- if (!(typeof transactions === "undefined")) {
363
- for (let j = 0; j < transactions.length; j++) {
364
- const confirmedTransaction = transactions[j];
365
- // Search for unspent records in execute transactions of credits.aleo
366
- if (confirmedTransaction.type == "execute") {
367
- const transaction = confirmedTransaction.transaction;
368
- if (transaction.execution &&
369
- !(typeof transaction.execution
370
- .transitions == "undefined")) {
371
- for (let k = 0; k <
372
- transaction.execution.transitions
373
- .length; k++) {
374
- const transition = transaction.execution.transitions[k];
375
- // Only search for unspent records in the specified programs.
376
- if (!(typeof programs === "undefined")) {
377
- if (!programs.includes(transition.program)) {
378
- continue;
379
- }
380
- }
381
- if (!(typeof transition.outputs ==
382
- "undefined")) {
383
- for (let l = 0; l < transition.outputs.length; l++) {
384
- const output = transition.outputs[l];
385
- if (output.type === "record") {
386
- try {
387
- // Create a wasm record ciphertext object from the found output
388
- const record = RecordCiphertext.fromString(output.value);
389
- // Determine if the record is owned by the specified view key
390
- if (record.isOwner(viewKey)) {
391
- // Decrypt the record and get the serial number
392
- const recordPlaintext = record.decrypt(viewKey);
393
- // If the record has already been found, skip it
394
- const nonce = recordPlaintext.nonce();
395
- if (nonces.includes(nonce)) {
396
- continue;
397
- }
398
- if (unspent) {
399
- // Otherwise record the nonce that has been found
400
- const serialNumber = recordPlaintext.serialNumberString(resolvedPrivateKey, "credits.aleo", "credits");
401
- // Attempt to see if the serial number is spent
402
- try {
403
- await retryWithBackoff(() => this.getTransitionId(serialNumber));
404
- continue;
405
- }
406
- catch (error) {
407
- console.log("Found unspent record!");
408
- }
409
- }
410
- // Add the record to the list of records if the user did not specify amounts.
411
- if (!amounts) {
412
- records.push(recordPlaintext);
413
- // If the user specified a maximum number of microcredits, check if the search has found enough
414
- if (typeof maxMicrocredits ===
415
- "number") {
416
- totalRecordValue +=
417
- recordPlaintext.microcredits();
418
- // Exit if the search has found the amount specified
419
- if (totalRecordValue >=
420
- BigInt(maxMicrocredits)) {
421
- return records;
422
- }
423
- }
424
- }
425
- // If the user specified a list of amounts, check if the search has found them
426
- if (!(typeof amounts ===
427
- "undefined") &&
428
- amounts.length >
429
- 0) {
430
- let amounts_found = 0;
431
- if (recordPlaintext.microcredits() >
432
- amounts[amounts_found]) {
433
- amounts_found += 1;
434
- records.push(recordPlaintext);
435
- // If the user specified a maximum number of microcredits, check if the search has found enough
436
- if (typeof maxMicrocredits ===
437
- "number") {
438
- totalRecordValue +=
439
- recordPlaintext.microcredits();
440
- // Exit if the search has found the amount specified
441
- if (totalRecordValue >=
442
- BigInt(maxMicrocredits)) {
443
- return records;
444
- }
445
- }
446
- if (records.length >=
447
- amounts.length) {
448
- return records;
449
- }
450
- }
451
- }
452
- }
453
- }
454
- catch (error) { }
455
- }
456
- }
457
- }
458
- }
459
- }
460
- }
461
- }
462
- }
463
- }
464
- }
465
- catch (error) {
466
- // If there is an error fetching blocks, log it and keep searching
467
- console.warn("Error fetching blocks in range: " +
468
- start.toString() +
469
- "-" +
470
- end.toString());
471
- console.warn("Error: ", error);
472
- failures += 1;
473
- if (failures > 10) {
474
- console.warn("10 failures fetching records reached. Returning records fetched so far");
475
- return records;
476
- }
477
- }
478
- }
479
- return records;
480
- }
481
- /**
482
- * Attempts to find unspent records in the Aleo blockchain.
483
- *
484
- * @param {number} startHeight - The height at which to start searching for unspent records
485
- * @param {number} endHeight - The height at which to stop searching for unspent records
486
- * @param {string[]} programs - The program(s) to search for unspent records in
487
- * @param {number[]} amounts - The amounts (in microcredits) to search for (eg. [100, 200, 3000])
488
- * @param {number} maxMicrocredits - The maximum number of microcredits to search for
489
- * @param {string[]} nonces - The nonces of already found records to exclude from the search
490
- * @param {string | PrivateKey} privateKey - An optional private key to use to find unspent records.
491
- * @returns {Promise<Array<RecordPlaintext>>} An array of unspent records belonging to the account configured in the network client.
492
- *
493
- * @example
494
- * import { Account, AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
495
- *
496
- * const account = Account.fromCiphertext(process.env.ciphertext, process.env.password);
497
- *
498
- * // Create a network client and set an account to search for records with.
499
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
500
- * networkClient.setAccount(account);
501
- *
502
- * // Find specific amounts
503
- * const startHeight = 500000;
504
- * const endHeight = 550000;
505
- * const amounts = [600000, 1000000];
506
- * const records = networkClient.findUnspentRecords(startHeight, endHeight, ["credits.aleo"], amounts);
507
- *
508
- * // Find specific amounts with a maximum number of cumulative microcredits
509
- * const maxMicrocredits = 100000;
510
- * const records = networkClient.findUnspentRecords(startHeight, undefined, ["credits.aleo"], undefined, maxMicrocredits);
511
- */
512
- async findUnspentRecords(startHeight, endHeight, programs, amounts, maxMicrocredits, nonces, privateKey) {
513
- try {
514
- this.ctx = { "X-ALEO-METHOD": "findUnspentRecords" };
515
- return await this.findRecords(startHeight, endHeight, true, programs, amounts, maxMicrocredits, nonces, privateKey);
516
- }
517
- catch (error) {
518
- throw new Error("Error finding unspent records: " + error);
519
- }
520
- finally {
521
- this.ctx = {};
522
- }
523
- }
524
- /**
525
- * Returns the contents of the block at the specified block height.
526
- *
527
- * @param {number} blockHeight - The height of the block to fetch
528
- * @returns {Promise<BlockJSON>} A javascript object containing the block at the specified height
529
- *
530
- * @example
531
- * const block = networkClient.getBlock(1234);
532
- */
533
- async getBlock(blockHeight) {
534
- try {
535
- this.ctx = { "X-ALEO-METHOD": "getBlock" };
536
- const block = await this.fetchData("/block/" + blockHeight);
537
- return block;
538
- }
539
- catch (error) {
540
- throw new Error(`Error fetching block ${blockHeight}: ${error}`);
541
- }
542
- finally {
543
- this.ctx = {};
544
- }
545
- }
546
- /**
547
- * Returns the contents of the block with the specified hash.
548
- *
549
- * @param {string} blockHash The hash of the block to fetch.
550
- * @returns {Promise<BlockJSON>} A javascript object representation of the block matching the hash.
551
- *
552
- * @example
553
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
554
- *
555
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
556
- * const block = networkClient.getBlockByHash("ab19dklwl9vp63zu3hwg57wyhvmqf92fx5g8x0t6dr72py8r87pxupqfne5t9");
557
- */
558
- async getBlockByHash(blockHash) {
559
- try {
560
- this.ctx = { "X-ALEO-METHOD": "getBlockByHash" };
561
- const block = await this.fetchData(`/block/${blockHash}`);
562
- return block;
563
- }
564
- catch (error) {
565
- throw new Error(`Error fetching block ${blockHash}: ${error}`);
566
- }
567
- finally {
568
- this.ctx = {};
569
- }
570
- }
571
- /**
572
- * Returns a range of blocks between the specified block heights. A maximum of 50 blocks can be fetched at a time.
573
- *
574
- * @param {number} start Starting block to fetch.
575
- * @param {number} end Ending block to fetch. This cannot be more than 50 blocks ahead of the start block.
576
- * @returns {Promise<Array<BlockJSON>>} An array of block objects
577
- *
578
- * @example
579
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
580
- *
581
- * // Fetch 50 blocks.
582
- * const (start, end) = (2050, 2100);
583
- * const blockRange = networkClient.getBlockRange(start, end);
584
- *
585
- * let cursor = start;
586
- * blockRange.forEach((block) => {
587
- * assert(block.height == cursor);
588
- * cursor += 1;
589
- * }
590
- */
591
- async getBlockRange(start, end) {
592
- try {
593
- this.ctx = { "X-ALEO-METHOD": "getBlockRange" };
594
- return await this.fetchData("/blocks?start=" + start + "&end=" + end);
595
- }
596
- catch (error) {
597
- throw new Error(`Error fetching blocks between ${start} and ${end}: ${error}`);
598
- }
599
- finally {
600
- this.ctx = {};
601
- }
602
- }
603
- /**
604
- * Returns the deployment transaction id associated with the specified program.
605
- *
606
- * @param {Program | string} program The name of the deployed program OR a wasm Program object.
607
- * @returns {Promise<string>} The transaction ID of the deployment transaction.
608
- *
609
- * @example
610
- * import { AleoNetworkClient } from "@provablehq/sdk/testnet.js";
611
- *
612
- * // Get the transaction ID of the deployment transaction for a program.
613
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
614
- * const transactionId = networkClient.getDeploymentTransactionIDForProgram("hello_hello.aleo");
615
- *
616
- * // Get the transaction data for the deployment transaction.
617
- * const transaction = networkClient.getTransactionObject(transactionId);
618
- *
619
- * // Get the verifying keys for the functions in the deployed program.
620
- * const verifyingKeys = transaction.verifyingKeys();
621
- */
622
- async getDeploymentTransactionIDForProgram(program) {
623
- this.ctx = { "X-ALEO-METHOD": "getDeploymentTransactionIDForProgram" };
624
- if (program instanceof Program) {
625
- program = program.id();
626
- }
627
- try {
628
- const id = await this.fetchData("/find/transactionID/deployment/" + program);
629
- return id.replace('"', "");
630
- }
631
- catch (error) {
632
- throw new Error(`Error fetching deployment transaction for program ${program}: ${error}`);
633
- }
634
- finally {
635
- this.ctx = {};
636
- }
637
- }
638
- /**
639
- * Returns the deployment transaction associated with a specified program as a JSON object.
640
- *
641
- * @param {Program | string} program The name of the deployed program OR a wasm Program object.
642
- * @returns {Promise<Transaction>} JSON representation of the deployment transaction.
643
- *
644
- * @example
645
- * import { AleoNetworkClient, DeploymentJSON } from "@provablehq/sdk/testnet.js";
646
- *
647
- * // Get the transaction ID of the deployment transaction for a program.
648
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
649
- * const transaction = networkClient.getDeploymentTransactionForProgram("hello_hello.aleo");
650
- *
651
- * // Get the verifying keys for each function in the deployment.
652
- * const deployment = <DeploymentJSON>transaction.deployment;
653
- * const verifyingKeys = deployment.verifying_keys;
654
- */
655
- async getDeploymentTransactionForProgram(program) {
656
- if (program instanceof Program) {
657
- program = program.id();
658
- }
659
- try {
660
- this.ctx = { "X-ALEO-METHOD": "getDeploymentTransactionForProgram" };
661
- const transaction_id = (await this.getDeploymentTransactionIDForProgram(program));
662
- return await this.getTransaction(transaction_id);
663
- }
664
- catch (error) {
665
- throw new Error(`Error fetching deployment transaction for program ${program}: ${error}`);
666
- }
667
- finally {
668
- this.ctx = {};
669
- }
670
- }
671
- /**
672
- * Returns the deployment transaction associated with a specified program as a wasm object.
673
- *
674
- * @param {Program | string} program The name of the deployed program OR a wasm Program object.
675
- * @returns {Promise<Transaction>} Wasm object representation of the deployment transaction.
676
- *
677
- * @example
678
- * import { AleoNetworkClient } from "@provablehq/sdk/testnet.js";
679
- *
680
- * // Get the transaction ID of the deployment transaction for a program.
681
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
682
- * const transactionId = networkClient.getDeploymentTransactionIDForProgram("hello_hello.aleo");
683
- *
684
- * // Get the transaction data for the deployment transaction.
685
- * const transaction = networkClient.getDeploymentTransactionObjectForProgram(transactionId);
686
- *
687
- * // Get the verifying keys for the functions in the deployed program.
688
- * const verifyingKeys = transaction.verifyingKeys();
689
- */
690
- async getDeploymentTransactionObjectForProgram(program) {
691
- try {
692
- this.ctx = { "X-ALEO-METHOD": "getDeploymentTransactionObjectForProgram" };
693
- const transaction_id = (await this.getDeploymentTransactionIDForProgram(program));
694
- return await this.getTransactionObject(transaction_id);
695
- }
696
- catch (error) {
697
- throw new Error(`Error fetching deployment transaction for program ${program}: ${error}`);
698
- }
699
- finally {
700
- this.ctx = {};
701
- }
702
- }
703
- /**
704
- * Returns the contents of the latest block as JSON.
705
- *
706
- * @returns {Promise<BlockJSON>} A javascript object containing the latest block
707
- *
708
- * @example
709
- * import { AleoNetworkClient } from "@provablehq/sdk/testnet.js";
710
- *
711
- * // Create a network client.
712
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
713
- *
714
- * const latestHeight = networkClient.getLatestBlock();
715
- */
716
- async getLatestBlock() {
717
- try {
718
- this.ctx = { "X-ALEO-METHOD": "getLatestBlock" };
719
- return (await this.fetchData("/block/latest"));
720
- }
721
- catch (error) {
722
- throw new Error(`Error fetching latest block: ${error}`);
723
- }
724
- finally {
725
- this.ctx = {};
726
- }
727
- }
728
- /**
729
- * Returns the latest committee.
730
- *
731
- * @returns {Promise<object>} A javascript object containing the latest committee
732
- *
733
- * @example
734
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
735
- *
736
- * // Create a network client.
737
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
738
- *
739
- * // Create a network client and get the latest committee.
740
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
741
- * const latestCommittee = await networkClient.getLatestCommittee();
742
- */
743
- async getLatestCommittee() {
744
- try {
745
- this.ctx = { "X-ALEO-METHOD": "getLatestCommittee" };
746
- return await this.fetchData("/committee/latest");
747
- }
748
- catch (error) {
749
- throw new Error(`Error fetching latest committee: ${error}`);
750
- }
751
- finally {
752
- this.ctx = {};
753
- }
754
- }
755
- /**
756
- * Returns the committee at the specified block height.
757
- *
758
- * @param {number} blockHeight - The height of the block to fetch the committee for
759
- * @returns {Promise<object>} A javascript object containing the committee
760
- *
761
- * @example
762
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
763
- *
764
- * // Create a network client.
765
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
766
- *
767
- * // Create a network client and get the committee for a specific block.
768
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
769
- * const committee = await networkClient.getCommitteeByBlockHeight(1234);
770
- */
771
- async getCommitteeByBlockHeight(blockHeight) {
772
- try {
773
- this.ctx = { "X-ALEO-METHOD": "getCommitteeByBlockHeight" };
774
- return await this.fetchData(`/committee/${blockHeight}`);
775
- }
776
- catch (error) {
777
- throw new Error(`Error fetching committee at height ${blockHeight}: ${error}`);
778
- }
779
- finally {
780
- this.ctx = {};
781
- }
782
- }
783
- /**
784
- * Returns the latest block height.
785
- *
786
- * @returns {Promise<number>} The latest block height.
787
- *
788
- * @example
789
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
790
- *
791
- * // Create a network client.
792
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
793
- *
794
- * const latestHeight = networkClient.getLatestHeight();
795
- */
796
- async getLatestHeight() {
797
- try {
798
- this.ctx = { "X-ALEO-METHOD": "getLatestHeight" };
799
- return Number(await this.fetchData("/block/height/latest"));
800
- }
801
- catch (error) {
802
- throw new Error(`Error fetching latest height: ${error}`);
803
- }
804
- finally {
805
- this.ctx = {};
806
- }
807
- }
808
- /**
809
- * Returns the latest block hash.
810
- *
811
- * @returns {Promise<string>} The latest block hash.
812
- *
813
- * @example
814
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
815
- *
816
- * // Create a network client.
817
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
818
- *
819
- * // Get the latest block hash.
820
- * const latestHash = networkClient.getLatestBlockHash();
821
- */
822
- async getLatestBlockHash() {
823
- try {
824
- this.ctx = { "X-ALEO-METHOD": "getLatestBlockHash" };
825
- return String(await this.fetchData("/block/hash/latest"));
826
- }
827
- catch (error) {
828
- throw new Error(`Error fetching latest hash: ${error}`);
829
- }
830
- finally {
831
- this.ctx = {};
832
- }
833
- }
834
- /**
835
- * Returns the source code of a program given a program ID.
836
- *
837
- * @param {string} programId The program ID of a program deployed to the Aleo Network
838
- * @returns {Promise<string>} Source code of the program
839
- *
840
- * @example
841
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
842
- *
843
- * // Create a network client.
844
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
845
- *
846
- * const program = networkClient.getProgram("hello_hello.aleo");
847
- * const expectedSource = "program hello_hello.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n"
848
- * assert.equal(program, expectedSource);
849
- */
850
- async getProgram(programId) {
851
- try {
852
- this.ctx = { "X-ALEO-METHOD": "getProgram" };
853
- return await this.fetchData("/program/" + programId);
854
- }
855
- catch (error) {
856
- throw new Error(`Error fetching program ${programId}: ${error}`);
857
- }
858
- finally {
859
- this.ctx = {};
860
- }
861
- }
862
- /**
863
- * Returns a program object from a program ID or program source code.
864
- *
865
- * @param {string} inputProgram The program ID or program source code of a program deployed to the Aleo Network
866
- * @returns {Promise<Program>} Source code of the program
867
- *
868
- * @example
869
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
870
- *
871
- * // Create a network client.
872
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
873
- *
874
- * const programID = "hello_hello.aleo";
875
- * const programSource = "program hello_hello.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n"
876
- *
877
- * // Get program object from program ID or program source code
878
- * const programObjectFromID = await networkClient.getProgramObject(programID);
879
- * const programObjectFromSource = await networkClient.getProgramObject(programSource);
880
- *
881
- * // Both program objects should be equal
882
- * assert(programObjectFromID.to_string() === programObjectFromSource.to_string());
883
- */
884
- async getProgramObject(inputProgram) {
885
- try {
886
- this.ctx = { "X-ALEO-METHOD": "getProgramObject" };
887
- return Program.fromString(inputProgram);
888
- }
889
- catch (error) {
890
- try {
891
- return Program.fromString(await this.getProgram(inputProgram));
892
- }
893
- catch (error) {
894
- throw new Error(`${inputProgram} is neither a program name or a valid program: ${error}`);
895
- }
896
- }
897
- finally {
898
- this.ctx = {};
899
- }
900
- }
901
- /**
902
- * Returns an object containing the source code of a program and the source code of all programs it imports
903
- *
904
- * @param {Program | string} inputProgram The program ID or program source code of a program deployed to the Aleo Network
905
- * @returns {Promise<ProgramImports>} Object of the form { "program_id": "program_source", .. } containing program id & source code for all program imports
906
- *
907
- * @example
908
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
909
- *
910
- * const double_test_source = "import multiply_test.aleo;\n\nprogram double_test.aleo;\n\nfunction double_it:\n input r0 as u32.private;\n call multiply_test.aleo/multiply 2u32 r0 into r1;\n output r1 as u32.private;\n"
911
- * const double_test = Program.fromString(double_test_source);
912
- * const expectedImports = {
913
- * "multiply_test.aleo": "program multiply_test.aleo;\n\nfunction multiply:\n input r0 as u32.public;\n input r1 as u32.private;\n mul r0 r1 into r2;\n output r2 as u32.private;\n"
914
- * }
915
- *
916
- * // Create a network client.
917
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
918
- *
919
- * // Imports can be fetched using the program ID, source code, or program object
920
- * let programImports = await networkClient.getProgramImports("double_test.aleo");
921
- * assert.deepStrictEqual(programImports, expectedImports);
922
- *
923
- * // Using the program source code
924
- * programImports = await networkClient.getProgramImports(double_test_source);
925
- * assert.deepStrictEqual(programImports, expectedImports);
926
- *
927
- * // Using the program object
928
- * programImports = await networkClient.getProgramImports(double_test);
929
- * assert.deepStrictEqual(programImports, expectedImports);
930
- */
931
- async getProgramImports(inputProgram) {
932
- try {
933
- this.ctx = { "X-ALEO-METHOD": "getProgramImports" };
934
- const imports = {};
935
- // Get the program object or fail if the program is not valid or does not exist
936
- const program = inputProgram instanceof Program
937
- ? inputProgram
938
- : await this.getProgramObject(inputProgram);
939
- // Get the list of programs that the program imports
940
- const importList = program.getImports();
941
- // Recursively get any imports that the imported programs have in a depth first search order
942
- for (let i = 0; i < importList.length; i++) {
943
- const import_id = importList[i];
944
- if (!imports.hasOwnProperty(import_id)) {
945
- const programSource = (await this.getProgram(import_id));
946
- const nestedImports = (await this.getProgramImports(import_id));
947
- for (const key in nestedImports) {
948
- if (!imports.hasOwnProperty(key)) {
949
- imports[key] = nestedImports[key];
950
- }
951
- }
952
- imports[import_id] = programSource;
953
- }
954
- }
955
- return imports;
956
- }
957
- catch (error) {
958
- logAndThrow("Error fetching program imports: " + error.message);
959
- }
960
- finally {
961
- this.ctx = {};
962
- }
963
- }
964
- /**
965
- * Get a list of the program names that a program imports.
966
- *
967
- * @param {Program | string} inputProgram - The program id or program source code to get the imports of
968
- * @returns {string[]} - The list of program names that the program imports
969
- *
970
- * @example
971
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
972
- *
973
- * // Create a network client.
974
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
975
- *
976
- * const programImportsNames = networkClient.getProgramImports("wrapped_credits.aleo");
977
- * const expectedImportsNames = ["credits.aleo"];
978
- * assert.deepStrictEqual(programImportsNames, expectedImportsNames);
979
- */
980
- async getProgramImportNames(inputProgram) {
981
- try {
982
- this.ctx = { "X-ALEO-METHOD": "getProgramImportNames" };
983
- const program = inputProgram instanceof Program
984
- ? inputProgram
985
- : await this.getProgramObject(inputProgram);
986
- return program.getImports();
987
- }
988
- catch (error) {
989
- throw new Error(`Error fetching imports for program ${inputProgram instanceof Program ? inputProgram.id() : inputProgram}: ${error.message}`);
990
- }
991
- finally {
992
- this.ctx = {};
993
- }
994
- }
995
- /**
996
- * Returns the names of the mappings of a program.
997
- *
998
- * @param {string} programId - The program ID to get the mappings of (e.g. "credits.aleo")
999
- * @returns {Promise<Array<string>>} - The names of the mappings of the program.
1000
- *
1001
- * @example
1002
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
1003
- *
1004
- * // Create a network client.
1005
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1006
- *
1007
- * const mappings = networkClient.getProgramMappingNames("credits.aleo");
1008
- * const expectedMappings = [
1009
- * "committee",
1010
- * "delegated",
1011
- * "metadata",
1012
- * "bonded",
1013
- * "unbonding",
1014
- * "account",
1015
- * "withdraw"
1016
- * ];
1017
- * assert.deepStrictEqual(mappings, expectedMappings);
1018
- */
1019
- async getProgramMappingNames(programId) {
1020
- try {
1021
- this.ctx = { "X-ALEO-METHOD": "getProgramMappingNames" };
1022
- return await this.fetchData(`/program/${programId}/mappings`);
1023
- }
1024
- catch (error) {
1025
- throw new Error(`Error fetching mappings for program ${programId} - ensure the program exists on chain before trying again`);
1026
- }
1027
- finally {
1028
- this.ctx = {};
1029
- }
1030
- }
1031
- /**
1032
- * Returns the value of a program's mapping for a specific key.
1033
- *
1034
- * @param {string} programId - The program ID to get the mapping value of (e.g. "credits.aleo")
1035
- * @param {string} mappingName - The name of the mapping to get the value of (e.g. "account")
1036
- * @param {string | Plaintext} key - The key to look up in the mapping (e.g. an address for the "account" mapping)
1037
- * @returns {Promise<string>} String representation of the value of the mapping
1038
- *
1039
- * @example
1040
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
1041
- *
1042
- * // Create a network client.
1043
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1044
- *
1045
- * // Get public balance of an account
1046
- * const mappingValue = networkClient.getMappingValue("credits.aleo", "account", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px");
1047
- * const expectedValue = "0u64";
1048
- * assert(mappingValue === expectedValue);
1049
- */
1050
- async getProgramMappingValue(programId, mappingName, key) {
1051
- try {
1052
- this.ctx = { "X-ALEO-METHOD": "getProgramMappingValue" };
1053
- const keyString = key instanceof Plaintext ? key.toString() : key;
1054
- return await this.fetchData(`/program/${programId}/mapping/${mappingName}/${keyString}`);
1055
- }
1056
- catch (error) {
1057
- throw new Error(`Error fetching value for key '${key}' in mapping '${mappingName}' in program '${programId}' - ensure the mapping exists and the key is correct`);
1058
- }
1059
- finally {
1060
- this.ctx = {};
1061
- }
1062
- }
1063
- /**
1064
- * Returns the value of a mapping as a wasm Plaintext object. Returning an object in this format allows it to be converted to a Js type and for its internal members to be inspected if it's a struct or array.
1065
- *
1066
- * @param {string} programId - The program ID to get the mapping value of (e.g. "credits.aleo")
1067
- * @param {string} mappingName - The name of the mapping to get the value of (e.g. "bonded")
1068
- * @param {string | Plaintext} key - The key to look up in the mapping (e.g. an address for the "bonded" mapping)
1069
- * @returns {Promise<Plaintext>} String representation of the value of the mapping
1070
- *
1071
- * @example
1072
- * import { AleoNetworkClient } from "@provablehq/sdk/mainnet.js";
1073
- *
1074
- * // Create a network client.
1075
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1076
- *
1077
- * // Get the bond state as an account.
1078
- * const unbondedState = networkClient.getMappingPlaintext("credits.aleo", "bonded", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px");
1079
- *
1080
- * // Get the two members of the object individually.
1081
- * const validator = unbondedState.getMember("validator");
1082
- * const microcredits = unbondedState.getMember("microcredits");
1083
- *
1084
- * // Ensure the expected values are correct.
1085
- * assert.equal(validator, "aleo1u6940v5m0fzud859xx2c9tj2gjg6m5qrd28n636e6fdd2akvfcgqs34mfd");
1086
- * assert.equal(microcredits, BigInt("9007199254740991"));
1087
- *
1088
- * // Get a JS object representation of the unbonded state.
1089
- * const unbondedStateObject = unbondedState.toObject();
1090
- *
1091
- * const expectedState = {
1092
- * validator: "aleo1u6940v5m0fzud859xx2c9tj2gjg6m5qrd28n636e6fdd2akvfcgqs34mfd",
1093
- * microcredits: BigInt(9007199254740991)
1094
- * };
1095
- * assert.equal(unbondedState, expectedState);
1096
- */
1097
- async getProgramMappingPlaintext(programId, mappingName, key) {
1098
- try {
1099
- this.ctx = { "X-ALEO-METHOD": "getProgramMappingPlaintext" };
1100
- const keyString = key instanceof Plaintext ? key.toString() : key;
1101
- const value = await this.fetchRaw(`/program/${programId}/mapping/${mappingName}/${keyString}`);
1102
- return Plaintext.fromString(JSON.parse(value));
1103
- }
1104
- catch (error) {
1105
- throw new Error("Failed to fetch mapping value." + error);
1106
- }
1107
- finally {
1108
- this.ctx = {};
1109
- }
1110
- }
1111
- /**
1112
- * Returns the public balance of an address from the account mapping in credits.aleo
1113
- *
1114
- * @param {Address | string} address A string or wasm object representing an address.
1115
- * @returns {Promise<number>} The public balance of the address in microcredits.
1116
- *
1117
- * @example
1118
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1119
- *
1120
- * // Create a network client.
1121
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1122
- *
1123
- * // Get the balance of an account from either an address object or address string.
1124
- * const account = Account.fromCiphertext(process.env.ciphertext, process.env.password);
1125
- * const publicBalance = await networkClient.getPublicBalance(account.address());
1126
- * const publicBalanceFromString = await networkClient.getPublicBalance(account.address().to_string());
1127
- * assert(publicBalance === publicBalanceFromString);
1128
- */
1129
- async getPublicBalance(address) {
1130
- try {
1131
- this.ctx = { "X-ALEO-METHOD": "getPublicBalance" };
1132
- const addressString = address instanceof Address ? address.to_string() : address;
1133
- const balanceStr = await this.getProgramMappingValue("credits.aleo", "account", addressString);
1134
- return balanceStr ? parseInt(balanceStr) : 0;
1135
- }
1136
- catch (error) {
1137
- throw new Error(`Error fetching public balance for ${address}: ${error}`);
1138
- }
1139
- finally {
1140
- this.ctx = {};
1141
- }
1142
- }
1143
- /**
1144
- * Returns the latest state/merkle root of the Aleo blockchain.
1145
- *
1146
- * @returns {Promise<string>} A string representing the latest state root of the Aleo blockchain.
1147
- *
1148
- * @example
1149
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1150
- *
1151
- * // Create a network client.
1152
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1153
- *
1154
- * // Get the latest state root.
1155
- * const stateRoot = networkClient.getStateRoot();
1156
- */
1157
- async getStateRoot() {
1158
- try {
1159
- this.ctx = { "X-ALEO-METHOD": "getStateRoot" };
1160
- return await this.fetchData("/stateRoot/latest");
1161
- }
1162
- catch (error) {
1163
- throw new Error(`Error fetching latest state root: ${error}`);
1164
- }
1165
- finally {
1166
- this.ctx = {};
1167
- }
1168
- }
1169
- /**
1170
- * Returns a transaction by its unique identifier.
1171
- *
1172
- * @param {string} transactionId The transaction ID to fetch.
1173
- * @returns {Promise<TransactionJSON>} A json representation of the transaction.
1174
- *
1175
- * @example
1176
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1177
- *
1178
- * // Create a network client.
1179
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1180
- *
1181
- * const transaction = networkClient.getTransaction("at1handz9xjrqeynjrr0xay4pcsgtnczdksz3e584vfsgaz0dh0lyxq43a4wj");
1182
- */
1183
- async getTransaction(transactionId) {
1184
- try {
1185
- this.ctx = { "X-ALEO-METHOD": "getTransaction" };
1186
- return await this.fetchData("/transaction/" + transactionId);
1187
- }
1188
- catch (error) {
1189
- throw new Error(`Error fetching transaction ${transactionId}: ${error}`);
1190
- }
1191
- finally {
1192
- this.ctx = {};
1193
- }
1194
- }
1195
- /**
1196
- * Returns a confirmed transaction by its unique identifier.
1197
- *
1198
- * @param {string} transactionId The transaction ID to fetch.
1199
- * @returns {Promise<ConfirmedTransactionJSON>} A json object containing the confirmed transaction.
1200
- *
1201
- * @example
1202
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1203
- *
1204
- * // Create a network client.
1205
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1206
- *
1207
- * const transaction = networkClient.getConfirmedTransaction("at1handz9xjrqeynjrr0xay4pcsgtnczdksz3e584vfsgaz0dh0lyxq43a4wj");
1208
- * assert.equal(transaction.status, "confirmed");
1209
- */
1210
- async getConfirmedTransaction(transactionId) {
1211
- try {
1212
- this.ctx = { "X-ALEO-METHOD": "getConfirmedTransaction" };
1213
- return await this.fetchData(`/transaction/confirmed/${transactionId}`);
1214
- }
1215
- catch (error) {
1216
- throw new Error(`Error fetching confirmed transaction ${transactionId}: ${error}`);
1217
- }
1218
- finally {
1219
- this.ctx = {};
1220
- }
1221
- }
1222
- /**
1223
- * Returns a transaction as a wasm object. Getting a transaction of this type will allow the ability for the inputs,
1224
- * outputs, and records to be searched for and displayed.
1225
- *
1226
- * @param {string} transactionId - The unique identifier of the transaction to fetch
1227
- * @returns {Promise<Transaction>} A wasm object representation of the transaction.
1228
- *
1229
- * @example
1230
- * const transactionObject = networkClient.getTransaction("at1handz9xjrqeynjrr0xay4pcsgtnczdksz3e584vfsgaz0dh0lyxq43a4wj");
1231
- * // Get the transaction inputs as a JS array.
1232
- * const transactionInputs = transactionObject.inputs(true);
1233
- *
1234
- * // Get the transaction outputs as a JS object.
1235
- * const transactionOutputs = transactionObject.outputs(true);
1236
- *
1237
- * // Get any records generated in transitions in the transaction as a JS object.
1238
- * const records = transactionObject.records();
1239
- *
1240
- * // Get the transaction type.
1241
- * const transactionType = transactionObject.transactionType();
1242
- * assert.equal(transactionType, "Execute");
1243
- *
1244
- * // Get a JS representation of all inputs, outputs, and transaction metadata.
1245
- * const transactionSummary = transactionObject.summary();
1246
- */
1247
- async getTransactionObject(transactionId) {
1248
- try {
1249
- this.ctx = { "X-ALEO-METHOD": "getTransactionObject" };
1250
- const transaction = await this.fetchRaw("/transaction/" + transactionId);
1251
- return Transaction.fromString(transaction);
1252
- }
1253
- catch (error) {
1254
- throw new Error(`Error fetching transaction object ${transactionId}: ${error}`);
1255
- }
1256
- finally {
1257
- this.ctx = {};
1258
- }
1259
- }
1260
- /**
1261
- * Returns the transactions present at the specified block height.
1262
- *
1263
- * @param {number} blockHeight The block height to fetch the confirmed transactions at.
1264
- * @returns {Promise<Array<ConfirmedTransactionJSON>>} An array of confirmed transactions (in JSON format) for the block height.
1265
- *
1266
- * @example
1267
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1268
- *
1269
- * // Create a network client.
1270
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1271
- *
1272
- * const transactions = networkClient.getTransactions(654);
1273
- */
1274
- async getTransactions(blockHeight) {
1275
- try {
1276
- this.ctx = { "X-ALEO-METHOD": "getTransactions" };
1277
- return await this.fetchData("/block/" + blockHeight.toString() + "/transactions");
1278
- }
1279
- catch (error) {
1280
- throw new Error(`Error fetching transactions: ${error}`);
1281
- }
1282
- finally {
1283
- this.ctx = {};
1284
- }
1285
- }
1286
- /**
1287
- * Returns the confirmed transactions present in the block with the specified block hash.
1288
- *
1289
- * @param {string} blockHash The block hash to fetch the confirmed transactions at.
1290
- * @returns {Promise<Array<ConfirmedTransactionJSON>>} An array of confirmed transactions (in JSON format) for the block hash.
1291
- *
1292
- * @example
1293
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1294
- *
1295
- * // Create a network client.
1296
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1297
- *
1298
- * const transactions = networkClient.getTransactionsByBlockHash("ab19dklwl9vp63zu3hwg57wyhvmqf92fx5g8x0t6dr72py8r87pxupqfne5t9");
1299
- */
1300
- async getTransactionsByBlockHash(blockHash) {
1301
- try {
1302
- this.ctx = { "X-ALEO-METHOD": "getTransactionsByBlockHash" };
1303
- const block = await this.fetchData(`/block/${blockHash}`);
1304
- const height = block.header.metadata.height;
1305
- return await this.getTransactions(Number(height));
1306
- }
1307
- catch (error) {
1308
- throw new Error(`Error fetching transactions for block ${blockHash}: ${error}`);
1309
- }
1310
- finally {
1311
- this.ctx = {};
1312
- }
1313
- }
1314
- /**
1315
- * Returns the transactions in the memory pool. This method requires access to a validator's REST API.
1316
- *
1317
- * @returns {Promise<Array<TransactionJSON>>} An array of transactions (in JSON format) currently in the mempool.
1318
- *
1319
- * @example
1320
- * import { AleoNetworkClient, Account } from "@provablehq/sdk/mainnet.js";
1321
- *
1322
- * // Create a network client.
1323
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1324
- *
1325
- * // Get the current transactions in the mempool.
1326
- * const transactions = networkClient.getTransactionsInMempool();
1327
- */
1328
- async getTransactionsInMempool() {
1329
- try {
1330
- this.ctx = { "X-ALEO-METHOD": "getTransactionsInMempool" };
1331
- return await this.fetchData("/memoryPool/transactions");
1332
- }
1333
- catch (error) {
1334
- throw new Error(`Error fetching transactions from mempool: ${error}`);
1335
- }
1336
- finally {
1337
- this.ctx = {};
1338
- }
1339
- }
1340
- /**
1341
- * Returns the transition ID of the transition corresponding to the ID of the input or output.
1342
- * @param {string} inputOrOutputID - The unique identifier of the input or output to find the transition ID for
1343
- * @returns {Promise<string>} - The transition ID of the input or output ID.
1344
- *
1345
- * @example
1346
- * const transitionId = networkClient.getTransitionId("2429232855236830926144356377868449890830704336664550203176918782554219952323field");
1347
- */
1348
- async getTransitionId(inputOrOutputID) {
1349
- try {
1350
- this.ctx = { "X-ALEO-METHOD": "getTransitionId" };
1351
- return await this.fetchData("/find/transitionID/" + inputOrOutputID);
1352
- }
1353
- catch (error) {
1354
- throw new Error(`Error fetching transition ID for input/output ${inputOrOutputID}: ${error}`);
1355
- }
1356
- finally {
1357
- this.ctx = {};
1358
- }
1359
- }
1360
- /**
1361
- * Submit an execute or deployment transaction to the Aleo network.
1362
- *
1363
- * @param {Transaction | string} transaction - The transaction to submit, either as a Transaction object or string representation
1364
- * @returns {Promise<string>} - The transaction id of the submitted transaction or the resulting error
1365
- */
1366
- async submitTransaction(transaction) {
1367
- const transactionString = transaction instanceof Transaction
1368
- ? transaction.toString()
1369
- : transaction;
1370
- try {
1371
- const response = await retryWithBackoff(() => this._sendPost(this.host + "/transaction/broadcast", {
1372
- body: transactionString,
1373
- headers: Object.assign({}, { ...this.headers, "X-ALEO-METHOD": "submitTransaction" }, {
1374
- "Content-Type": "application/json",
1375
- }),
1376
- }));
1377
- try {
1378
- const text = await response.text();
1379
- return parseJSON(text);
1380
- }
1381
- catch (error) {
1382
- throw new Error(`Error posting transaction. Aleo network response: ${error.message}`);
1383
- }
1384
- }
1385
- catch (error) {
1386
- throw new Error(`Error posting transaction: No response received: ${error.message}`);
1387
- }
1388
- }
1389
- /**
1390
- * Submit a solution to the Aleo network.
1391
- *
1392
- * @param {string} solution - The string representation of the solution to submit
1393
- * @returns {Promise<string>} The solution id of the submitted solution or the resulting error.
1394
- */
1395
- async submitSolution(solution) {
1396
- try {
1397
- const response = await retryWithBackoff(() => post(this.host + "/solution/broadcast", {
1398
- body: solution,
1399
- headers: Object.assign({}, { ...this.headers, "X-ALEO-METHOD": "submitSolution" }, {
1400
- "Content-Type": "application/json",
1401
- }),
1402
- }));
1403
- try {
1404
- const text = await response.text();
1405
- return parseJSON(text);
1406
- }
1407
- catch (error) {
1408
- throw new Error(`Error posting solution. Aleo network response: ${error.message}`);
1409
- }
1410
- }
1411
- catch (error) {
1412
- throw new Error(`Error posting solution: No response received: ${error.message}`);
1413
- }
1414
- }
1415
- /**
1416
- * Await a submitted transaction to be confirmed or rejected on the Aleo network.
1417
- *
1418
- * @param {string} transactionId - The transaction ID to wait for confirmation
1419
- * @param {number} checkInterval - The interval in milliseconds to check for confirmation (default: 2000)
1420
- * @param {number} timeout - The maximum time in milliseconds to wait for confirmation (default: 45000)
1421
- * @returns {Promise<Transaction>} The confirmed transaction object that returns if the transaction is confirmed.
1422
- *
1423
- * @example
1424
- * import { AleoNetworkClient, Account, ProgramManager } from "@provablehq/sdk/mainnet.js";
1425
- *
1426
- * // Create a network client and program manager.
1427
- * const networkClient = new AleoNetworkClient("http://api.explorer.provable.com/v1", undefined);
1428
- * const programManager = new ProgramManager(networkClient);
1429
- *
1430
- * // Set the account for the program manager.
1431
- * programManager.setAccount(Account.fromCiphertext(process.env.ciphertext, process.env.password));
1432
- *
1433
- * // Build a transfer transaction.
1434
- * const tx = await programManager.buildTransferPublicTransaction(100, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", 0);
1435
- *
1436
- * // Submit the transaction to the network.
1437
- * const transactionId = await networkClient.submitTransaction(tx);
1438
- *
1439
- * // Wait for the transaction to be confirmed.
1440
- * const transaction = await networkClient.waitForTransactionConfirmation(transactionId);
1441
- */
1442
- async waitForTransactionConfirmation(transactionId, checkInterval = 2000, timeout = 45000) {
1443
- const startTime = Date.now();
1444
- return new Promise((resolve, reject) => {
1445
- const interval = setInterval(async () => {
1446
- const elapsed = Date.now() - startTime;
1447
- if (elapsed > timeout) {
1448
- clearInterval(interval);
1449
- return reject(new Error(`Transaction ${transactionId} did not appear after the timeout period of ${interval}ms - consider resubmitting the transaction`));
1450
- }
1451
- try {
1452
- const res = await fetch(`${this.host}/transaction/confirmed/${transactionId}`, {
1453
- headers: {
1454
- ...this.headers,
1455
- "X-ALEO-METHOD": "waitForTransactionConfirmation",
1456
- },
1457
- });
1458
- if (!res.ok) {
1459
- let text = "";
1460
- try {
1461
- text = await res.text();
1462
- console.warn("Response text from server:", text);
1463
- }
1464
- catch (err) {
1465
- console.warn("Failed to read response text:", err);
1466
- }
1467
- // If the transaction ID is malformed (e.g. invalid checksum, wrong length),
1468
- // the API returns a 4XX with "Invalid URL" — we treat this as a fatal error and stop polling.
1469
- if (res.status >= 400 &&
1470
- res.status < 500 &&
1471
- text.includes("Invalid URL")) {
1472
- clearInterval(interval);
1473
- return reject(new Error(`Malformed transaction ID: ${text}`));
1474
- }
1475
- // Log and continue polling for 404s or 5XX errors in case a tx doesn't exist yet
1476
- console.warn("Non-OK response (retrying):", res.status, text);
1477
- return;
1478
- }
1479
- const data = parseJSON(await res.text());
1480
- if (data?.status === "accepted") {
1481
- clearInterval(interval);
1482
- return resolve(data);
1483
- }
1484
- if (data?.status === "rejected") {
1485
- clearInterval(interval);
1486
- return reject(new Error(`Transaction ${transactionId} was rejected by the network. Ensure that the account paying the fee has enough credits and that the inputs to the on-chain function are valid.`));
1487
- }
1488
- }
1489
- catch (err) {
1490
- console.error("Polling error:", err);
1491
- }
1492
- }, checkInterval);
1493
- });
1494
- }
1495
- }
1496
-
1497
- const KEY_STORE = Metadata.baseUrl();
1498
- function convert(metadata) {
1499
- // This looks up the method name in VerifyingKey
1500
- const verifyingKey = VerifyingKey[metadata.verifyingKey];
1501
- if (!verifyingKey) {
1502
- throw new Error("Invalid method name: " + metadata.verifyingKey);
1503
- }
1504
- return {
1505
- name: metadata.name,
1506
- locator: metadata.locator,
1507
- prover: metadata.prover,
1508
- verifier: metadata.verifier,
1509
- verifyingKey,
1510
- };
1511
- }
1512
- const CREDITS_PROGRAM_KEYS = {
1513
- bond_public: convert(Metadata.bond_public()),
1514
- bond_validator: convert(Metadata.bond_validator()),
1515
- claim_unbond_public: convert(Metadata.claim_unbond_public()),
1516
- fee_private: convert(Metadata.fee_private()),
1517
- fee_public: convert(Metadata.fee_public()),
1518
- inclusion: convert(Metadata.inclusion()),
1519
- join: convert(Metadata.join()),
1520
- set_validator_state: convert(Metadata.set_validator_state()),
1521
- split: convert(Metadata.split()),
1522
- transfer_private: convert(Metadata.transfer_private()),
1523
- transfer_private_to_public: convert(Metadata.transfer_private_to_public()),
1524
- transfer_public: convert(Metadata.transfer_public()),
1525
- transfer_public_as_signer: convert(Metadata.transfer_public_as_signer()),
1526
- transfer_public_to_private: convert(Metadata.transfer_public_to_private()),
1527
- unbond_public: convert(Metadata.unbond_public()),
1528
- getKey: function (key) {
1529
- if (this.hasOwnProperty(key)) {
1530
- return this[key];
1531
- }
1532
- else {
1533
- throw new Error(`Key "${key}" not found.`);
1534
- }
1535
- }
1536
- };
1537
- const PRIVATE_TRANSFER_TYPES = new Set([
1538
- "transfer_private",
1539
- "private",
1540
- "transferPrivate",
1541
- "transfer_private_to_public",
1542
- "privateToPublic",
1543
- "transferPrivateToPublic",
1544
- ]);
1545
- const VALID_TRANSFER_TYPES = new Set([
1546
- "transfer_private",
1547
- "private",
1548
- "transferPrivate",
1549
- "transfer_private_to_public",
1550
- "privateToPublic",
1551
- "transferPrivateToPublic",
1552
- "transfer_public",
1553
- "transfer_public_as_signer",
1554
- "public",
1555
- "public_as_signer",
1556
- "transferPublic",
1557
- "transferPublicAsSigner",
1558
- "transfer_public_to_private",
1559
- "publicToPrivate",
1560
- "publicAsSigner",
1561
- "transferPublicToPrivate",
1562
- ]);
1563
- const PRIVATE_TRANSFER = new Set([
1564
- "private",
1565
- "transfer_private",
1566
- "transferPrivate",
1567
- ]);
1568
- const PRIVATE_TO_PUBLIC_TRANSFER = new Set([
1569
- "private_to_public",
1570
- "privateToPublic",
1571
- "transfer_private_to_public",
1572
- "transferPrivateToPublic",
1573
- ]);
1574
- const PUBLIC_TRANSFER = new Set([
1575
- "public",
1576
- "transfer_public",
1577
- "transferPublic",
1578
- ]);
1579
- const PUBLIC_TRANSFER_AS_SIGNER = new Set([
1580
- "public_as_signer",
1581
- "transfer_public_as_signer",
1582
- "transferPublicAsSigner",
1583
- ]);
1584
- const PUBLIC_TO_PRIVATE_TRANSFER = new Set([
1585
- "public_to_private",
1586
- "publicToPrivate",
1587
- "transfer_public_to_private",
1588
- "transferPublicToPrivate",
1589
- ]);
1590
-
1591
- /**
1592
- * AleoKeyProviderParams search parameter for the AleoKeyProvider. It allows for the specification of a proverUri and
1593
- * verifierUri to fetch keys via HTTP from a remote resource as well as a unique cacheKey to store the keys in memory.
1594
- */
1595
- class AleoKeyProviderParams {
1596
- name;
1597
- proverUri;
1598
- verifierUri;
1599
- cacheKey;
1600
- /**
1601
- * Create a new AleoKeyProviderParams object which implements the KeySearchParams interface. Users can optionally
1602
- * specify a url for the proverUri & verifierUri to fetch keys via HTTP from a remote resource as well as a unique
1603
- * cacheKey to store the keys in memory for future use. If no proverUri or verifierUri is specified, a cachekey must
1604
- * be provided.
1605
- *
1606
- * @param { AleoKeyProviderInitParams } params - Optional search parameters
1607
- */
1608
- constructor(params) {
1609
- this.proverUri = params.proverUri;
1610
- this.verifierUri = params.verifierUri;
1611
- this.cacheKey = params.cacheKey;
1612
- this.name = params.name;
1613
- }
1614
- }
1615
- /**
1616
- * AleoKeyProvider class. Implements the KeyProvider interface. Enables the retrieval of Aleo program proving and
1617
- * verifying keys for the credits.aleo program over http from official Aleo sources and storing and retrieving function
1618
- * keys from a local memory cache.
1619
- */
1620
- class AleoKeyProvider {
1621
- cache;
1622
- cacheOption;
1623
- keyUris;
1624
- async fetchBytes(url = "/") {
1625
- try {
1626
- const response = await get(url);
1627
- const data = await response.arrayBuffer();
1628
- return new Uint8Array(data);
1629
- }
1630
- catch (error) {
1631
- throw new Error("Error fetching data." + error.message);
1632
- }
1633
- }
1634
- constructor() {
1635
- this.keyUris = KEY_STORE;
1636
- this.cache = new Map();
1637
- this.cacheOption = false;
1638
- }
1639
- /**
1640
- * Use local memory to store keys
1641
- *
1642
- * @param {boolean} useCache whether to store keys in local memory
1643
- */
1644
- useCache(useCache) {
1645
- this.cacheOption = useCache;
1646
- }
1647
- /**
1648
- * Clear the key cache
1649
- */
1650
- clearCache() {
1651
- this.cache.clear();
1652
- }
1653
- /**
1654
- * Cache a set of keys. This will overwrite any existing keys with the same keyId. The user can check if a keyId
1655
- * exists in the cache using the containsKeys method prior to calling this method if overwriting is not desired.
1656
- *
1657
- * @param {string} keyId access key for the cache
1658
- * @param {FunctionKeyPair} keys keys to cache
1659
- */
1660
- cacheKeys(keyId, keys) {
1661
- const [provingKey, verifyingKey] = keys;
1662
- this.cache.set(keyId, [provingKey.toBytes(), verifyingKey.toBytes()]);
1663
- }
1664
- /**
1665
- * Determine if a keyId exists in the cache
1666
- *
1667
- * @param {string} keyId keyId of a proving and verifying key pair
1668
- * @returns {boolean} true if the keyId exists in the cache, false otherwise
1669
- */
1670
- containsKeys(keyId) {
1671
- return this.cache.has(keyId);
1672
- }
1673
- /**
1674
- * Delete a set of keys from the cache
1675
- *
1676
- * @param {string} keyId keyId of a proving and verifying key pair to delete from memory
1677
- * @returns {boolean} true if the keyId exists in the cache and was deleted, false if the key did not exist
1678
- */
1679
- deleteKeys(keyId) {
1680
- return this.cache.delete(keyId);
1681
- }
1682
- /**
1683
- * Get a set of keys from the cache
1684
- * @param keyId keyId of a proving and verifying key pair
1685
- *
1686
- * @returns {FunctionKeyPair} Proving and verifying keys for the specified program
1687
- */
1688
- getKeys(keyId) {
1689
- console.debug(`Checking if key exists in cache. KeyId: ${keyId}`);
1690
- if (this.cache.has(keyId)) {
1691
- const [provingKeyBytes, verifyingKeyBytes] = this.cache.get(keyId);
1692
- return [ProvingKey.fromBytes(provingKeyBytes), VerifyingKey.fromBytes(verifyingKeyBytes)];
1693
- }
1694
- else {
1695
- throw new Error("Key not found in cache.");
1696
- }
1697
- }
1698
- /**
1699
- * Get arbitrary function keys from a provider
1700
- *
1701
- * @param {KeySearchParams} params parameters for the key search in form of: {proverUri: string, verifierUri: string, cacheKey: string}
1702
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the specified program
1703
- *
1704
- * @example
1705
- * // Create a new object which implements the KeyProvider interface
1706
- * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1707
- * const keyProvider = new AleoKeyProvider();
1708
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
1709
- *
1710
- * // Initialize a program manager with the key provider to automatically fetch keys for value transfers
1711
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1712
- * programManager.transfer(1, "aleo166q6ww6688cug7qxwe7nhctjpymydwzy2h7rscfmatqmfwnjvggqcad0at", "public", 0.5);
1713
- *
1714
- * // Keys can also be fetched manually using the key provider
1715
- * const keySearchParams = { "cacheKey": "myProgram:myFunction" };
1716
- * const [transferPrivateProvingKey, transferPrivateVerifyingKey] = await keyProvider.functionKeys(keySearchParams);
1717
- */
1718
- async functionKeys(params) {
1719
- if (params) {
1720
- let proverUrl;
1721
- let verifierUrl;
1722
- let cacheKey;
1723
- if ("name" in params && typeof params["name"] == "string") {
1724
- let key = CREDITS_PROGRAM_KEYS.getKey(params["name"]);
1725
- return this.fetchCreditsKeys(key);
1726
- }
1727
- if ("proverUri" in params && typeof params["proverUri"] == "string") {
1728
- proverUrl = params["proverUri"];
1729
- }
1730
- if ("verifierUri" in params && typeof params["verifierUri"] == "string") {
1731
- verifierUrl = params["verifierUri"];
1732
- }
1733
- if ("cacheKey" in params && typeof params["cacheKey"] == "string") {
1734
- cacheKey = params["cacheKey"];
1735
- }
1736
- if (proverUrl && verifierUrl) {
1737
- return await this.fetchRemoteKeys(proverUrl, verifierUrl, cacheKey);
1738
- }
1739
- if (cacheKey) {
1740
- return this.getKeys(cacheKey);
1741
- }
1742
- }
1743
- throw new Error("Invalid parameters provided, must provide either a cacheKey and/or a proverUrl and a verifierUrl");
1744
- }
1745
- /**
1746
- * Returns the proving and verifying keys for a specified program from a specified url.
1747
- *
1748
- * @param {string} verifierUrl Url of the proving key
1749
- * @param {string} proverUrl Url the verifying key
1750
- * @param {string} cacheKey Key to store the keys in the cache
1751
- *
1752
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the specified program
1753
- *
1754
- * @example
1755
- * // Create a new AleoKeyProvider object
1756
- * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1757
- * const keyProvider = new AleoKeyProvider();
1758
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
1759
- *
1760
- * // Initialize a program manager with the key provider to automatically fetch keys for value transfers
1761
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1762
- * programManager.transfer(1, "aleo166q6ww6688cug7qxwe7nhctjpymydwzy2h7rscfmatqmfwnjvggqcad0at", "public", 0.5);
1763
- *
1764
- * // Keys can also be fetched manually
1765
- * const [transferPrivateProvingKey, transferPrivateVerifyingKey] = await keyProvider.fetchKeys(
1766
- * CREDITS_PROGRAM_KEYS.transfer_private.prover,
1767
- * CREDITS_PROGRAM_KEYS.transfer_private.verifier,
1768
- * );
1769
- */
1770
- async fetchRemoteKeys(proverUrl, verifierUrl, cacheKey) {
1771
- try {
1772
- // If cache is enabled, check if the keys have already been fetched and return them if they have
1773
- if (this.cacheOption) {
1774
- if (!cacheKey) {
1775
- cacheKey = proverUrl;
1776
- }
1777
- const value = this.cache.get(cacheKey);
1778
- if (typeof value !== "undefined") {
1779
- return [ProvingKey.fromBytes(value[0]), VerifyingKey.fromBytes(value[1])];
1780
- }
1781
- else {
1782
- console.debug("Fetching proving keys from url " + proverUrl);
1783
- const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
1784
- console.debug("Fetching verifying keys " + verifierUrl);
1785
- const verifyingKey = (await this.getVerifyingKey(verifierUrl));
1786
- this.cache.set(cacheKey, [provingKey.toBytes(), verifyingKey.toBytes()]);
1787
- return [provingKey, verifyingKey];
1788
- }
1789
- }
1790
- else {
1791
- // If cache is disabled, fetch the keys and return them
1792
- const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
1793
- const verifyingKey = (await this.getVerifyingKey(verifierUrl));
1794
- return [provingKey, verifyingKey];
1795
- }
1796
- }
1797
- catch (error) {
1798
- throw new Error(`Error: ${error.message} fetching fee proving and verifying keys from ${proverUrl} and ${verifierUrl}.`);
1799
- }
1800
- }
1801
- /***
1802
- * Fetches the proving key from a remote source.
1803
- *
1804
- * @param proverUrl
1805
- * @param cacheKey
1806
- *
1807
- * @returns {Promise<ProvingKey>} Proving key for the specified program
1808
- */
1809
- async fetchProvingKey(proverUrl, cacheKey) {
1810
- try {
1811
- // If cache is enabled, check if the keys have already been fetched and return them if they have
1812
- if (this.cacheOption) {
1813
- if (!cacheKey) {
1814
- cacheKey = proverUrl;
1815
- }
1816
- const value = this.cache.get(cacheKey);
1817
- if (typeof value !== "undefined") {
1818
- return ProvingKey.fromBytes(value[0]);
1819
- }
1820
- else {
1821
- console.debug("Fetching proving keys from url " + proverUrl);
1822
- const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
1823
- return provingKey;
1824
- }
1825
- }
1826
- else {
1827
- const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
1828
- return provingKey;
1829
- }
1830
- }
1831
- catch (error) {
1832
- throw new Error(`Error: ${error.message} fetching fee proving keys from ${proverUrl}`);
1833
- }
1834
- }
1835
- async fetchCreditsKeys(key) {
1836
- try {
1837
- if (!this.cache.has(key.locator) || !this.cacheOption) {
1838
- const verifying_key = key.verifyingKey();
1839
- const proving_key = await this.fetchProvingKey(key.prover, key.locator);
1840
- if (this.cacheOption) {
1841
- this.cache.set(CREDITS_PROGRAM_KEYS.bond_public.locator, [proving_key.toBytes(), verifying_key.toBytes()]);
1842
- }
1843
- return [proving_key, verifying_key];
1844
- }
1845
- else {
1846
- const keyPair = this.cache.get(key.locator);
1847
- return [ProvingKey.fromBytes(keyPair[0]), VerifyingKey.fromBytes(keyPair[1])];
1848
- }
1849
- }
1850
- catch (error) {
1851
- throw new Error(`Error: fetching credits.aleo keys: ${error.message}`);
1852
- }
1853
- }
1854
- async bondPublicKeys() {
1855
- return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.bond_public);
1856
- }
1857
- bondValidatorKeys() {
1858
- return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.bond_validator);
1859
- }
1860
- claimUnbondPublicKeys() {
1861
- return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.claim_unbond_public);
1862
- }
1863
- /**
1864
- * Returns the proving and verifying keys for the transfer functions in the credits.aleo program
1865
- * @param {string} visibility Visibility of the transfer function
1866
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the transfer functions
1867
- *
1868
- * @example
1869
- * // Create a new AleoKeyProvider
1870
- * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1871
- * const keyProvider = new AleoKeyProvider();
1872
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
1873
- *
1874
- * // Initialize a program manager with the key provider to automatically fetch keys for value transfers
1875
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1876
- * programManager.transfer(1, "aleo166q6ww6688cug7qxwe7nhctjpymydwzy2h7rscfmatqmfwnjvggqcad0at", "public", 0.5);
1877
- *
1878
- * // Keys can also be fetched manually
1879
- * const [transferPublicProvingKey, transferPublicVerifyingKey] = await keyProvider.transferKeys("public");
1880
- */
1881
- async transferKeys(visibility) {
1882
- if (PRIVATE_TRANSFER.has(visibility)) {
1883
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_private);
1884
- }
1885
- else if (PRIVATE_TO_PUBLIC_TRANSFER.has(visibility)) {
1886
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_private_to_public);
1887
- }
1888
- else if (PUBLIC_TRANSFER.has(visibility)) {
1889
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_public);
1890
- }
1891
- else if (PUBLIC_TRANSFER_AS_SIGNER.has(visibility)) {
1892
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_public_as_signer);
1893
- }
1894
- else if (PUBLIC_TO_PRIVATE_TRANSFER.has(visibility)) {
1895
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_public_to_private);
1896
- }
1897
- else {
1898
- throw new Error("Invalid visibility type");
1899
- }
1900
- }
1901
- /**
1902
- * Returns the proving and verifying keys for the join function in the credits.aleo program
1903
- *
1904
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the join function
1905
- */
1906
- async joinKeys() {
1907
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.join);
1908
- }
1909
- /**
1910
- * Returns the proving and verifying keys for the split function in the credits.aleo program
1911
- *
1912
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the split function
1913
- * */
1914
- async splitKeys() {
1915
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.split);
1916
- }
1917
- /**
1918
- * Returns the proving and verifying keys for the fee_private function in the credits.aleo program
1919
- *
1920
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the fee function
1921
- */
1922
- async feePrivateKeys() {
1923
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.fee_private);
1924
- }
1925
- /**
1926
- * Returns the proving and verifying keys for the fee_public function in the credits.aleo program
1927
- *
1928
- * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the fee function
1929
- */
1930
- async feePublicKeys() {
1931
- return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.fee_public);
1932
- }
1933
- /**
1934
- * Gets a verifying key. If the verifying key is for a credits.aleo function, get it from the wasm cache otherwise
1935
- *
1936
- * @returns {Promise<VerifyingKey>} Verifying key for the function
1937
- */
1938
- // attempt to fetch it from the network
1939
- async getVerifyingKey(verifierUri) {
1940
- switch (verifierUri) {
1941
- case CREDITS_PROGRAM_KEYS.bond_public.verifier:
1942
- return CREDITS_PROGRAM_KEYS.bond_public.verifyingKey();
1943
- case CREDITS_PROGRAM_KEYS.bond_validator.verifier:
1944
- return CREDITS_PROGRAM_KEYS.bond_validator.verifyingKey();
1945
- case CREDITS_PROGRAM_KEYS.claim_unbond_public.verifier:
1946
- return CREDITS_PROGRAM_KEYS.claim_unbond_public.verifyingKey();
1947
- case CREDITS_PROGRAM_KEYS.fee_private.verifier:
1948
- return CREDITS_PROGRAM_KEYS.fee_private.verifyingKey();
1949
- case CREDITS_PROGRAM_KEYS.fee_public.verifier:
1950
- return CREDITS_PROGRAM_KEYS.fee_public.verifyingKey();
1951
- case CREDITS_PROGRAM_KEYS.inclusion.verifier:
1952
- return CREDITS_PROGRAM_KEYS.inclusion.verifyingKey();
1953
- case CREDITS_PROGRAM_KEYS.join.verifier:
1954
- return CREDITS_PROGRAM_KEYS.join.verifyingKey();
1955
- case CREDITS_PROGRAM_KEYS.set_validator_state.verifier:
1956
- return CREDITS_PROGRAM_KEYS.set_validator_state.verifyingKey();
1957
- case CREDITS_PROGRAM_KEYS.split.verifier:
1958
- return CREDITS_PROGRAM_KEYS.split.verifyingKey();
1959
- case CREDITS_PROGRAM_KEYS.transfer_private.verifier:
1960
- return CREDITS_PROGRAM_KEYS.transfer_private.verifyingKey();
1961
- case CREDITS_PROGRAM_KEYS.transfer_private_to_public.verifier:
1962
- return CREDITS_PROGRAM_KEYS.transfer_private_to_public.verifyingKey();
1963
- case CREDITS_PROGRAM_KEYS.transfer_public.verifier:
1964
- return CREDITS_PROGRAM_KEYS.transfer_public.verifyingKey();
1965
- case CREDITS_PROGRAM_KEYS.transfer_public_as_signer.verifier:
1966
- return CREDITS_PROGRAM_KEYS.transfer_public_as_signer.verifyingKey();
1967
- case CREDITS_PROGRAM_KEYS.transfer_public_to_private.verifier:
1968
- return CREDITS_PROGRAM_KEYS.transfer_public_to_private.verifyingKey();
1969
- case CREDITS_PROGRAM_KEYS.unbond_public.verifier:
1970
- return CREDITS_PROGRAM_KEYS.unbond_public.verifyingKey();
1971
- default:
1972
- try {
1973
- /// Try to fetch the verifying key from the network as a string
1974
- const response = await get(verifierUri);
1975
- const text = await response.text();
1976
- return VerifyingKey.fromString(text);
1977
- }
1978
- catch (e) {
1979
- /// If that fails, try to fetch the verifying key from the network as bytes
1980
- try {
1981
- return VerifyingKey.fromBytes(await this.fetchBytes(verifierUri));
1982
- }
1983
- catch (inner) {
1984
- throw new Error("Invalid verifying key. Error: " + inner.message);
1985
- }
1986
- }
1987
- }
1988
- }
1989
- unBondPublicKeys() {
1990
- return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.unbond_public);
1991
- }
1992
- }
1993
-
1994
- /**
1995
- * The ProgramManager class is used to execute and deploy programs on the Aleo network and create value transfers.
1996
- */
1997
- class ProgramManager {
1998
- account;
1999
- keyProvider;
2000
- host;
2001
- networkClient;
2002
- recordProvider;
2003
- /** Create a new instance of the ProgramManager
2004
- *
2005
- * @param { string | undefined } host A host uri running the official Aleo API
2006
- * @param { FunctionKeyProvider | undefined } keyProvider A key provider that implements {@link FunctionKeyProvider} interface
2007
- * @param { RecordProvider | undefined } recordProvider A record provider that implements {@link RecordProvider} interface
2008
- */
2009
- constructor(host, keyProvider, recordProvider, networkClientOptions) {
2010
- this.host = host ? host : "https://api.explorer.provable.com/v1";
2011
- this.networkClient = new AleoNetworkClient(this.host, networkClientOptions);
2012
- this.keyProvider = keyProvider ? keyProvider : new AleoKeyProvider();
2013
- this.recordProvider = recordProvider;
2014
- }
2015
- /**
2016
- * Check if the fee is sufficient to pay for the transaction
2017
- */
2018
- async checkFee(address, feeAmount) {
2019
- const balance = BigInt(await this.networkClient.getPublicBalance(address));
2020
- if (feeAmount > balance) {
2021
- throw Error(`The desired execution requires a fee of ${feeAmount} microcredits, but the account paying the fee has ${balance} microcredits available.`);
2022
- }
2023
- }
2024
- /**
2025
- * Set the account to use for transaction submission to the Aleo network
2026
- *
2027
- * @param {Account} account Account to use for transaction submission
2028
- */
2029
- setAccount(account) {
2030
- this.account = account;
2031
- }
2032
- /**
2033
- * Set the key provider that provides the proving and verifying keys for programs
2034
- *
2035
- * @param {FunctionKeyProvider} keyProvider
2036
- */
2037
- setKeyProvider(keyProvider) {
2038
- this.keyProvider = keyProvider;
2039
- }
2040
- /**
2041
- * Set the host peer to use for transaction submission to the Aleo network
2042
- *
2043
- * @param host {string} Peer url to use for transaction submission
2044
- */
2045
- setHost(host) {
2046
- this.host = host;
2047
- this.networkClient.setHost(host);
2048
- }
2049
- /**
2050
- * Set the record provider that provides records for transactions
2051
- *
2052
- * @param {RecordProvider} recordProvider
2053
- */
2054
- setRecordProvider(recordProvider) {
2055
- this.recordProvider = recordProvider;
2056
- }
2057
- /**
2058
- * Set a header in the `AleoNetworkClient`s header map
2059
- *
2060
- * @param {string} headerName The name of the header to set
2061
- * @param {string} value The header value
2062
- *
2063
- * @example
2064
- * import { ProgramManager } from "@provablehq/sdk/mainnet.js";
2065
- *
2066
- * // Create a ProgramManager
2067
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1");
2068
- *
2069
- * // Set the value of the `Accept-Language` header to `en-US`
2070
- * programManager.setHeader('Accept-Language', 'en-US');
2071
- */
2072
- setHeader(headerName, value) {
2073
- this.networkClient.headers[headerName] = value;
2074
- }
2075
- /**
2076
- * Remove a header from the `AleoNetworkClient`s header map
2077
- *
2078
- * @param {string} headerName The name of the header to be removed
2079
- *
2080
- * @example
2081
- * import { ProgramManager } from "@provablehq/sdk/mainnet.js";
2082
- *
2083
- * // Create a ProgramManager
2084
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1");
2085
- *
2086
- * // Remove the default `X-Aleo-SDK-Version` header
2087
- * programManager.removeHeader('X-Aleo-SDK-Version');
2088
- */
2089
- removeHeader(headerName) {
2090
- delete this.networkClient.headers[headerName];
2091
- }
2092
- /**
2093
- * Builds a deployment transaction for submission to the Aleo network.
2094
- *
2095
- * @param {string} program Program source code
2096
- * @param {number} priorityFee The optional priority fee to be paid for that transaction.
2097
- * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
2098
- * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for searching for a record to use pay the deployment fee
2099
- * @param {string | RecordPlaintext | undefined} feeRecord Optional Fee record to use for the transaction
2100
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transaction
2101
- * @returns {string} The transaction id of the deployed program or a failure message from the network
2102
- *
2103
- * @example
2104
- * /// Import the mainnet version of the sdk.
2105
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2106
- *
2107
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2108
- * const keyProvider = new AleoKeyProvider();
2109
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2110
- * keyProvider.useCache = true;
2111
- *
2112
- * // Initialize a program manager with the key provider to automatically fetch keys for deployments
2113
- * const program = "program hello_hello.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n";
2114
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2115
- * programManager.setAccount(Account);
2116
- *
2117
- * // Define a fee in credits
2118
- * const priorityFee = 0.0;
2119
- *
2120
- * // Create the deployment transaction.
2121
- * const tx = await programManager.buildDeploymentTransaction(program, fee, false);
2122
- * await programManager.networkClient.submitTransaction(tx);
2123
- *
2124
- * // Verify the transaction was successful
2125
- * setTimeout(async () => {
2126
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
2127
- * assert(transaction.id() === tx.id());
2128
- * }, 20000);
2129
- */
2130
- async buildDeploymentTransaction(program, priorityFee, privateFee, recordSearchParams, feeRecord, privateKey) {
2131
- // Ensure the program is valid.
2132
- let programObject;
2133
- try {
2134
- programObject = Program.fromString(program);
2135
- }
2136
- catch (e) {
2137
- logAndThrow(`Error parsing program: '${e.message}'. Please ensure the program is valid.`);
2138
- }
2139
- // Ensure the program is valid and does not exist on the network
2140
- try {
2141
- let programSource;
2142
- try {
2143
- programSource = await this.networkClient.getProgram(programObject.id());
2144
- }
2145
- catch (e) {
2146
- // Program does not exist on the network, deployment can proceed
2147
- console.log(`Program ${programObject.id()} does not exist on the network, deploying...`);
2148
- }
2149
- if (typeof programSource === "string") {
2150
- throw Error(`Program ${programObject.id()} already exists on the network, please rename your program`);
2151
- }
2152
- }
2153
- catch (e) {
2154
- logAndThrow(`Error validating program: ${e.message}`);
2155
- }
2156
- // Get the private key from the account if it is not provided in the parameters
2157
- let deploymentPrivateKey = privateKey;
2158
- if (typeof privateKey === "undefined" &&
2159
- typeof this.account !== "undefined") {
2160
- deploymentPrivateKey = this.account.privateKey();
2161
- }
2162
- if (typeof deploymentPrivateKey === "undefined") {
2163
- throw "No private key provided and no private key set in the ProgramManager";
2164
- }
2165
- // Get the fee record from the account if it is not provided in the parameters
2166
- try {
2167
- feeRecord = privateFee
2168
- ? (await this.getCreditsRecord(priorityFee, [], feeRecord, recordSearchParams))
2169
- : undefined;
2170
- }
2171
- catch (e) {
2172
- logAndThrow(`Error finding fee record. Record finder response: '${e.message}'. Please ensure you're connected to a valid Aleo network and a record with enough balance exists.`);
2173
- }
2174
- // Get the proving and verifying keys from the key provider
2175
- let feeKeys;
2176
- try {
2177
- feeKeys = privateFee
2178
- ? await this.keyProvider.feePrivateKeys()
2179
- : await this.keyProvider.feePublicKeys();
2180
- }
2181
- catch (e) {
2182
- logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
2183
- }
2184
- const [feeProvingKey, feeVerifyingKey] = feeKeys;
2185
- // Resolve the program imports if they exist
2186
- let imports;
2187
- try {
2188
- imports = await this.networkClient.getProgramImports(program);
2189
- }
2190
- catch (e) {
2191
- logAndThrow(`Error finding program imports. Network response: '${e.message}'. Please ensure you're connected to a valid Aleo network and the program is deployed to the network.`);
2192
- }
2193
- // Build a deployment transaction
2194
- return await ProgramManager$1.buildDeploymentTransaction(deploymentPrivateKey, program, priorityFee, feeRecord, this.host, imports, feeProvingKey, feeVerifyingKey);
2195
- }
2196
- /**
2197
- * Deploy an Aleo program to the Aleo network
2198
- *
2199
- * @param {string} program Program source code
2200
- * @param {number} priorityFee The optional fee to be paid for the transaction
2201
- * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
2202
- * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for searching for a record to used pay the deployment fee
2203
- * @param {string | RecordPlaintext | undefined} feeRecord Optional Fee record to use for the transaction
2204
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transaction
2205
- * @returns {string} The transaction id of the deployed program or a failure message from the network
2206
- *
2207
- * @example
2208
- * /// Import the mainnet version of the sdk.
2209
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2210
- *
2211
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2212
- * const keyProvider = new AleoKeyProvider();
2213
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2214
- * keyProvider.useCache = true;
2215
- *
2216
- * // Initialize a program manager with the key provider to automatically fetch keys for deployments
2217
- * const program = "program hello_hello.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n";
2218
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2219
- *
2220
- * // Define a fee in credits
2221
- * const priorityFee = 0.0;
2222
- *
2223
- * // Deploy the program
2224
- * const tx_id = await programManager.deploy(program, fee, false);
2225
- *
2226
- * // Verify the transaction was successful
2227
- * setTimeout(async () => {
2228
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2229
- * assert(transaction.id() === tx_id);
2230
- * }, 20000);
2231
- */
2232
- async deploy(program, priorityFee, privateFee, recordSearchParams, feeRecord, privateKey) {
2233
- const tx = (await this.buildDeploymentTransaction(program, priorityFee, privateFee, recordSearchParams, feeRecord, privateKey));
2234
- let feeAddress;
2235
- if (typeof privateKey !== "undefined") {
2236
- feeAddress = Address.from_private_key(privateKey);
2237
- }
2238
- else if (this.account !== undefined) {
2239
- feeAddress = this.account?.address();
2240
- }
2241
- else {
2242
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
2243
- }
2244
- // Check if the account has sufficient credits to pay for the transaction
2245
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
2246
- return await this.networkClient.submitTransaction(tx);
2247
- }
2248
- /**
2249
- * Builds an execution transaction for submission to the Aleo network.
2250
- *
2251
- * @param {ExecuteOptions} options - The options for the execution transaction.
2252
- * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error.
2253
- *
2254
- * @example
2255
- * /// Import the mainnet version of the sdk.
2256
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2257
- *
2258
- * // Create a new NetworkClient, KeyProvider, and RecordProvider using official Aleo record, key, and network providers
2259
- * const keyProvider = new AleoKeyProvider();
2260
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2261
- * keyProvider.useCache = true;
2262
- *
2263
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2264
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2265
- *
2266
- * // Build and execute the transaction
2267
- * const tx = await programManager.buildExecutionTransaction({
2268
- * programName: "hello_hello.aleo",
2269
- * functionName: "hello_hello",
2270
- * priorityFee: 0.0,
2271
- * privateFee: false,
2272
- * inputs: ["5u32", "5u32"],
2273
- * keySearchParams: { "cacheKey": "hello_hello:hello" }
2274
- * });
2275
- *
2276
- * // Submit the transaction to the network
2277
- * await programManager.networkClient.submitTransaction(tx.toString());
2278
- *
2279
- * // Verify the transaction was successful
2280
- * setTimeout(async () => {
2281
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
2282
- * assert(transaction.id() === tx.id());
2283
- * }, 10000);
2284
- */
2285
- async buildExecutionTransaction(options) {
2286
- // Destructure the options object to access the parameters
2287
- const { programName, functionName, priorityFee, privateFee, inputs, recordSearchParams, keySearchParams, privateKey, offlineQuery, } = options;
2288
- let feeRecord = options.feeRecord;
2289
- let provingKey = options.provingKey;
2290
- let verifyingKey = options.verifyingKey;
2291
- let program = options.program;
2292
- let imports = options.imports;
2293
- // Ensure the function exists on the network
2294
- if (program === undefined) {
2295
- try {
2296
- program = (await this.networkClient.getProgram(programName));
2297
- }
2298
- catch (e) {
2299
- logAndThrow(`Error finding ${programName}. Network response: '${e.message}'. Please ensure you're connected to a valid Aleo network the program is deployed to the network.`);
2300
- }
2301
- }
2302
- else if (program instanceof Program) {
2303
- program = program.toString();
2304
- }
2305
- // Get the private key from the account if it is not provided in the parameters
2306
- let executionPrivateKey = privateKey;
2307
- if (typeof privateKey === "undefined" &&
2308
- typeof this.account !== "undefined") {
2309
- executionPrivateKey = this.account.privateKey();
2310
- }
2311
- if (typeof executionPrivateKey === "undefined") {
2312
- throw "No private key provided and no private key set in the ProgramManager";
2313
- }
2314
- // Get the fee record from the account if it is not provided in the parameters
2315
- try {
2316
- feeRecord = privateFee
2317
- ? (await this.getCreditsRecord(priorityFee, [], feeRecord, recordSearchParams))
2318
- : undefined;
2319
- }
2320
- catch (e) {
2321
- logAndThrow(`Error finding fee record. Record finder response: '${e.message}'. Please ensure you're connected to a valid Aleo network and a record with enough balance exists.`);
2322
- }
2323
- // Get the fee proving and verifying keys from the key provider
2324
- let feeKeys;
2325
- try {
2326
- feeKeys = privateFee
2327
- ? await this.keyProvider.feePrivateKeys()
2328
- : await this.keyProvider.feePublicKeys();
2329
- }
2330
- catch (e) {
2331
- logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
2332
- }
2333
- const [feeProvingKey, feeVerifyingKey] = feeKeys;
2334
- // If the function proving and verifying keys are not provided, attempt to find them using the key provider
2335
- if (!provingKey || !verifyingKey) {
2336
- try {
2337
- [provingKey, verifyingKey] = (await this.keyProvider.functionKeys(keySearchParams));
2338
- }
2339
- catch (e) {
2340
- console.log(`Function keys not found. Key finder response: '${e}'. The function keys will be synthesized`);
2341
- }
2342
- }
2343
- // Resolve the program imports if they exist
2344
- const numberOfImports = Program.fromString(program).getImports().length;
2345
- if (numberOfImports > 0 && !imports) {
2346
- try {
2347
- imports = (await this.networkClient.getProgramImports(programName));
2348
- }
2349
- catch (e) {
2350
- logAndThrow(`Error finding program imports. Network response: '${e.message}'. Please ensure you're connected to a valid Aleo network and the program is deployed to the network.`);
2351
- }
2352
- }
2353
- // Build an execution transaction
2354
- return await ProgramManager$1.buildExecutionTransaction(executionPrivateKey, program, functionName, inputs, priorityFee, feeRecord, this.host, imports, provingKey, verifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery);
2355
- }
2356
- /**
2357
- * Builds an execution transaction for submission to the Aleo network.
2358
- *
2359
- * @param {ExecuteOptions} options - The options for the execution transaction.
2360
- * @returns {Promise<string>} - The transaction id
2361
- *
2362
- * @example
2363
- * /// Import the mainnet version of the sdk.
2364
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2365
- *
2366
- * // Create a new NetworkClient, KeyProvider, and RecordProvider using official Aleo record, key, and network providers
2367
- * const keyProvider = new AleoKeyProvider();
2368
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2369
- * keyProvider.useCache = true;
2370
- *
2371
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2372
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2373
- *
2374
- * // Build and execute the transaction
2375
- * const tx_id = await programManager.execute({
2376
- * programName: "hello_hello.aleo",
2377
- * functionName: "hello_hello",
2378
- * priorityFee: 0.0,
2379
- * privateFee: false,
2380
- * inputs: ["5u32", "5u32"],
2381
- * keySearchParams: { "cacheKey": "hello_hello:hello" }
2382
- * });
2383
- *
2384
- * // Verify the transaction was successful
2385
- * setTimeout(async () => {
2386
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2387
- * assert(transaction.id() === tx_id);
2388
- * }, 10000);
2389
- */
2390
- async execute(options) {
2391
- const tx = await this.buildExecutionTransaction(options);
2392
- let feeAddress;
2393
- if (typeof options.privateKey !== "undefined") {
2394
- feeAddress = Address.from_private_key(options.privateKey);
2395
- }
2396
- else if (this.account !== undefined) {
2397
- feeAddress = this.account?.address();
2398
- }
2399
- else {
2400
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
2401
- }
2402
- // Check if the account has sufficient credits to pay for the transaction
2403
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
2404
- return await this.networkClient.submitTransaction(tx);
2405
- }
2406
- /**
2407
- * Run an Aleo program in offline mode
2408
- *
2409
- * @param {string} program Program source code containing the function to be executed
2410
- * @param {string} function_name Function name to execute
2411
- * @param {string[]} inputs Inputs to the function
2412
- * @param {number} proveExecution Whether to prove the execution of the function and return an execution transcript that contains the proof.
2413
- * @param {string[] | undefined} imports Optional imports to the program
2414
- * @param {KeySearchParams | undefined} keySearchParams Optional parameters for finding the matching proving & verifying keys for the function
2415
- * @param {ProvingKey | undefined} provingKey Optional proving key to use for the transaction
2416
- * @param {VerifyingKey | undefined} verifyingKey Optional verifying key to use for the transaction
2417
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transaction
2418
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2419
- * @returns {Promise<ExecutionResponse>} The execution response containing the outputs of the function and the proof if the program is proved.
2420
- *
2421
- * @example
2422
- * /// Import the mainnet version of the sdk used to build executions.
2423
- * import { Account, ProgramManager } from "@provablehq/sdk/mainnet.js";
2424
- *
2425
- * /// Create the source for the "helloworld" program
2426
- * const program = "program helloworld.aleo;\n\nfunction hello:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n";
2427
- * const programManager = new ProgramManager(undefined, undefined, undefined);
2428
- *
2429
- * /// Create a temporary account for the execution of the program
2430
- * const account = new Account();
2431
- * programManager.setAccount(account);
2432
- *
2433
- * /// Get the response and ensure that the program executed correctly
2434
- * const executionResponse = await programManager.run(program, "hello", ["5u32", "5u32"]);
2435
- * const result = executionResponse.getOutputs();
2436
- * assert(result === ["10u32"]);
2437
- */
2438
- async run(program, function_name, inputs, proveExecution, imports, keySearchParams, provingKey, verifyingKey, privateKey, offlineQuery) {
2439
- // Get the private key from the account if it is not provided in the parameters
2440
- let executionPrivateKey = privateKey;
2441
- if (typeof privateKey === "undefined" &&
2442
- typeof this.account !== "undefined") {
2443
- executionPrivateKey = this.account.privateKey();
2444
- }
2445
- if (typeof executionPrivateKey === "undefined") {
2446
- throw "No private key provided and no private key set in the ProgramManager";
2447
- }
2448
- // If the function proving and verifying keys are not provided, attempt to find them using the key provider
2449
- if (!provingKey || !verifyingKey) {
2450
- try {
2451
- [provingKey, verifyingKey] = (await this.keyProvider.functionKeys(keySearchParams));
2452
- }
2453
- catch (e) {
2454
- console.log(`Function keys not found. Key finder response: '${e}'. The function keys will be synthesized`);
2455
- }
2456
- }
2457
- // Run the program offline and return the result
2458
- console.log("Running program offline");
2459
- console.log("Proving key: ", provingKey);
2460
- console.log("Verifying key: ", verifyingKey);
2461
- return ProgramManager$1.executeFunctionOffline(executionPrivateKey, program, function_name, inputs, proveExecution, false, imports, provingKey, verifyingKey, this.host, offlineQuery);
2462
- }
2463
- /**
2464
- * Join two credits records into a single credits record
2465
- *
2466
- * @param {RecordPlaintext | string} recordOne First credits record to join
2467
- * @param {RecordPlaintext | string} recordTwo Second credits record to join
2468
- * @param {number} priorityFee The optional priority fee to be paid for the transaction
2469
- * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
2470
- * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the fee record to use to pay the fee for the join transaction
2471
- * @param {RecordPlaintext | string | undefined} feeRecord Fee record to use for the join transaction
2472
- * @param {PrivateKey | undefined} privateKey Private key to use for the join transaction
2473
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2474
- * @returns {Promise<string>} The transaction id
2475
- *
2476
- * @example
2477
- * /// Import the mainnet version of the sdk.
2478
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2479
- *
2480
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2481
- * const keyProvider = new AleoKeyProvider();
2482
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2483
- * keyProvider.useCache = true;
2484
- *
2485
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2486
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2487
- * const record_1 = "{ owner: aleo184vuwr5u7u0ha5f5k44067dd2uaqewxx6pe5ltha5pv99wvhfqxqv339h4.private, microcredits: 45000000u64.private, _nonce: 4106205762862305308495708971985748592380064201230396559307556388725936304984group.public}"
2488
- * const record_2 = "{ owner: aleo184vuwr5u7u0ha5f5k44067dd2uaqewxx6pe5ltha5pv99wvhfqxqv339h4.private, microcredits: 45000000u64.private, _nonce: 1540945439182663264862696551825005342995406165131907382295858612069623286213group.public}"
2489
- * const tx_id = await programManager.join(record_1, record_2, 0.05, false);
2490
- *
2491
- * // Verify the transaction was successful
2492
- * setTimeout(async () => {
2493
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2494
- * assert(transaction.id() === tx_id);
2495
- * }, 10000);
2496
- */
2497
- async join(recordOne, recordTwo, priorityFee, privateFee, recordSearchParams, feeRecord, privateKey, offlineQuery) {
2498
- // Get the private key from the account if it is not provided in the parameters and assign the fee address
2499
- let executionPrivateKey = privateKey;
2500
- let feeAddress;
2501
- if (typeof privateKey === "undefined" &&
2502
- typeof this.account !== "undefined") {
2503
- executionPrivateKey = this.account.privateKey();
2504
- feeAddress = this.account?.address();
2505
- }
2506
- else if (typeof executionPrivateKey === "undefined") {
2507
- throw "No private key provided and no private key set in the ProgramManager";
2508
- }
2509
- else {
2510
- feeAddress = Address.from_private_key(executionPrivateKey);
2511
- }
2512
- // Get the proving and verifying keys from the key provider
2513
- let feeKeys;
2514
- let joinKeys;
2515
- try {
2516
- feeKeys = privateFee
2517
- ? await this.keyProvider.feePrivateKeys()
2518
- : await this.keyProvider.feePublicKeys();
2519
- joinKeys = await this.keyProvider.joinKeys();
2520
- }
2521
- catch (e) {
2522
- logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
2523
- }
2524
- const [feeProvingKey, feeVerifyingKey] = feeKeys;
2525
- const [joinProvingKey, joinVerifyingKey] = joinKeys;
2526
- // Get the fee record from the account if it is not provided in the parameters
2527
- try {
2528
- feeRecord = privateFee
2529
- ? (await this.getCreditsRecord(priorityFee, [], feeRecord, recordSearchParams))
2530
- : undefined;
2531
- }
2532
- catch (e) {
2533
- logAndThrow(`Error finding fee record. Record finder response: '${e.message}'. Please ensure you're connected to a valid Aleo network and a record with enough balance exists.`);
2534
- }
2535
- // Validate the records provided are valid plaintext records
2536
- try {
2537
- recordOne =
2538
- recordOne instanceof RecordPlaintext
2539
- ? recordOne
2540
- : RecordPlaintext.fromString(recordOne);
2541
- recordTwo =
2542
- recordTwo instanceof RecordPlaintext
2543
- ? recordTwo
2544
- : RecordPlaintext.fromString(recordTwo);
2545
- }
2546
- catch (e) {
2547
- logAndThrow("Records provided are not valid. Please ensure they are valid plaintext records.");
2548
- }
2549
- // Build an execution transaction and submit it to the network
2550
- const tx = await ProgramManager$1.buildJoinTransaction(executionPrivateKey, recordOne, recordTwo, priorityFee, feeRecord, this.host, joinProvingKey, joinVerifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery);
2551
- // Check if the account has sufficient credits to pay for the transaction
2552
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
2553
- return await this.networkClient.submitTransaction(tx);
2554
- }
2555
- /**
2556
- * Split credits into two new credits records
2557
- *
2558
- * @param {number} splitAmount Amount in microcredits to split from the original credits record
2559
- * @param {RecordPlaintext | string} amountRecord Amount record to use for the split transaction
2560
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the split transaction
2561
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2562
- * @returns {Promise<string>} The transaction id
2563
- *
2564
- * @example
2565
- * /// Import the mainnet version of the sdk.
2566
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2567
- *
2568
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2569
- * const keyProvider = new AleoKeyProvider();
2570
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2571
- * keyProvider.useCache = true;
2572
- *
2573
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2574
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2575
- * const record = "{ owner: aleo184vuwr5u7u0ha5f5k44067dd2uaqewxx6pe5ltha5pv99wvhfqxqv339h4.private, microcredits: 45000000u64.private, _nonce: 4106205762862305308495708971985748592380064201230396559307556388725936304984group.public}"
2576
- * const tx_id = await programManager.split(25000000, record);
2577
- *
2578
- * // Verify the transaction was successful
2579
- * setTimeout(async () => {
2580
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2581
- * assert(transaction.id() === tx_id);
2582
- * }, 10000);
2583
- */
2584
- async split(splitAmount, amountRecord, privateKey, offlineQuery) {
2585
- // Get the private key from the account if it is not provided in the parameters
2586
- let executionPrivateKey = privateKey;
2587
- if (typeof privateKey === "undefined" &&
2588
- typeof this.account !== "undefined") {
2589
- executionPrivateKey = this.account.privateKey();
2590
- }
2591
- if (typeof executionPrivateKey === "undefined") {
2592
- throw "No private key provided and no private key set in the ProgramManager";
2593
- }
2594
- // Get the split keys from the key provider
2595
- let splitKeys;
2596
- try {
2597
- splitKeys = await this.keyProvider.splitKeys();
2598
- }
2599
- catch (e) {
2600
- logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
2601
- }
2602
- const [splitProvingKey, splitVerifyingKey] = splitKeys;
2603
- // Validate the record to be split
2604
- try {
2605
- amountRecord =
2606
- amountRecord instanceof RecordPlaintext
2607
- ? amountRecord
2608
- : RecordPlaintext.fromString(amountRecord);
2609
- }
2610
- catch (e) {
2611
- logAndThrow("Record provided is not valid. Please ensure it is a valid plaintext record.");
2612
- }
2613
- // Build an execution transaction and submit it to the network
2614
- const tx = await ProgramManager$1.buildSplitTransaction(executionPrivateKey, splitAmount, amountRecord, this.host, splitProvingKey, splitVerifyingKey, offlineQuery);
2615
- return await this.networkClient.submitTransaction(tx);
2616
- }
2617
- /**
2618
- * Pre-synthesize proving and verifying keys for a program
2619
- *
2620
- * @param program {string} The program source code to synthesize keys for
2621
- * @param function_id {string} The function id to synthesize keys for
2622
- * @param inputs {Array<string>} Sample inputs to the function
2623
- * @param privateKey {PrivateKey | undefined} Optional private key to use for the key synthesis
2624
- *
2625
- * @returns {Promise<FunctionKeyPair>}
2626
- */
2627
- async synthesizeKeys(program, function_id, inputs, privateKey) {
2628
- // Resolve the program imports if they exist
2629
- let imports;
2630
- let executionPrivateKey = privateKey;
2631
- if (typeof executionPrivateKey === "undefined") {
2632
- if (typeof this.account !== "undefined") {
2633
- executionPrivateKey = this.account.privateKey();
2634
- }
2635
- else {
2636
- executionPrivateKey = new PrivateKey();
2637
- }
2638
- }
2639
- // Attempt to run an offline execution of the program and extract the proving and verifying keys
2640
- try {
2641
- imports = await this.networkClient.getProgramImports(program);
2642
- const keyPair = await ProgramManager$1.synthesizeKeyPair(executionPrivateKey, program, function_id, inputs, imports);
2643
- return [
2644
- keyPair.provingKey(),
2645
- keyPair.verifyingKey(),
2646
- ];
2647
- }
2648
- catch (e) {
2649
- logAndThrow(`Could not synthesize keys - error ${e.message}. Please ensure the program is valid and the inputs are correct.`);
2650
- }
2651
- }
2652
- /**
2653
- * Build a transaction to transfer credits to another account for later submission to the Aleo network
2654
- *
2655
- * @param {number} amount The amount of credits to transfer
2656
- * @param {string} recipient The recipient of the transfer
2657
- * @param {string} transferType The type of transfer to perform - options: 'private', 'privateToPublic', 'public', 'publicToPrivate'
2658
- * @param {number} priorityFee The optional priority fee to be paid for the transaction
2659
- * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
2660
- * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the amount and fee records for the transfer transaction
2661
- * @param {RecordPlaintext | string} amountRecord Optional amount record to use for the transfer
2662
- * @param {RecordPlaintext | string} feeRecord Optional fee record to use for the transfer
2663
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
2664
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2665
- * @returns {Promise<Transaction>} The transaction object
2666
- *
2667
- * @example
2668
- * /// Import the mainnet version of the sdk.
2669
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2670
- *
2671
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2672
- * const keyProvider = new AleoKeyProvider();
2673
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2674
- * keyProvider.useCache = true;
2675
- *
2676
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2677
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2678
- * const tx = await programManager.buildTransferTransaction(1, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "public", 0.2, false);
2679
- * await programManager.networkClient.submitTransaction(tx.toString());
2680
- *
2681
- * // Verify the transaction was successful
2682
- * setTimeout(async () => {
2683
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
2684
- * assert(transaction.id() === tx.id());
2685
- * }, 10000);
2686
- */
2687
- async buildTransferTransaction(amount, recipient, transferType, priorityFee, privateFee, recordSearchParams, amountRecord, feeRecord, privateKey, offlineQuery) {
2688
- // Validate the transfer type
2689
- transferType = validateTransferType(transferType);
2690
- // Get the private key from the account if it is not provided in the parameters
2691
- let executionPrivateKey = privateKey;
2692
- if (typeof executionPrivateKey === "undefined" &&
2693
- typeof this.account !== "undefined") {
2694
- executionPrivateKey = this.account.privateKey();
2695
- }
2696
- if (typeof executionPrivateKey === "undefined") {
2697
- throw "No private key provided and no private key set in the ProgramManager";
2698
- }
2699
- // Get the proving and verifying keys from the key provider
2700
- let feeKeys;
2701
- let transferKeys;
2702
- try {
2703
- feeKeys = privateFee
2704
- ? await this.keyProvider.feePrivateKeys()
2705
- : await this.keyProvider.feePublicKeys();
2706
- transferKeys = (await this.keyProvider.transferKeys(transferType));
2707
- }
2708
- catch (e) {
2709
- logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
2710
- }
2711
- const [feeProvingKey, feeVerifyingKey] = feeKeys;
2712
- const [transferProvingKey, transferVerifyingKey] = transferKeys;
2713
- // Get the amount and fee record from the account if it is not provided in the parameters
2714
- try {
2715
- // Track the nonces of the records found so no duplicate records are used
2716
- const nonces = [];
2717
- if (requiresAmountRecord(transferType)) {
2718
- // If the transfer type is private and requires an amount record, get it from the record provider
2719
- amountRecord = (await this.getCreditsRecord(priorityFee, [], amountRecord, recordSearchParams));
2720
- nonces.push(amountRecord.nonce());
2721
- }
2722
- else {
2723
- amountRecord = undefined;
2724
- }
2725
- feeRecord = privateFee
2726
- ? (await this.getCreditsRecord(priorityFee, nonces, feeRecord, recordSearchParams))
2727
- : undefined;
2728
- }
2729
- catch (e) {
2730
- logAndThrow(`Error finding fee record. Record finder response: '${e.message}'. Please ensure you're connected to a valid Aleo network and a record with enough balance exists.`);
2731
- }
2732
- // Build an execution transaction
2733
- return await ProgramManager$1.buildTransferTransaction(executionPrivateKey, amount, recipient, transferType, amountRecord, priorityFee, feeRecord, this.host, transferProvingKey, transferVerifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery);
2734
- }
2735
- /**
2736
- * Build a transfer_public transaction to transfer credits to another account for later submission to the Aleo network
2737
- *
2738
- * @param {number} amount The amount of credits to transfer
2739
- * @param {string} recipient The recipient of the transfer
2740
- * @param {number} priorityFee The optional priority fee to be paid for the transfer
2741
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
2742
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2743
- * @returns {Promise<Transaction>} The transaction object
2744
- *
2745
- * @example
2746
- * /// Import the mainnet version of the sdk.
2747
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2748
- *
2749
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2750
- * const keyProvider = new AleoKeyProvider();
2751
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2752
- * keyProvider.useCache = true;
2753
- *
2754
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2755
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2756
- * const tx = await programManager.buildTransferPublicTransaction(1, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", 0.2);
2757
- * await programManager.networkClient.submitTransaction(tx.toString());
2758
- *
2759
- * // Verify the transaction was successful
2760
- * setTimeout(async () => {
2761
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
2762
- * assert(transaction.id() === tx.id());
2763
- * }, 10000);
2764
- */
2765
- async buildTransferPublicTransaction(amount, recipient, priorityFee, privateKey, offlineQuery) {
2766
- return this.buildTransferTransaction(amount, recipient, "public", priorityFee, false, undefined, undefined, undefined, privateKey, offlineQuery);
2767
- }
2768
- /**
2769
- * Build a transfer_public_as_signer transaction to transfer credits to another account for later submission to the Aleo network
2770
- *
2771
- * @param {number} amount The amount of credits to transfer
2772
- * @param {string} recipient The recipient of the transfer
2773
- * @param {number} priorityFee The optional priority fee to be paid for the transfer
2774
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
2775
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2776
- * @returns {Promise<Transaction>} The transaction object
2777
- *
2778
- * @example
2779
- * /// Import the mainnet version of the sdk.
2780
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2781
- *
2782
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2783
- * const keyProvider = new AleoKeyProvider();
2784
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2785
- * keyProvider.useCache = true;
2786
- *
2787
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2788
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2789
- * const tx = await programManager.buildTransferPublicAsSignerTransaction(1, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", 0.2);
2790
- * await programManager.networkClient.submitTransaction(tx.toString());
2791
- *
2792
- * // Verify the transaction was successful
2793
- * setTimeout(async () => {
2794
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
2795
- * assert(transaction.id() === tx.id());
2796
- * }, 10000);
2797
- */
2798
- async buildTransferPublicAsSignerTransaction(amount, recipient, priorityFee, privateKey, offlineQuery) {
2799
- return this.buildTransferTransaction(amount, recipient, "public", priorityFee, false, undefined, undefined, undefined, privateKey, offlineQuery);
2800
- }
2801
- /**
2802
- * Transfer credits to another account
2803
- *
2804
- * @param {number} amount The amount of credits to transfer
2805
- * @param {string} recipient The recipient of the transfer
2806
- * @param {string} transferType The type of transfer to perform - options: 'private', 'privateToPublic', 'public', 'publicToPrivate'
2807
- * @param {number} priorityFee The optional priority fee to be paid for the transfer
2808
- * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
2809
- * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the amount and fee records for the transfer transaction
2810
- * @param {RecordPlaintext | string} amountRecord Optional amount record to use for the transfer
2811
- * @param {RecordPlaintext | string} feeRecord Optional fee record to use for the transfer
2812
- * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
2813
- * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
2814
- * @returns {Promise<string>} The transaction id
2815
- *
2816
- * @example
2817
- * /// Import the mainnet version of the sdk.
2818
- * import { AleoKeyProvider, ProgramManager, NetworkRecordProvider } from "@provablehq/sdk/mainnet.js";
2819
- *
2820
- * // Create a new NetworkClient, KeyProvider, and RecordProvider
2821
- * const keyProvider = new AleoKeyProvider();
2822
- * const recordProvider = new NetworkRecordProvider(account, networkClient);
2823
- * keyProvider.useCache = true;
2824
- *
2825
- * // Initialize a program manager with the key provider to automatically fetch keys for executions
2826
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
2827
- * const tx_id = await programManager.transfer(1, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "public", 0.2, false);
2828
- *
2829
- * // Verify the transaction was successful
2830
- * setTimeout(async () => {
2831
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2832
- * assert(transaction.id() === tx_id);
2833
- * }, 10000);
2834
- */
2835
- async transfer(amount, recipient, transferType, priorityFee, privateFee, recordSearchParams, amountRecord, feeRecord, privateKey, offlineQuery) {
2836
- const tx = (await this.buildTransferTransaction(amount, recipient, transferType, priorityFee, privateFee, recordSearchParams, amountRecord, feeRecord, privateKey, offlineQuery));
2837
- let feeAddress;
2838
- if (typeof privateKey !== "undefined") {
2839
- feeAddress = Address.from_private_key(privateKey);
2840
- }
2841
- else if (this.account !== undefined) {
2842
- feeAddress = this.account?.address();
2843
- }
2844
- else {
2845
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
2846
- }
2847
- // Check if the account has sufficient credits to pay for the transaction
2848
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
2849
- return await this.networkClient.submitTransaction(tx);
2850
- }
2851
- /**
2852
- * Build transaction to bond credits to a validator for later submission to the Aleo Network
2853
- *
2854
- * @param {string} validator_address Address of the validator to bond to, if this address is the same as the staker (i.e. the executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently requires a minimum of 10,000,000 credits to bond (subject to change). If the address is specified is an existing validator and is different from the address of the executor of this function, it will bond the credits to that validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
2855
- * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
2856
- * @param {number} amount The amount of credits to bond
2857
- * @param {Partial<ExecuteOptions>} options - Override default execution options.
2858
- * @returns {Promise<Transaction>} The transaction object
2859
- *
2860
- * @example
2861
- * // Import the mainnet version of the sdk.
2862
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
2863
- *
2864
- * // Create a keyProvider to handle key management
2865
- * const keyProvider = new AleoKeyProvider();
2866
- * keyProvider.useCache = true;
2867
- *
2868
- * // Create a new ProgramManager with the key that will be used to bond credits
2869
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
2870
- * programManager.setAccount(new Account("YourPrivateKey"));
2871
- *
2872
- * // Create the bonding transaction object for later submission
2873
- * const tx = await programManager.buildBondPublicTransaction("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
2874
- *
2875
- * // The transaction can be later submitted to the network using the network client.
2876
- * await programManager.networkClient.submitTransaction(tx.toString());
2877
- *
2878
- * // Verify the transaction was successful
2879
- * setTimeout(async () => {
2880
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
2881
- * assert(transaction.id() === tx.id());
2882
- * }, 10000);
2883
- */
2884
- async buildBondPublicTransaction(validator_address, withdrawal_address, amount, options = {}) {
2885
- const scaledAmount = Math.trunc(amount * 1000000);
2886
- const { programName = "credits.aleo", functionName = "bond_public", priorityFee = options.priorityFee || 0, privateFee = false, inputs = [
2887
- validator_address,
2888
- withdrawal_address,
2889
- `${scaledAmount.toString()}u64`,
2890
- ], keySearchParams = new AleoKeyProviderParams({
2891
- proverUri: CREDITS_PROGRAM_KEYS.bond_public.prover,
2892
- verifierUri: CREDITS_PROGRAM_KEYS.bond_public.verifier,
2893
- cacheKey: "credits.aleo/bond_public",
2894
- }), program = this.creditsProgram(), ...additionalOptions } = options;
2895
- const executeOptions = {
2896
- programName,
2897
- functionName,
2898
- priorityFee,
2899
- privateFee,
2900
- inputs,
2901
- keySearchParams,
2902
- ...additionalOptions,
2903
- };
2904
- return await this.buildExecutionTransaction(executeOptions);
2905
- }
2906
- /**
2907
- * Bond credits to validator.
2908
- *
2909
- * @param {string} validator_address Address of the validator to bond to, if this address is the same as the signer (i.e. the executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently requires a minimum of 1,000,000 credits to bond (subject to change). If the address is specified is an existing validator and is different from the address of the executor of this function, it will bond the credits to that validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
2910
- * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
2911
- * @param {number} amount The amount of credits to bond
2912
- * @param {Options} options Options for the execution
2913
- * @returns {Promise<string>} The transaction id
2914
- *
2915
- * @example
2916
- * // Import the mainnet version of the sdk.
2917
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
2918
- *
2919
- * // Create a keyProvider to handle key management
2920
- * const keyProvider = new AleoKeyProvider();
2921
- * keyProvider.useCache = true;
2922
- *
2923
- * // Create a new ProgramManager with the key that will be used to bond credits
2924
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
2925
- *
2926
- * // Create the bonding transaction
2927
- * tx_id = await programManager.bondPublic("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
2928
- *
2929
- * // Verify the transaction was successful
2930
- * setTimeout(async () => {
2931
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2932
- * assert(transaction.id() === tx_id);
2933
- * }, 10000);
2934
- */
2935
- async bondPublic(validator_address, withdrawal_address, amount, options = {}) {
2936
- const tx = (await this.buildBondPublicTransaction(validator_address, withdrawal_address, amount, options));
2937
- let feeAddress;
2938
- if (typeof options.privateKey !== "undefined") {
2939
- feeAddress = Address.from_private_key(options.privateKey);
2940
- }
2941
- else if (this.account !== undefined) {
2942
- feeAddress = this.account?.address();
2943
- }
2944
- else {
2945
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
2946
- }
2947
- // Check if the account has sufficient credits to pay for the transaction
2948
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
2949
- return await this.networkClient.submitTransaction(tx);
2950
- }
2951
- /**
2952
- * Build a bond_validator transaction for later submission to the Aleo Network.
2953
- *
2954
- * @param {string} validator_address Address of the validator to bond to, if this address is the same as the staker (i.e. the executor of this function), it will attempt to bond the credits as a validator. If the address is specified is an existing validator and is different from the address of the executor of this function, it will bond the credits to that validator's staking committee as a delegator.
2955
- * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
2956
- * @param {number} amount The amount of credits to bond. A minimum of 10000 credits is required to bond as a delegator.
2957
- * @param {number} commission The commission rate for the validator (must be between 0 and 100 - an error will be thrown if it is not)
2958
- * @param {Partial<ExecuteOptions>} options - Override default execution options.
2959
- * @returns {Promise<Transaction>} The transaction object
2960
- *
2961
- * @example
2962
- * // Import the mainnet version of the sdk.
2963
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
2964
- *
2965
- * // Create a keyProvider to handle key management
2966
- * const keyProvider = new AleoKeyProvider();
2967
- * keyProvider.useCache = true;
2968
- *
2969
- * // Create a new ProgramManager with the key that will be used to bond credits
2970
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
2971
- * programManager.setAccount(new Account("YourPrivateKey"));
2972
- *
2973
- * // Create the bond validator transaction object for later use.
2974
- * const tx = await programManager.buildBondValidatorTransaction("aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
2975
- *
2976
- * // The transaction can later be submitted to the network using the network client.
2977
- * const tx_id = await programManager.networkClient.submitTransaction(tx.toString());
2978
- *
2979
- * // Verify the transaction was successful
2980
- * setTimeout(async () => {
2981
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
2982
- * assert(transaction.id() === tx_id);
2983
- * }, 10000);
2984
- */
2985
- async buildBondValidatorTransaction(validator_address, withdrawal_address, amount, commission, options = {}) {
2986
- const scaledAmount = Math.trunc(amount * 1000000);
2987
- const adjustedCommission = Math.trunc(commission);
2988
- const { programName = "credits.aleo", functionName = "bond_validator", priorityFee = options.priorityFee || 0, privateFee = false, inputs = [
2989
- validator_address,
2990
- withdrawal_address,
2991
- `${scaledAmount.toString()}u64`,
2992
- `${adjustedCommission.toString()}u8`,
2993
- ], keySearchParams = new AleoKeyProviderParams({
2994
- proverUri: CREDITS_PROGRAM_KEYS.bond_validator.prover,
2995
- verifierUri: CREDITS_PROGRAM_KEYS.bond_validator.verifier,
2996
- cacheKey: "credits.aleo/bond_validator",
2997
- }), program = this.creditsProgram(), ...additionalOptions } = options;
2998
- const executeOptions = {
2999
- programName,
3000
- functionName,
3001
- priorityFee,
3002
- privateFee,
3003
- inputs,
3004
- keySearchParams,
3005
- ...additionalOptions,
3006
- };
3007
- return await this.buildExecutionTransaction(executeOptions);
3008
- }
3009
- /**
3010
- * Build transaction to bond a validator.
3011
- *
3012
- * @param {string} validator_address Address of the validator to bond to, if this address is the same as the staker (i.e. the executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently requires a minimum of 10,000,000 credits to bond (subject to change). If the address is specified is an existing validator and is different from the address of the executor of this function, it will bond the credits to that validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
3013
- * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
3014
- * @param {number} amount The amount of credits to bond
3015
- * @param {number} commission The commission rate for the validator (must be between 0 and 100 - an error will be thrown if it is not)
3016
- * @param {Partial<ExecuteOptions>} options - Override default execution options.
3017
- * @returns {Promise<string>} The transaction id
3018
- *
3019
- * @example
3020
- * // Import the mainnet version of the sdk.
3021
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3022
- *
3023
- * // Create a keyProvider to handle key management
3024
- * const keyProvider = new AleoKeyProvider();
3025
- * keyProvider.useCache = true;
3026
- *
3027
- * // Create a new ProgramManager with the key that will be used to bond credits
3028
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3029
- * programManager.setAccount(new Account("YourPrivateKey"));
3030
- *
3031
- * // Create the bonding transaction
3032
- * const tx_id = await programManager.bondValidator("aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
3033
- *
3034
- * // Verify the transaction was successful
3035
- * setTimeout(async () => {
3036
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
3037
- * assert(transaction.id() === tx_id);
3038
- * }, 10000);
3039
- */
3040
- async bondValidator(validator_address, withdrawal_address, amount, commission, options = {}) {
3041
- const tx = (await this.buildBondValidatorTransaction(validator_address, withdrawal_address, amount, commission, options));
3042
- let feeAddress;
3043
- if (typeof options.privateKey !== "undefined") {
3044
- feeAddress = Address.from_private_key(options.privateKey);
3045
- }
3046
- else if (this.account !== undefined) {
3047
- feeAddress = this.account?.address();
3048
- }
3049
- else {
3050
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
3051
- }
3052
- // Check if the account has sufficient credits to pay for the transaction
3053
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
3054
- return await this.networkClient.submitTransaction(tx);
3055
- }
3056
- /**
3057
- * Build an unbond_public execution transaction to unbond credits from a validator in the Aleo network.
3058
- *
3059
- * @param {string} staker_address - The address of the staker who is unbonding the credits.
3060
- * @param {number} amount - The amount of credits to unbond (scaled by 1,000,000).
3061
- * @param {Partial<ExecuteOptions>} options - Override default execution options.
3062
- * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error message.
3063
- *
3064
- * @example
3065
- * // Import the mainnet version of the sdk.
3066
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3067
- *
3068
- * // Create a keyProvider to handle key management.
3069
- * const keyProvider = new AleoKeyProvider();
3070
- * keyProvider.useCache = true;
3071
- *
3072
- * // Create a new ProgramManager with the key that will be used to unbond credits.
3073
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3074
- * const tx = await programManager.buildUnbondPublicTransaction("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", 2000000);
3075
- *
3076
- * // The transaction can be submitted later to the network using the network client.
3077
- * programManager.networkClient.submitTransaction(tx.toString());
3078
- *
3079
- * // Verify the transaction was successful
3080
- * setTimeout(async () => {
3081
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
3082
- * assert(transaction.id() === tx.id());
3083
- * }, 10000);
3084
- */
3085
- async buildUnbondPublicTransaction(staker_address, amount, options = {}) {
3086
- const scaledAmount = Math.trunc(amount * 1000000);
3087
- const { programName = "credits.aleo", functionName = "unbond_public", priorityFee = options.priorityFee || 0, privateFee = false, inputs = [staker_address, `${scaledAmount.toString()}u64`], keySearchParams = new AleoKeyProviderParams({
3088
- proverUri: CREDITS_PROGRAM_KEYS.unbond_public.prover,
3089
- verifierUri: CREDITS_PROGRAM_KEYS.unbond_public.verifier,
3090
- cacheKey: "credits.aleo/unbond_public",
3091
- }), program = this.creditsProgram(), ...additionalOptions } = options;
3092
- const executeOptions = {
3093
- programName,
3094
- functionName,
3095
- priorityFee,
3096
- privateFee,
3097
- inputs,
3098
- keySearchParams,
3099
- ...additionalOptions,
3100
- };
3101
- return this.buildExecutionTransaction(executeOptions);
3102
- }
3103
- /**
3104
- * Unbond a specified amount of staked credits. If the address of the executor of this function is an existing
3105
- * validator, it will subtract this amount of credits from the validator's staked credits. If there are less than
3106
- * 1,000,000 credits staked pool after the unbond, the validator will be removed from the validator set. If the
3107
- * address of the executor of this function is not a validator and has credits bonded as a delegator, it will
3108
- * subtract this amount of credits from the delegator's staked credits. If there are less than 10 credits bonded
3109
- * after the unbond operation, the delegator will be removed from the validator's staking pool.
3110
- *
3111
- * @param {string} staker_address Address of the staker who is unbonding the credits
3112
- * @param {number} amount Amount of credits to unbond.
3113
- * @param {ExecuteOptions} options Options for the execution
3114
- * @returns {Promise<string>} The transaction id
3115
- *
3116
- * @example
3117
- * // Import the mainnet version of the sdk.
3118
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3119
- *
3120
- * // Create a keyProvider to handle key management
3121
- * const keyProvider = new AleoKeyProvider();
3122
- * keyProvider.useCache = true;
3123
- *
3124
- * // Create a new ProgramManager with the key that will be used to bond credits
3125
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3126
- * programManager.setAccount(new Account("YourPrivateKey"));
3127
- *
3128
- * // Create the unbond_public transaction and send it to the network
3129
- * const tx_id = await programManager.unbondPublic("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", 10);
3130
- *
3131
- * // Verify the transaction was successful
3132
- * setTimeout(async () => {
3133
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
3134
- * assert(transaction.id() === tx_id);
3135
- * }, 10000);
3136
- */
3137
- async unbondPublic(staker_address, amount, options = {}) {
3138
- const tx = (await this.buildUnbondPublicTransaction(staker_address, amount, options));
3139
- let feeAddress;
3140
- if (typeof options.privateKey !== "undefined") {
3141
- feeAddress = Address.from_private_key(options.privateKey);
3142
- }
3143
- else if (this.account !== undefined) {
3144
- feeAddress = this.account?.address();
3145
- }
3146
- else {
3147
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
3148
- }
3149
- // Check if the account has sufficient credits to pay for the transaction
3150
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
3151
- return await this.networkClient.submitTransaction(tx);
3152
- }
3153
- /**
3154
- * Build a transaction to claim unbonded public credits in the Aleo network.
3155
- *
3156
- * @param {string} staker_address - The address of the staker who is claiming the credits.
3157
- * @param {Partial<ExecuteOptions>} options - Override default execution options.
3158
- * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error message.
3159
- *
3160
- * @example
3161
- * // Import the mainnet version of the sdk.
3162
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3163
- *
3164
- * // Create a keyProvider to handle key management
3165
- * const keyProvider = new AleoKeyProvider();
3166
- * keyProvider.useCache = true;
3167
- *
3168
- * // Create a new ProgramManager with the key that will be used to claim unbonded credits.
3169
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3170
- *
3171
- * // Create the claim_unbond_public transaction object for later use.
3172
- * const tx = await programManager.buildClaimUnbondPublicTransaction("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j");
3173
- *
3174
- * // The transaction can be submitted later to the network using the network client.
3175
- * programManager.networkClient.submitTransaction(tx.toString());
3176
- *
3177
- * // Verify the transaction was successful
3178
- * setTimeout(async () => {
3179
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
3180
- * assert(transaction.id() === tx.id());
3181
- * }, 10000);
3182
- */
3183
- async buildClaimUnbondPublicTransaction(staker_address, options = {}) {
3184
- const { programName = "credits.aleo", functionName = "claim_unbond_public", priorityFee = options.priorityFee || 0, privateFee = false, inputs = [staker_address], keySearchParams = new AleoKeyProviderParams({
3185
- proverUri: CREDITS_PROGRAM_KEYS.claim_unbond_public.prover,
3186
- verifierUri: CREDITS_PROGRAM_KEYS.claim_unbond_public.verifier,
3187
- cacheKey: "credits.aleo/claim_unbond_public",
3188
- }), program = this.creditsProgram(), ...additionalOptions } = options;
3189
- const executeOptions = {
3190
- programName,
3191
- functionName,
3192
- priorityFee,
3193
- privateFee,
3194
- inputs,
3195
- keySearchParams,
3196
- ...additionalOptions,
3197
- };
3198
- // Check if the account has sufficient credits to pay for the transaction
3199
- return await this.buildExecutionTransaction(executeOptions);
3200
- }
3201
- /**
3202
- * Claim unbonded credits. If credits have been unbonded by the account executing this function, this method will
3203
- * claim them and add them to the public balance of the account.
3204
- *
3205
- * @param {string} staker_address Address of the staker who is claiming the credits
3206
- * @param {ExecuteOptions} options
3207
- * @returns {Promise<string>} The transaction id
3208
- *
3209
- * @example
3210
- * // Import the mainnet version of the sdk.
3211
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3212
- *
3213
- * // Create a keyProvider to handle key management
3214
- * const keyProvider = new AleoKeyProvider();
3215
- * keyProvider.useCache = true;
3216
- *
3217
- * // Create a new ProgramManager with the key that will be used to bond credits
3218
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3219
- * programManager.setAccount(new Account("YourPrivateKey"));
3220
- *
3221
- * // Create the claim_unbond_public transaction
3222
- * const tx_id = await programManager.claimUnbondPublic("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j");
3223
- *
3224
- * // Verify the transaction was successful
3225
- * setTimeout(async () => {
3226
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
3227
- * assert(transaction.id() === tx_id);
3228
- * }, 10000);
3229
- */
3230
- async claimUnbondPublic(staker_address, options = {}) {
3231
- const tx = (await this.buildClaimUnbondPublicTransaction(staker_address, options));
3232
- let feeAddress;
3233
- if (typeof options.privateKey !== "undefined") {
3234
- feeAddress = Address.from_private_key(options.privateKey);
3235
- }
3236
- else if (this.account !== undefined) {
3237
- feeAddress = this.account?.address();
3238
- }
3239
- else {
3240
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
3241
- }
3242
- // Check if the account has sufficient credits to pay for the transaction
3243
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
3244
- return await this.networkClient.submitTransaction(tx);
3245
- }
3246
- /**
3247
- * Build a set_validator_state transaction for later usage.
3248
- *
3249
- * This function allows a validator to set their state to be either opened or closed to new stakers.
3250
- * When the validator is open to new stakers, any staker (including the validator) can bond or unbond from the validator.
3251
- * When the validator is closed to new stakers, existing stakers can still bond or unbond from the validator, but new stakers cannot bond.
3252
- *
3253
- * This function serves two primary purposes:
3254
- * 1. Allow a validator to leave the committee, by closing themselves to stakers and then unbonding all of their stakers.
3255
- * 2. Allow a validator to maintain their % of stake, by closing themselves to allowing more stakers to bond to them.
3256
- *
3257
- * @param {boolean} validator_state
3258
- * @param {Partial<ExecuteOptions>} options - Override default execution options
3259
- * @returns {Promise<Transaction>} The transaction object
3260
- *
3261
- * @example
3262
- * // Import the mainnet version of the sdk.
3263
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3264
- *
3265
- * // Create a keyProvider to handle key management
3266
- * const keyProvider = new AleoKeyProvider();
3267
- * keyProvider.useCache = true;
3268
- *
3269
- * // Create a new ProgramManager with the key that will be used to bond credits
3270
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3271
- *
3272
- * // Create the set_validator_state transaction
3273
- * const tx = await programManager.buildSetValidatorStateTransaction(true);
3274
- *
3275
- * // The transaction can be submitted later to the network using the network client.
3276
- * programManager.networkClient.submitTransaction(tx.toString());
3277
- *
3278
- * // Verify the transaction was successful
3279
- * setTimeout(async () => {
3280
- * const transaction = await programManager.networkClient.getTransaction(tx.id());
3281
- * assert(transaction.id() === tx.id());
3282
- * }, 10000);
3283
- */
3284
- async buildSetValidatorStateTransaction(validator_state, options = {}) {
3285
- const { programName = "credits.aleo", functionName = "set_validator_state", priorityFee = 0, privateFee = false, inputs = [validator_state.toString()], keySearchParams = new AleoKeyProviderParams({
3286
- proverUri: CREDITS_PROGRAM_KEYS.set_validator_state.prover,
3287
- verifierUri: CREDITS_PROGRAM_KEYS.set_validator_state.verifier,
3288
- cacheKey: "credits.aleo/set_validator_state",
3289
- }), ...additionalOptions } = options;
3290
- const executeOptions = {
3291
- programName,
3292
- functionName,
3293
- priorityFee,
3294
- privateFee,
3295
- inputs,
3296
- keySearchParams,
3297
- ...additionalOptions,
3298
- };
3299
- return await this.buildExecutionTransaction(executeOptions);
3300
- }
3301
- /**
3302
- * Submit a set_validator_state transaction to the Aleo Network.
3303
- *
3304
- * This function allows a validator to set their state to be either opened or closed to new stakers.
3305
- * When the validator is open to new stakers, any staker (including the validator) can bond or unbond from the validator.
3306
- * When the validator is closed to new stakers, existing stakers can still bond or unbond from the validator, but new stakers cannot bond.
3307
- *
3308
- * This function serves two primary purposes:
3309
- * 1. Allow a validator to leave the committee, by closing themselves to stakers and then unbonding all of their stakers.
3310
- * 2. Allow a validator to maintain their % of stake, by closing themselves to allowing more stakers to bond to them.
3311
- *
3312
- * @param {boolean} validator_state
3313
- * @param {Partial<ExecuteOptions>} options - Override default execution options
3314
- * @returns {Promise<string>} The transaction id
3315
- *
3316
- * @example
3317
- * // Import the mainnet version of the sdk.
3318
- * import { AleoKeyProvider, ProgramManager } from "@provablehq/sdk/mainnet.js";
3319
- *
3320
- * // Create a keyProvider to handle key management
3321
- * const keyProvider = new AleoKeyProvider();
3322
- * keyProvider.useCache = true;
3323
- *
3324
- * // Create a new ProgramManager with the key that will be used to bond credits
3325
- * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
3326
- *
3327
- * // Create the set_validator_state transaction
3328
- * const tx_id = await programManager.setValidatorState(true);
3329
- *
3330
- * // Verify the transaction was successful
3331
- * setTimeout(async () => {
3332
- * const transaction = await programManager.networkClient.getTransaction(tx_id);
3333
- * assert(transaction.id() === tx_id);
3334
- * }, 10000);
3335
- */
3336
- async setValidatorState(validator_state, options = {}) {
3337
- const tx = (await this.buildSetValidatorStateTransaction(validator_state, options));
3338
- let feeAddress;
3339
- if (typeof options.privateKey !== "undefined") {
3340
- feeAddress = Address.from_private_key(options.privateKey);
3341
- }
3342
- else if (this.account !== undefined) {
3343
- feeAddress = this.account?.address();
3344
- }
3345
- else {
3346
- throw Error("No private key provided and no private key set in the ProgramManager. Please set an account or provide a private key.");
3347
- }
3348
- // Check if the account has sufficient credits to pay for the transaction
3349
- await this.checkFee(feeAddress.to_string(), tx.feeAmount());
3350
- return this.networkClient.submitTransaction(tx);
3351
- }
3352
- /**
3353
- * Verify a proof from an offline execution. This is useful when it is desired to do offchain proving and verification.
3354
- *
3355
- * @param {executionResponse} executionResponse The response from an offline function execution (via the `programManager.run` method)
3356
- * @param {ImportedPrograms} imports The imported programs used in the execution. Specified as { "programName": "programSourceCode", ... }
3357
- * @param {ImportedVerifyingKeys} importedVerifyingKeys The verifying keys in the execution. Specified as { "programName": [["functionName", "verifyingKey"], ...], ... }
3358
- * @returns {boolean} True if the proof is valid, false otherwise
3359
- *
3360
- * @example
3361
- * /// Import the mainnet version of the sdk used to build executions.
3362
- * import { Account, ProgramManager } from "@provablehq/sdk/mainnet.js";
3363
- *
3364
- * /// Create the source for two programs.
3365
- * const program = "import add_it_up.aleo; \n\n program mul_add.aleo;\n\nfunction mul_and_add:\n input r0 as u32.public;\n input r1 as u32.private;\n mul r0 r1 into r2;\n call add_it_up.aleo/add_it r1 r2 into r3; output r3 as u32.private;\n";
3366
- * const program_import = "program add_it_up.aleo;\n\nfunction add_it:\n input r0 as u32.public;\n input r1 as u32.private;\n add r0 r1 into r2;\n output r2 as u32.private;\n";
3367
- * const programManager = new ProgramManager(undefined, undefined, undefined);
3368
- *
3369
- * /// Create a temporary account for the execution of the program
3370
- * const account = Account.fromCipherText(process.env.ciphertext, process.env.password);
3371
- * programManager.setAccount(account);
3372
- *
3373
- * /// Get the response and ensure that the program executed correctly
3374
- * const executionResponse = await programManager.run(program, "mul_and_add", ["5u32", "5u32"], true);
3375
- *
3376
- * /// Construct the imports and verifying keys
3377
- * const imports = { "add_it_up.aleo": program_import };
3378
- * const importedVerifyingKeys = { "add_it_up.aleo": [["add_it", "verifyingKey1..."]] };
3379
- *
3380
- * /// Verify the execution.
3381
- * const isValid = programManager.verifyExecution(executionResponse, imports, importedVerifyingKeys);
3382
- * assert(isValid);
3383
- */
3384
- verifyExecution(executionResponse, imports, importedVerifyingKeys) {
3385
- try {
3386
- const execution = (executionResponse.getExecution());
3387
- const function_id = executionResponse.getFunctionId();
3388
- const program = executionResponse.getProgram();
3389
- const verifyingKey = executionResponse.getVerifyingKey();
3390
- return verifyFunctionExecution(execution, verifyingKey, program, function_id, imports, importedVerifyingKeys);
3391
- }
3392
- catch (e) {
3393
- console.warn("The execution was not found in the response, cannot verify the execution");
3394
- return false;
3395
- }
3396
- }
3397
- /**
3398
- * Create a program object from a program's source code
3399
- *
3400
- * @param {string} program Program source code
3401
- * @returns {Program} The program object
3402
- */
3403
- createProgramFromSource(program) {
3404
- return Program.fromString(program);
3405
- }
3406
- /**
3407
- * Get the credits program object
3408
- *
3409
- * @returns {Program} The credits program object
3410
- */
3411
- creditsProgram() {
3412
- return Program.getCreditsProgram();
3413
- }
3414
- /**
3415
- * Verify a program is valid
3416
- *
3417
- * @param {string} program The program source code
3418
- */
3419
- verifyProgram(program) {
3420
- try {
3421
- Program.fromString(program);
3422
- return true;
3423
- }
3424
- catch (e) {
3425
- return false;
3426
- }
3427
- }
3428
- // Internal utility function for getting a credits.aleo record
3429
- async getCreditsRecord(amount, nonces, record, params) {
3430
- try {
3431
- return record instanceof RecordPlaintext
3432
- ? record
3433
- : RecordPlaintext.fromString(record);
3434
- }
3435
- catch (e) {
3436
- try {
3437
- const recordProvider = this.recordProvider;
3438
- return (await recordProvider.findCreditsRecord(amount, true, nonces, params));
3439
- }
3440
- catch (e) {
3441
- logAndThrow(`Error finding fee record. Record finder response: '${e.message}'. Please ensure you're connected to a valid Aleo network and a record with enough balance exists.`);
3442
- }
3443
- }
3444
- }
3445
- }
3446
- // Ensure the transfer type requires an amount record
3447
- function requiresAmountRecord(transferType) {
3448
- return PRIVATE_TRANSFER_TYPES.has(transferType);
3449
- }
3450
- // Validate the transfer type
3451
- function validateTransferType(transferType) {
3452
- return VALID_TRANSFER_TYPES.has(transferType)
3453
- ? transferType
3454
- : logAndThrow(`Invalid transfer type '${transferType}'. Valid transfer types are 'private', 'privateToPublic', 'public', and 'publicToPrivate'.`);
3455
- }
3456
-
3457
- export { AleoKeyProvider as A, CREDITS_PROGRAM_KEYS as C, KEY_STORE as K, ProgramManager as P, VALID_TRANSFER_TYPES as V, AleoKeyProviderParams as a, AleoNetworkClient as b, PRIVATE_TRANSFER as c, PRIVATE_TO_PUBLIC_TRANSFER as d, PRIVATE_TRANSFER_TYPES as e, PUBLIC_TRANSFER as f, PUBLIC_TRANSFER_AS_SIGNER as g, PUBLIC_TO_PRIVATE_TRANSFER as h, logAndThrow as l };
3458
- //# sourceMappingURL=program-manager-B-18sj9m.js.map