@provablehq/sdk 0.7.4 → 0.7.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/dist/mainnet/account.d.ts +137 -0
  2. package/dist/mainnet/browser.d.ts +20 -0
  3. package/dist/mainnet/browser.js +934 -0
  4. package/dist/mainnet/browser.js.map +1 -0
  5. package/dist/mainnet/constants.d.ts +34 -0
  6. package/dist/mainnet/function-key-provider.d.ts +349 -0
  7. package/dist/mainnet/managed-worker.d.ts +3 -0
  8. package/dist/mainnet/models/block.d.ts +21 -0
  9. package/dist/mainnet/models/confirmed_transaction.d.ts +6 -0
  10. package/dist/mainnet/models/execution.d.ts +5 -0
  11. package/dist/mainnet/models/input.d.ts +10 -0
  12. package/dist/mainnet/models/output.d.ts +6 -0
  13. package/dist/mainnet/models/transactionModel.d.ts +6 -0
  14. package/dist/mainnet/models/transition.d.ts +13 -0
  15. package/dist/mainnet/network-client.d.ts +270 -0
  16. package/dist/mainnet/node-polyfill.d.ts +5 -0
  17. package/dist/mainnet/node-polyfill.js +304 -0
  18. package/dist/mainnet/node-polyfill.js.map +1 -0
  19. package/dist/mainnet/node.d.ts +2 -0
  20. package/dist/mainnet/node.js +13 -0
  21. package/dist/mainnet/node.js.map +1 -0
  22. package/dist/mainnet/offline-key-provider.d.ts +348 -0
  23. package/dist/mainnet/polyfill/crypto.d.ts +1 -0
  24. package/dist/mainnet/polyfill/fetch.d.ts +1 -0
  25. package/dist/mainnet/polyfill/shared.d.ts +1 -0
  26. package/dist/mainnet/polyfill/worker.d.ts +1 -0
  27. package/dist/mainnet/polyfill/xmlhttprequest.d.ts +1 -0
  28. package/dist/mainnet/program-manager-a25c2f23.js +2200 -0
  29. package/dist/mainnet/program-manager-a25c2f23.js.map +1 -0
  30. package/dist/mainnet/program-manager.d.ts +640 -0
  31. package/dist/mainnet/record-provider.d.ts +236 -0
  32. package/dist/mainnet/utils.d.ts +4 -0
  33. package/dist/mainnet/wasm.d.ts +1 -0
  34. package/dist/mainnet/worker.d.ts +9 -0
  35. package/dist/mainnet/worker.js +78 -0
  36. package/dist/mainnet/worker.js.map +1 -0
  37. package/dist/testnet/account.d.ts +137 -0
  38. package/dist/testnet/browser.d.ts +20 -0
  39. package/dist/testnet/browser.js +934 -0
  40. package/dist/testnet/browser.js.map +1 -0
  41. package/dist/testnet/constants.d.ts +34 -0
  42. package/dist/testnet/function-key-provider.d.ts +349 -0
  43. package/dist/testnet/managed-worker.d.ts +3 -0
  44. package/dist/testnet/models/block.d.ts +21 -0
  45. package/dist/testnet/models/confirmed_transaction.d.ts +6 -0
  46. package/dist/testnet/models/execution.d.ts +5 -0
  47. package/dist/testnet/models/input.d.ts +10 -0
  48. package/dist/testnet/models/output.d.ts +6 -0
  49. package/dist/testnet/models/transactionModel.d.ts +6 -0
  50. package/dist/testnet/models/transition.d.ts +13 -0
  51. package/dist/testnet/network-client.d.ts +270 -0
  52. package/dist/testnet/node-polyfill.d.ts +5 -0
  53. package/dist/testnet/node-polyfill.js +304 -0
  54. package/dist/testnet/node-polyfill.js.map +1 -0
  55. package/dist/testnet/node.d.ts +2 -0
  56. package/dist/testnet/node.js +13 -0
  57. package/dist/testnet/node.js.map +1 -0
  58. package/dist/testnet/offline-key-provider.d.ts +348 -0
  59. package/dist/testnet/polyfill/crypto.d.ts +1 -0
  60. package/dist/testnet/polyfill/fetch.d.ts +1 -0
  61. package/dist/testnet/polyfill/shared.d.ts +1 -0
  62. package/dist/testnet/polyfill/worker.d.ts +1 -0
  63. package/dist/testnet/polyfill/xmlhttprequest.d.ts +1 -0
  64. package/dist/testnet/program-manager-4e9a7ef4.js +2200 -0
  65. package/dist/testnet/program-manager-4e9a7ef4.js.map +1 -0
  66. package/dist/testnet/program-manager.d.ts +640 -0
  67. package/dist/testnet/record-provider.d.ts +236 -0
  68. package/dist/testnet/utils.d.ts +4 -0
  69. package/dist/testnet/wasm.d.ts +1 -0
  70. package/dist/testnet/worker.d.ts +9 -0
  71. package/dist/testnet/worker.js +78 -0
  72. package/dist/testnet/worker.js.map +1 -0
  73. package/package.json +1 -1
@@ -0,0 +1,2200 @@
1
+ import { PrivateKey, RecordCiphertext, Program, Transaction, Metadata, VerifyingKey, ProvingKey, ProgramManager as ProgramManager$1, RecordPlaintext, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
2
+
3
+ function logAndThrow(message) {
4
+ console.error(message);
5
+ throw new Error(message);
6
+ }
7
+ function parseJSON(json) {
8
+ function revive(key, value, context) {
9
+ if (Number.isInteger(value)) {
10
+ return BigInt(context.source);
11
+ }
12
+ else {
13
+ return value;
14
+ }
15
+ }
16
+ return JSON.parse(json, revive);
17
+ }
18
+ async function get(url, options) {
19
+ const response = await fetch(url, options);
20
+ if (!response.ok) {
21
+ throw new Error(response.status + " could not get URL " + url);
22
+ }
23
+ return response;
24
+ }
25
+ async function post(url, options) {
26
+ options.method = "POST";
27
+ const response = await fetch(url, options);
28
+ if (!response.ok) {
29
+ throw new Error(response.status + " could not post URL " + url);
30
+ }
31
+ return response;
32
+ }
33
+
34
+ /**
35
+ * Client library that encapsulates REST calls to publicly exposed endpoints of Aleo nodes. The methods provided in this
36
+ * allow users to query public information from the Aleo blockchain and submit transactions to the network.
37
+ *
38
+ * @param {string} host
39
+ * @example
40
+ * // Connection to a local node
41
+ * const localNetworkClient = new AleoNetworkClient("http://localhost:3030");
42
+ *
43
+ * // Connection to a public beacon node
44
+ * const publicnetworkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
45
+ */
46
+ class AleoNetworkClient {
47
+ host;
48
+ headers;
49
+ account;
50
+ constructor(host, options) {
51
+ this.host = host + "/mainnet";
52
+ if (options && options.headers) {
53
+ this.headers = options.headers;
54
+ }
55
+ else {
56
+ this.headers = {
57
+ // This is replaced by the actual version by a Rollup plugin
58
+ "X-Aleo-SDK-Version": "0.7.4",
59
+ };
60
+ }
61
+ }
62
+ /**
63
+ * Set an account to use in networkClient calls
64
+ *
65
+ * @param {Account} account
66
+ * @example
67
+ * const account = new Account();
68
+ * networkClient.setAccount(account);
69
+ */
70
+ setAccount(account) {
71
+ this.account = account;
72
+ }
73
+ /**
74
+ * Return the Aleo account used in the networkClient
75
+ *
76
+ * @example
77
+ * const account = networkClient.getAccount();
78
+ */
79
+ getAccount() {
80
+ return this.account;
81
+ }
82
+ /**
83
+ * Set a new host for the networkClient
84
+ *
85
+ * @param {string} host The address of a node hosting the Aleo API
86
+ * @param host
87
+ */
88
+ setHost(host) {
89
+ this.host = host + "/mainnet";
90
+ }
91
+ async fetchData(url = "/") {
92
+ try {
93
+ const response = await get(this.host + url, {
94
+ headers: this.headers
95
+ });
96
+ const text = await response.text();
97
+ return parseJSON(text);
98
+ }
99
+ catch (error) {
100
+ throw new Error("Error fetching data.");
101
+ }
102
+ }
103
+ /**
104
+ * Attempts to find unspent records in the Aleo blockchain for a specified private key
105
+ * @param {number} startHeight - The height at which to start searching for unspent records
106
+ * @param {number} endHeight - The height at which to stop searching for unspent records
107
+ * @param {string | PrivateKey} privateKey - The private key to use to find unspent records
108
+ * @param {number[]} amounts - The amounts (in microcredits) to search for (eg. [100, 200, 3000])
109
+ * @param {number} maxMicrocredits - The maximum number of microcredits to search for
110
+ * @param {string[]} nonces - The nonces of already found records to exclude from the search
111
+ *
112
+ * @example
113
+ * // Find all unspent records
114
+ * const privateKey = "[PRIVATE_KEY]";
115
+ * const records = networkClient.findUnspentRecords(0, undefined, privateKey);
116
+ *
117
+ * // Find specific amounts
118
+ * const startHeight = 500000;
119
+ * const amounts = [600000, 1000000];
120
+ * const records = networkClient.findUnspentRecords(startHeight, undefined, privateKey, amounts);
121
+ *
122
+ * // Find specific amounts with a maximum number of cumulative microcredits
123
+ * const maxMicrocredits = 100000;
124
+ * const records = networkClient.findUnspentRecords(startHeight, undefined, privateKey, undefined, maxMicrocredits);
125
+ */
126
+ async findUnspentRecords(startHeight, endHeight, privateKey, amounts, maxMicrocredits, nonces) {
127
+ nonces = nonces || [];
128
+ // Ensure start height is not negative
129
+ if (startHeight < 0) {
130
+ throw new Error("Start height must be greater than or equal to 0");
131
+ }
132
+ // Initialize search parameters
133
+ const records = new Array();
134
+ let start;
135
+ let end;
136
+ let resolvedPrivateKey;
137
+ let failures = 0;
138
+ let totalRecordValue = BigInt(0);
139
+ let latestHeight;
140
+ // Ensure a private key is present to find owned records
141
+ if (typeof privateKey === "undefined") {
142
+ if (typeof this.account === "undefined") {
143
+ throw new Error("Private key must be specified in an argument to findOwnedRecords or set in the AleoNetworkClient");
144
+ }
145
+ else {
146
+ resolvedPrivateKey = this.account._privateKey;
147
+ }
148
+ }
149
+ else {
150
+ try {
151
+ resolvedPrivateKey = privateKey instanceof PrivateKey ? privateKey : PrivateKey.from_string(privateKey);
152
+ }
153
+ catch (error) {
154
+ throw new Error("Error parsing private key provided.");
155
+ }
156
+ }
157
+ const viewKey = resolvedPrivateKey.to_view_key();
158
+ // Get the latest height to ensure the range being searched is valid
159
+ try {
160
+ const blockHeight = await this.getLatestHeight();
161
+ if (typeof blockHeight === "number") {
162
+ latestHeight = blockHeight;
163
+ }
164
+ else {
165
+ throw new Error("Error fetching latest block height.");
166
+ }
167
+ }
168
+ catch (error) {
169
+ throw new Error("Error fetching latest block height.");
170
+ }
171
+ // If no end height is specified or is greater than the latest height, set the end height to the latest height
172
+ if (typeof endHeight === "number" && endHeight <= latestHeight) {
173
+ end = endHeight;
174
+ }
175
+ else {
176
+ end = latestHeight;
177
+ }
178
+ // If the starting is greater than the ending height, return an error
179
+ if (startHeight > end) {
180
+ throw new Error("Start height must be less than or equal to end height.");
181
+ }
182
+ // Iterate through blocks in reverse order in chunks of 50
183
+ while (end > startHeight) {
184
+ start = end - 50;
185
+ if (start < startHeight) {
186
+ start = startHeight;
187
+ }
188
+ try {
189
+ // Get 50 blocks (or the difference between the start and end if less than 50)
190
+ const blocks = await this.getBlockRange(start, end);
191
+ end = start;
192
+ // Iterate through blocks to find unspent records
193
+ for (let i = 0; i < blocks.length; i++) {
194
+ const block = blocks[i];
195
+ const transactions = block.transactions;
196
+ if (!(typeof transactions === "undefined")) {
197
+ for (let j = 0; j < transactions.length; j++) {
198
+ const confirmedTransaction = transactions[j];
199
+ // Search for unspent records in execute transactions of credits.aleo
200
+ if (confirmedTransaction.type == "execute") {
201
+ const transaction = confirmedTransaction.transaction;
202
+ if (transaction.execution && !(typeof transaction.execution.transitions == "undefined")) {
203
+ for (let k = 0; k < transaction.execution.transitions.length; k++) {
204
+ const transition = transaction.execution.transitions[k];
205
+ // Only search for unspent records in credits.aleo (for now)
206
+ if (transition.program !== "credits.aleo") {
207
+ continue;
208
+ }
209
+ if (!(typeof transition.outputs == "undefined")) {
210
+ for (let l = 0; l < transition.outputs.length; l++) {
211
+ const output = transition.outputs[l];
212
+ if (output.type === "record") {
213
+ try {
214
+ // Create a wasm record ciphertext object from the found output
215
+ const record = RecordCiphertext.fromString(output.value);
216
+ // Determine if the record is owned by the specified view key
217
+ if (record.isOwner(viewKey)) {
218
+ // Decrypt the record and get the serial number
219
+ const recordPlaintext = record.decrypt(viewKey);
220
+ // If the record has already been found, skip it
221
+ const nonce = recordPlaintext.nonce();
222
+ if (nonces.includes(nonce)) {
223
+ continue;
224
+ }
225
+ // Otherwise record the nonce that has been found
226
+ const serialNumber = recordPlaintext.serialNumberString(resolvedPrivateKey, "credits.aleo", "credits");
227
+ // Attempt to see if the serial number is spent
228
+ try {
229
+ await this.getTransitionId(serialNumber);
230
+ }
231
+ catch (error) {
232
+ // If it's not found, add it to the list of unspent records
233
+ if (!amounts) {
234
+ records.push(recordPlaintext);
235
+ // If the user specified a maximum number of microcredits, check if the search has found enough
236
+ if (typeof maxMicrocredits === "number") {
237
+ totalRecordValue += recordPlaintext.microcredits();
238
+ // Exit if the search has found the amount specified
239
+ if (totalRecordValue >= BigInt(maxMicrocredits)) {
240
+ return records;
241
+ }
242
+ }
243
+ }
244
+ // If the user specified a list of amounts, check if the search has found them
245
+ if (!(typeof amounts === "undefined") && amounts.length > 0) {
246
+ let amounts_found = 0;
247
+ if (recordPlaintext.microcredits() > amounts[amounts_found]) {
248
+ amounts_found += 1;
249
+ records.push(recordPlaintext);
250
+ // If the user specified a maximum number of microcredits, check if the search has found enough
251
+ if (typeof maxMicrocredits === "number") {
252
+ totalRecordValue += recordPlaintext.microcredits();
253
+ // Exit if the search has found the amount specified
254
+ if (totalRecordValue >= BigInt(maxMicrocredits)) {
255
+ return records;
256
+ }
257
+ }
258
+ if (records.length >= amounts.length) {
259
+ return records;
260
+ }
261
+ }
262
+ }
263
+ }
264
+ }
265
+ }
266
+ catch (error) {
267
+ }
268
+ }
269
+ }
270
+ }
271
+ }
272
+ }
273
+ }
274
+ }
275
+ }
276
+ }
277
+ }
278
+ catch (error) {
279
+ // If there is an error fetching blocks, log it and keep searching
280
+ console.warn("Error fetching blocks in range: " + start.toString() + "-" + end.toString());
281
+ console.warn("Error: ", error);
282
+ failures += 1;
283
+ if (failures > 10) {
284
+ console.warn("10 failures fetching records reached. Returning records fetched so far");
285
+ return records;
286
+ }
287
+ }
288
+ }
289
+ return records;
290
+ }
291
+ /**
292
+ * Returns the contents of the block at the specified block height
293
+ *
294
+ * @param {number} height
295
+ * @example
296
+ * const block = networkClient.getBlock(1234);
297
+ */
298
+ async getBlock(height) {
299
+ try {
300
+ const block = await this.fetchData("/block/" + height);
301
+ return block;
302
+ }
303
+ catch (error) {
304
+ throw new Error("Error fetching block.");
305
+ }
306
+ }
307
+ /**
308
+ * Returns a range of blocks between the specified block heights
309
+ *
310
+ * @param {number} start
311
+ * @param {number} end
312
+ * @example
313
+ * const blockRange = networkClient.getBlockRange(2050, 2100);
314
+ */
315
+ async getBlockRange(start, end) {
316
+ try {
317
+ return await this.fetchData("/blocks?start=" + start + "&end=" + end);
318
+ }
319
+ catch (error) {
320
+ const errorMessage = `Error fetching blocks between ${start} and ${end}.`;
321
+ throw new Error(errorMessage);
322
+ }
323
+ }
324
+ /**
325
+ * Returns the deployment transaction id associated with the specified program
326
+ *
327
+ * @param {Program | string} program
328
+ * @returns {TransactionModel}
329
+ */
330
+ async getDeploymentTransactionIDForProgram(program) {
331
+ if (program instanceof Program) {
332
+ program = program.toString();
333
+ }
334
+ try {
335
+ const id = await this.fetchData("/find/transactionID/deployment/" + program);
336
+ return id.replace("\"", "");
337
+ }
338
+ catch (error) {
339
+ throw new Error("Error fetching deployment transaction for program.");
340
+ }
341
+ }
342
+ /**
343
+ * Returns the deployment transaction associated with a specified program
344
+ *
345
+ * @param {Program | string} program
346
+ * @returns {TransactionModel}
347
+ */
348
+ async getDeploymentTransactionForProgram(program) {
349
+ try {
350
+ const transaction_id = await this.getDeploymentTransactionIDForProgram(program);
351
+ return await this.getTransaction(transaction_id);
352
+ }
353
+ catch (error) {
354
+ throw new Error("Error fetching deployment transaction for program.");
355
+ }
356
+ }
357
+ /**
358
+ * Returns the contents of the latest block
359
+ *
360
+ * @example
361
+ * const latestHeight = networkClient.getLatestBlock();
362
+ */
363
+ async getLatestBlock() {
364
+ try {
365
+ return await this.fetchData("/block/latest");
366
+ }
367
+ catch (error) {
368
+ throw new Error("Error fetching latest block.");
369
+ }
370
+ }
371
+ /**
372
+ * Returns the latest committee
373
+ *
374
+ * @returns {Promise<object>} A javascript object containing the latest committee
375
+ */
376
+ async getLatestCommittee() {
377
+ try {
378
+ return await this.fetchData("/committee/latest");
379
+ }
380
+ catch (error) {
381
+ throw new Error("Error fetching latest block.");
382
+ }
383
+ }
384
+ /**
385
+ * Returns the latest block height
386
+ *
387
+ * @example
388
+ * const latestHeight = networkClient.getLatestHeight();
389
+ */
390
+ async getLatestHeight() {
391
+ try {
392
+ return Number(await this.fetchData("/block/height/latest"));
393
+ }
394
+ catch (error) {
395
+ throw new Error("Error fetching latest height.");
396
+ }
397
+ }
398
+ /**
399
+ * Returns the source code of a program given a program ID
400
+ *
401
+ * @param {string} programId The program ID of a program deployed to the Aleo Network
402
+ * @return {Promise<string>} Source code of the program
403
+ *
404
+ * @example
405
+ * const program = networkClient.getProgram("hello_hello.aleo");
406
+ * 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"
407
+ * assert.equal(program, expectedSource);
408
+ */
409
+ async getProgram(programId) {
410
+ try {
411
+ return await this.fetchData("/program/" + programId);
412
+ }
413
+ catch (error) {
414
+ throw new Error("Error fetching program");
415
+ }
416
+ }
417
+ /**
418
+ * Returns a program object from a program ID or program source code
419
+ *
420
+ * @param {string} inputProgram The program ID or program source code of a program deployed to the Aleo Network
421
+ * @return {Promise<Program>} Source code of the program
422
+ *
423
+ * @example
424
+ * const programID = "hello_hello.aleo";
425
+ * 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"
426
+ *
427
+ * // Get program object from program ID or program source code
428
+ * const programObjectFromID = await networkClient.getProgramObject(programID);
429
+ * const programObjectFromSource = await networkClient.getProgramObject(programSource);
430
+ *
431
+ * // Both program objects should be equal
432
+ * assert.equal(programObjectFromID.to_string(), programObjectFromSource.to_string());
433
+ */
434
+ async getProgramObject(inputProgram) {
435
+ try {
436
+ return Program.fromString(inputProgram);
437
+ }
438
+ catch (error) {
439
+ try {
440
+ return Program.fromString((await this.getProgram(inputProgram)));
441
+ }
442
+ catch (error) {
443
+ throw new Error(`${inputProgram} is neither a program name or a valid program`);
444
+ }
445
+ }
446
+ }
447
+ /**
448
+ * Returns an object containing the source code of a program and the source code of all programs it imports
449
+ *
450
+ * @param {Program | string} inputProgram The program ID or program source code of a program deployed to the Aleo Network
451
+ * @returns {Promise<ProgramImports>} Object of the form { "program_id": "program_source", .. } containing program id & source code for all program imports
452
+ *
453
+ * @example
454
+ * 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"
455
+ * const double_test = Program.fromString(double_test_source);
456
+ * const expectedImports = {
457
+ * "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"
458
+ * }
459
+ *
460
+ * // Imports can be fetched using the program ID, source code, or program object
461
+ * let programImports = await networkClient.getProgramImports("double_test.aleo");
462
+ * assert.deepStrictEqual(programImports, expectedImports);
463
+ *
464
+ * // Using the program source code
465
+ * programImports = await networkClient.getProgramImports(double_test_source);
466
+ * assert.deepStrictEqual(programImports, expectedImports);
467
+ *
468
+ * // Using the program object
469
+ * programImports = await networkClient.getProgramImports(double_test);
470
+ * assert.deepStrictEqual(programImports, expectedImports);
471
+ */
472
+ async getProgramImports(inputProgram) {
473
+ try {
474
+ const imports = {};
475
+ // Get the program object or fail if the program is not valid or does not exist
476
+ const program = inputProgram instanceof Program ? inputProgram : (await this.getProgramObject(inputProgram));
477
+ // Get the list of programs that the program imports
478
+ const importList = program.getImports();
479
+ // Recursively get any imports that the imported programs have in a depth first search order
480
+ for (let i = 0; i < importList.length; i++) {
481
+ const import_id = importList[i];
482
+ if (!imports.hasOwnProperty(import_id)) {
483
+ const programSource = await this.getProgram(import_id);
484
+ const nestedImports = await this.getProgramImports(import_id);
485
+ for (const key in nestedImports) {
486
+ if (!imports.hasOwnProperty(key)) {
487
+ imports[key] = nestedImports[key];
488
+ }
489
+ }
490
+ imports[import_id] = programSource;
491
+ }
492
+ }
493
+ return imports;
494
+ }
495
+ catch (error) {
496
+ logAndThrow("Error fetching program imports: " + error.message);
497
+ }
498
+ }
499
+ /**
500
+ * Get a list of the program names that a program imports
501
+ *
502
+ * @param {Program | string} inputProgram - The program id or program source code to get the imports of
503
+ * @returns {string[]} - The list of program names that the program imports
504
+ *
505
+ * @example
506
+ * const programImportsNames = networkClient.getProgramImports("double_test.aleo");
507
+ * const expectedImportsNames = ["multiply_test.aleo"];
508
+ * assert.deepStrictEqual(programImportsNames, expectedImportsNames);
509
+ */
510
+ async getProgramImportNames(inputProgram) {
511
+ try {
512
+ const program = inputProgram instanceof Program ? inputProgram : (await this.getProgramObject(inputProgram));
513
+ return program.getImports();
514
+ }
515
+ catch (error) {
516
+ throw new Error("Error fetching program imports with error: " + error.message);
517
+ }
518
+ }
519
+ /**
520
+ * Returns the names of the mappings of a program
521
+ *
522
+ * @param {string} programId - The program ID to get the mappings of (e.g. "credits.aleo")
523
+ * @example
524
+ * const mappings = networkClient.getProgramMappingNames("credits.aleo");
525
+ * const expectedMappings = ["account"];
526
+ * assert.deepStrictEqual(mappings, expectedMappings);
527
+ */
528
+ async getProgramMappingNames(programId) {
529
+ try {
530
+ return await this.fetchData("/program/" + programId + "/mappings");
531
+ }
532
+ catch (error) {
533
+ throw new Error("Error fetching program mappings - ensure the program exists on chain before trying again");
534
+ }
535
+ }
536
+ /**
537
+ * Returns the value of a program's mapping for a specific key
538
+ *
539
+ * @param {string} programId - The program ID to get the mapping value of (e.g. "credits.aleo")
540
+ * @param {string} mappingName - The name of the mapping to get the value of (e.g. "account")
541
+ * @param {string} key - The key of the mapping to get the value of (e.g. "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px")
542
+ * @return {Promise<string>} String representation of the value of the mapping
543
+ *
544
+ * @example
545
+ * // Get public balance of an account
546
+ * const mappingValue = networkClient.getMappingValue("credits.aleo", "account", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px");
547
+ * const expectedValue = "0u64";
548
+ * assert.equal(mappingValue, expectedValue);
549
+ */
550
+ async getProgramMappingValue(programId, mappingName, key) {
551
+ try {
552
+ return await this.fetchData("/program/" + programId + "/mapping/" + mappingName + "/" + key);
553
+ }
554
+ catch (error) {
555
+ throw new Error("Error fetching mapping value - ensure the mapping exists and the key is correct");
556
+ }
557
+ }
558
+ /**
559
+ * Returns the latest state/merkle root of the Aleo blockchain
560
+ *
561
+ * @example
562
+ * const stateRoot = networkClient.getStateRoot();
563
+ */
564
+ async getStateRoot() {
565
+ try {
566
+ return await this.fetchData("/stateRoot/latest");
567
+ }
568
+ catch (error) {
569
+ throw new Error("Error fetching Aleo state root");
570
+ }
571
+ }
572
+ /**
573
+ * Returns a transaction by its unique identifier
574
+ *
575
+ * @param {string} id
576
+ * @example
577
+ * const transaction = networkClient.getTransaction("at1handz9xjrqeynjrr0xay4pcsgtnczdksz3e584vfsgaz0dh0lyxq43a4wj");
578
+ */
579
+ async getTransaction(id) {
580
+ try {
581
+ return await this.fetchData("/transaction/" + id);
582
+ }
583
+ catch (error) {
584
+ throw new Error("Error fetching transaction.");
585
+ }
586
+ }
587
+ /**
588
+ * Returns the transactions present at the specified block height
589
+ *
590
+ * @param {number} height
591
+ * @example
592
+ * const transactions = networkClient.getTransactions(654);
593
+ */
594
+ async getTransactions(height) {
595
+ try {
596
+ return await this.fetchData("/block/" + height.toString() + "/transactions");
597
+ }
598
+ catch (error) {
599
+ throw new Error("Error fetching transactions.");
600
+ }
601
+ }
602
+ /**
603
+ * Returns the transactions in the memory pool.
604
+ *
605
+ * @example
606
+ * const transactions = networkClient.getTransactionsInMempool();
607
+ */
608
+ async getTransactionsInMempool() {
609
+ try {
610
+ return await this.fetchData("/memoryPool/transactions");
611
+ }
612
+ catch (error) {
613
+ throw new Error("Error fetching transactions from mempool.");
614
+ }
615
+ }
616
+ /**
617
+ * Returns the transition ID of the transition corresponding to the ID of the input or output.
618
+ * @param {string} inputOrOutputID - ID of the input or output.
619
+ *
620
+ * @example
621
+ * const transitionId = networkClient.getTransitionId("2429232855236830926144356377868449890830704336664550203176918782554219952323field");
622
+ */
623
+ async getTransitionId(inputOrOutputID) {
624
+ try {
625
+ return await this.fetchData("/find/transitionID/" + inputOrOutputID);
626
+ }
627
+ catch (error) {
628
+ throw new Error("Error fetching transition ID.");
629
+ }
630
+ }
631
+ /**
632
+ * Submit an execute or deployment transaction to the Aleo network
633
+ *
634
+ * @param {Transaction | string} transaction - The transaction to submit to the network
635
+ * @returns {string} - The transaction id of the submitted transaction or the resulting error
636
+ */
637
+ async submitTransaction(transaction) {
638
+ const transaction_string = transaction instanceof Transaction ? transaction.toString() : transaction;
639
+ try {
640
+ const response = await post(this.host + "/transaction/broadcast", {
641
+ body: transaction_string,
642
+ headers: Object.assign({}, this.headers, {
643
+ "Content-Type": "application/json",
644
+ }),
645
+ });
646
+ try {
647
+ const text = await response.text();
648
+ return parseJSON(text);
649
+ }
650
+ catch (error) {
651
+ throw new Error(`Error posting transaction. Aleo network response: ${error.message}`);
652
+ }
653
+ }
654
+ catch (error) {
655
+ throw new Error(`Error posting transaction: No response received: ${error.message}`);
656
+ }
657
+ }
658
+ }
659
+
660
+ const KEY_STORE = Metadata.baseUrl();
661
+ function convert(metadata) {
662
+ // This looks up the method name in VerifyingKey
663
+ const verifyingKey = VerifyingKey[metadata.verifyingKey];
664
+ if (!verifyingKey) {
665
+ throw new Error("Invalid method name: " + metadata.verifyingKey);
666
+ }
667
+ return {
668
+ name: metadata.name,
669
+ locator: metadata.locator,
670
+ prover: metadata.prover,
671
+ verifier: metadata.verifier,
672
+ verifyingKey,
673
+ };
674
+ }
675
+ const CREDITS_PROGRAM_KEYS = {
676
+ bond_public: convert(Metadata.bond_public()),
677
+ bond_validator: convert(Metadata.bond_validator()),
678
+ claim_unbond_public: convert(Metadata.claim_unbond_public()),
679
+ fee_private: convert(Metadata.fee_private()),
680
+ fee_public: convert(Metadata.fee_public()),
681
+ inclusion: convert(Metadata.inclusion()),
682
+ join: convert(Metadata.join()),
683
+ set_validator_state: convert(Metadata.set_validator_state()),
684
+ split: convert(Metadata.split()),
685
+ transfer_private: convert(Metadata.transfer_private()),
686
+ transfer_private_to_public: convert(Metadata.transfer_private_to_public()),
687
+ transfer_public: convert(Metadata.transfer_public()),
688
+ transfer_public_as_signer: convert(Metadata.transfer_public_as_signer()),
689
+ transfer_public_to_private: convert(Metadata.transfer_public_to_private()),
690
+ unbond_public: convert(Metadata.unbond_public()),
691
+ getKey: function (key) {
692
+ if (this.hasOwnProperty(key)) {
693
+ return this[key];
694
+ }
695
+ else {
696
+ throw new Error(`Key "${key}" not found.`);
697
+ }
698
+ }
699
+ };
700
+ const PRIVATE_TRANSFER_TYPES = new Set([
701
+ "transfer_private",
702
+ "private",
703
+ "transferPrivate",
704
+ "transfer_private_to_public",
705
+ "privateToPublic",
706
+ "transferPrivateToPublic",
707
+ ]);
708
+ const VALID_TRANSFER_TYPES = new Set([
709
+ "transfer_private",
710
+ "private",
711
+ "transferPrivate",
712
+ "transfer_private_to_public",
713
+ "privateToPublic",
714
+ "transferPrivateToPublic",
715
+ "transfer_public",
716
+ "transfer_public_as_signer",
717
+ "public",
718
+ "public_as_signer",
719
+ "transferPublic",
720
+ "transferPublicAsSigner",
721
+ "transfer_public_to_private",
722
+ "publicToPrivate",
723
+ "publicAsSigner",
724
+ "transferPublicToPrivate",
725
+ ]);
726
+ const PRIVATE_TRANSFER = new Set([
727
+ "private",
728
+ "transfer_private",
729
+ "transferPrivate",
730
+ ]);
731
+ const PRIVATE_TO_PUBLIC_TRANSFER = new Set([
732
+ "private_to_public",
733
+ "privateToPublic",
734
+ "transfer_private_to_public",
735
+ "transferPrivateToPublic",
736
+ ]);
737
+ const PUBLIC_TRANSFER = new Set([
738
+ "public",
739
+ "transfer_public",
740
+ "transferPublic",
741
+ ]);
742
+ const PUBLIC_TRANSFER_AS_SIGNER = new Set([
743
+ "public_as_signer",
744
+ "transfer_public_as_signer",
745
+ "transferPublicAsSigner",
746
+ ]);
747
+ const PUBLIC_TO_PRIVATE_TRANSFER = new Set([
748
+ "public_to_private",
749
+ "publicToPrivate",
750
+ "transfer_public_to_private",
751
+ "transferPublicToPrivate",
752
+ ]);
753
+
754
+ /**
755
+ * AleoKeyProviderParams search parameter for the AleoKeyProvider. It allows for the specification of a proverUri and
756
+ * verifierUri to fetch keys via HTTP from a remote resource as well as a unique cacheKey to store the keys in memory.
757
+ */
758
+ class AleoKeyProviderParams {
759
+ name;
760
+ proverUri;
761
+ verifierUri;
762
+ cacheKey;
763
+ /**
764
+ * Create a new AleoKeyProviderParams object which implements the KeySearchParams interface. Users can optionally
765
+ * specify a url for the proverUri & verifierUri to fetch keys via HTTP from a remote resource as well as a unique
766
+ * cacheKey to store the keys in memory for future use. If no proverUri or verifierUri is specified, a cachekey must
767
+ * be provided.
768
+ *
769
+ * @param { AleoKeyProviderInitParams } params - Optional search parameters
770
+ */
771
+ constructor(params) {
772
+ this.proverUri = params.proverUri;
773
+ this.verifierUri = params.verifierUri;
774
+ this.cacheKey = params.cacheKey;
775
+ this.name = params.name;
776
+ }
777
+ }
778
+ /**
779
+ * AleoKeyProvider class. Implements the KeyProvider interface. Enables the retrieval of Aleo program proving and
780
+ * verifying keys for the credits.aleo program over http from official Aleo sources and storing and retrieving function
781
+ * keys from a local memory cache.
782
+ */
783
+ class AleoKeyProvider {
784
+ cache;
785
+ cacheOption;
786
+ keyUris;
787
+ async fetchBytes(url = "/") {
788
+ try {
789
+ const response = await get(url);
790
+ const data = await response.arrayBuffer();
791
+ return new Uint8Array(data);
792
+ }
793
+ catch (error) {
794
+ throw new Error("Error fetching data." + error.message);
795
+ }
796
+ }
797
+ constructor() {
798
+ this.keyUris = KEY_STORE;
799
+ this.cache = new Map();
800
+ this.cacheOption = false;
801
+ }
802
+ /**
803
+ * Use local memory to store keys
804
+ *
805
+ * @param {boolean} useCache whether to store keys in local memory
806
+ */
807
+ useCache(useCache) {
808
+ this.cacheOption = useCache;
809
+ }
810
+ /**
811
+ * Clear the key cache
812
+ */
813
+ clearCache() {
814
+ this.cache.clear();
815
+ }
816
+ /**
817
+ * Cache a set of keys. This will overwrite any existing keys with the same keyId. The user can check if a keyId
818
+ * exists in the cache using the containsKeys method prior to calling this method if overwriting is not desired.
819
+ *
820
+ * @param {string} keyId access key for the cache
821
+ * @param {FunctionKeyPair} keys keys to cache
822
+ */
823
+ cacheKeys(keyId, keys) {
824
+ const [provingKey, verifyingKey] = keys;
825
+ this.cache.set(keyId, [provingKey.toBytes(), verifyingKey.toBytes()]);
826
+ }
827
+ /**
828
+ * Determine if a keyId exists in the cache
829
+ *
830
+ * @param {string} keyId keyId of a proving and verifying key pair
831
+ * @returns {boolean} true if the keyId exists in the cache, false otherwise
832
+ */
833
+ containsKeys(keyId) {
834
+ return this.cache.has(keyId);
835
+ }
836
+ /**
837
+ * Delete a set of keys from the cache
838
+ *
839
+ * @param {string} keyId keyId of a proving and verifying key pair to delete from memory
840
+ * @returns {boolean} true if the keyId exists in the cache and was deleted, false if the key did not exist
841
+ */
842
+ deleteKeys(keyId) {
843
+ return this.cache.delete(keyId);
844
+ }
845
+ /**
846
+ * Get a set of keys from the cache
847
+ * @param keyId keyId of a proving and verifying key pair
848
+ *
849
+ * @returns {FunctionKeyPair} Proving and verifying keys for the specified program
850
+ */
851
+ getKeys(keyId) {
852
+ console.debug(`Checking if key exists in cache. KeyId: ${keyId}`);
853
+ if (this.cache.has(keyId)) {
854
+ const [provingKeyBytes, verifyingKeyBytes] = this.cache.get(keyId);
855
+ return [ProvingKey.fromBytes(provingKeyBytes), VerifyingKey.fromBytes(verifyingKeyBytes)];
856
+ }
857
+ else {
858
+ throw new Error("Key not found in cache.");
859
+ }
860
+ }
861
+ /**
862
+ * Get arbitrary function keys from a provider
863
+ *
864
+ * @param {KeySearchParams} params parameters for the key search in form of: {proverUri: string, verifierUri: string, cacheKey: string}
865
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the specified program
866
+ *
867
+ * @example
868
+ * // Create a new object which implements the KeyProvider interface
869
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
870
+ * const keyProvider = new AleoKeyProvider();
871
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
872
+ *
873
+ * // Initialize a program manager with the key provider to automatically fetch keys for value transfers
874
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
875
+ * programManager.transfer(1, "aleo166q6ww6688cug7qxwe7nhctjpymydwzy2h7rscfmatqmfwnjvggqcad0at", "public", 0.5);
876
+ *
877
+ * // Keys can also be fetched manually using the key provider
878
+ * const keySearchParams = { "cacheKey": "myProgram:myFunction" };
879
+ * const [transferPrivateProvingKey, transferPrivateVerifyingKey] = await keyProvider.functionKeys(keySearchParams);
880
+ */
881
+ async functionKeys(params) {
882
+ if (params) {
883
+ let proverUrl;
884
+ let verifierUrl;
885
+ let cacheKey;
886
+ if ("name" in params && typeof params["name"] == "string") {
887
+ let key = CREDITS_PROGRAM_KEYS.getKey(params["name"]);
888
+ return this.fetchCreditsKeys(key);
889
+ }
890
+ if ("proverUri" in params && typeof params["proverUri"] == "string") {
891
+ proverUrl = params["proverUri"];
892
+ }
893
+ if ("verifierUri" in params && typeof params["verifierUri"] == "string") {
894
+ verifierUrl = params["verifierUri"];
895
+ }
896
+ if ("cacheKey" in params && typeof params["cacheKey"] == "string") {
897
+ cacheKey = params["cacheKey"];
898
+ }
899
+ if (proverUrl && verifierUrl) {
900
+ return await this.fetchRemoteKeys(proverUrl, verifierUrl, cacheKey);
901
+ }
902
+ if (cacheKey) {
903
+ return this.getKeys(cacheKey);
904
+ }
905
+ }
906
+ throw new Error("Invalid parameters provided, must provide either a cacheKey and/or a proverUrl and a verifierUrl");
907
+ }
908
+ /**
909
+ * Returns the proving and verifying keys for a specified program from a specified url.
910
+ *
911
+ * @param {string} verifierUrl Url of the proving key
912
+ * @param {string} proverUrl Url the verifying key
913
+ * @param {string} cacheKey Key to store the keys in the cache
914
+ *
915
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the specified program
916
+ *
917
+ * @example
918
+ * // Create a new AleoKeyProvider object
919
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
920
+ * const keyProvider = new AleoKeyProvider();
921
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
922
+ *
923
+ * // Initialize a program manager with the key provider to automatically fetch keys for value transfers
924
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
925
+ * programManager.transfer(1, "aleo166q6ww6688cug7qxwe7nhctjpymydwzy2h7rscfmatqmfwnjvggqcad0at", "public", 0.5);
926
+ *
927
+ * // Keys can also be fetched manually
928
+ * const [transferPrivateProvingKey, transferPrivateVerifyingKey] = await keyProvider.fetchKeys(
929
+ * CREDITS_PROGRAM_KEYS.transfer_private.prover,
930
+ * CREDITS_PROGRAM_KEYS.transfer_private.verifier,
931
+ * );
932
+ */
933
+ async fetchRemoteKeys(proverUrl, verifierUrl, cacheKey) {
934
+ try {
935
+ // If cache is enabled, check if the keys have already been fetched and return them if they have
936
+ if (this.cacheOption) {
937
+ if (!cacheKey) {
938
+ cacheKey = proverUrl;
939
+ }
940
+ const value = this.cache.get(cacheKey);
941
+ if (typeof value !== "undefined") {
942
+ return [ProvingKey.fromBytes(value[0]), VerifyingKey.fromBytes(value[1])];
943
+ }
944
+ else {
945
+ console.debug("Fetching proving keys from url " + proverUrl);
946
+ const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
947
+ console.debug("Fetching verifying keys " + verifierUrl);
948
+ const verifyingKey = (await this.getVerifyingKey(verifierUrl));
949
+ this.cache.set(cacheKey, [provingKey.toBytes(), verifyingKey.toBytes()]);
950
+ return [provingKey, verifyingKey];
951
+ }
952
+ }
953
+ else {
954
+ // If cache is disabled, fetch the keys and return them
955
+ const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
956
+ const verifyingKey = (await this.getVerifyingKey(verifierUrl));
957
+ return [provingKey, verifyingKey];
958
+ }
959
+ }
960
+ catch (error) {
961
+ throw new Error(`Error: ${error.message} fetching fee proving and verifying keys from ${proverUrl} and ${verifierUrl}.`);
962
+ }
963
+ }
964
+ /***
965
+ * Fetches the proving key from a remote source.
966
+ *
967
+ * @param proverUrl
968
+ * @param cacheKey
969
+ *
970
+ * @returns {Promise<ProvingKey>} Proving key for the specified program
971
+ */
972
+ async fetchProvingKey(proverUrl, cacheKey) {
973
+ try {
974
+ // If cache is enabled, check if the keys have already been fetched and return them if they have
975
+ if (this.cacheOption) {
976
+ if (!cacheKey) {
977
+ cacheKey = proverUrl;
978
+ }
979
+ const value = this.cache.get(cacheKey);
980
+ if (typeof value !== "undefined") {
981
+ return ProvingKey.fromBytes(value[0]);
982
+ }
983
+ else {
984
+ console.debug("Fetching proving keys from url " + proverUrl);
985
+ const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
986
+ return provingKey;
987
+ }
988
+ }
989
+ else {
990
+ const provingKey = ProvingKey.fromBytes(await this.fetchBytes(proverUrl));
991
+ return provingKey;
992
+ }
993
+ }
994
+ catch (error) {
995
+ throw new Error(`Error: ${error.message} fetching fee proving keys from ${proverUrl}`);
996
+ }
997
+ }
998
+ async fetchCreditsKeys(key) {
999
+ try {
1000
+ if (!this.cache.has(key.locator) || !this.cacheOption) {
1001
+ const verifying_key = key.verifyingKey();
1002
+ const proving_key = await this.fetchProvingKey(key.prover, key.locator);
1003
+ if (this.cacheOption) {
1004
+ this.cache.set(CREDITS_PROGRAM_KEYS.bond_public.locator, [proving_key.toBytes(), verifying_key.toBytes()]);
1005
+ }
1006
+ return [proving_key, verifying_key];
1007
+ }
1008
+ else {
1009
+ const keyPair = this.cache.get(key.locator);
1010
+ return [ProvingKey.fromBytes(keyPair[0]), VerifyingKey.fromBytes(keyPair[1])];
1011
+ }
1012
+ }
1013
+ catch (error) {
1014
+ throw new Error(`Error: fetching credits.aleo keys: ${error.message}`);
1015
+ }
1016
+ }
1017
+ async bondPublicKeys() {
1018
+ return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.bond_public);
1019
+ }
1020
+ bondValidatorKeys() {
1021
+ return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.bond_validator);
1022
+ }
1023
+ claimUnbondPublicKeys() {
1024
+ return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.claim_unbond_public);
1025
+ }
1026
+ /**
1027
+ * Returns the proving and verifying keys for the transfer functions in the credits.aleo program
1028
+ * @param {string} visibility Visibility of the transfer function
1029
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the transfer functions
1030
+ *
1031
+ * @example
1032
+ * // Create a new AleoKeyProvider
1033
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1034
+ * const keyProvider = new AleoKeyProvider();
1035
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1036
+ *
1037
+ * // Initialize a program manager with the key provider to automatically fetch keys for value transfers
1038
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1039
+ * programManager.transfer(1, "aleo166q6ww6688cug7qxwe7nhctjpymydwzy2h7rscfmatqmfwnjvggqcad0at", "public", 0.5);
1040
+ *
1041
+ * // Keys can also be fetched manually
1042
+ * const [transferPublicProvingKey, transferPublicVerifyingKey] = await keyProvider.transferKeys("public");
1043
+ */
1044
+ async transferKeys(visibility) {
1045
+ if (PRIVATE_TRANSFER.has(visibility)) {
1046
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_private);
1047
+ }
1048
+ else if (PRIVATE_TO_PUBLIC_TRANSFER.has(visibility)) {
1049
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_private_to_public);
1050
+ }
1051
+ else if (PUBLIC_TRANSFER.has(visibility)) {
1052
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_public);
1053
+ }
1054
+ else if (PUBLIC_TRANSFER_AS_SIGNER.has(visibility)) {
1055
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_public_as_signer);
1056
+ }
1057
+ else if (PUBLIC_TO_PRIVATE_TRANSFER.has(visibility)) {
1058
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.transfer_public_to_private);
1059
+ }
1060
+ else {
1061
+ throw new Error("Invalid visibility type");
1062
+ }
1063
+ }
1064
+ /**
1065
+ * Returns the proving and verifying keys for the join function in the credits.aleo program
1066
+ *
1067
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the join function
1068
+ */
1069
+ async joinKeys() {
1070
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.join);
1071
+ }
1072
+ /**
1073
+ * Returns the proving and verifying keys for the split function in the credits.aleo program
1074
+ *
1075
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the split function
1076
+ * */
1077
+ async splitKeys() {
1078
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.split);
1079
+ }
1080
+ /**
1081
+ * Returns the proving and verifying keys for the fee_private function in the credits.aleo program
1082
+ *
1083
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the fee function
1084
+ */
1085
+ async feePrivateKeys() {
1086
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.fee_private);
1087
+ }
1088
+ /**
1089
+ * Returns the proving and verifying keys for the fee_public function in the credits.aleo program
1090
+ *
1091
+ * @returns {Promise<FunctionKeyPair>} Proving and verifying keys for the fee function
1092
+ */
1093
+ async feePublicKeys() {
1094
+ return await this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.fee_public);
1095
+ }
1096
+ /**
1097
+ * Gets a verifying key. If the verifying key is for a credits.aleo function, get it from the wasm cache otherwise
1098
+ *
1099
+ * @returns {Promise<VerifyingKey>} Verifying key for the function
1100
+ */
1101
+ // attempt to fetch it from the network
1102
+ async getVerifyingKey(verifierUri) {
1103
+ switch (verifierUri) {
1104
+ case CREDITS_PROGRAM_KEYS.bond_public.verifier:
1105
+ return CREDITS_PROGRAM_KEYS.bond_public.verifyingKey();
1106
+ case CREDITS_PROGRAM_KEYS.bond_validator.verifier:
1107
+ return CREDITS_PROGRAM_KEYS.bond_validator.verifyingKey();
1108
+ case CREDITS_PROGRAM_KEYS.claim_unbond_public.verifier:
1109
+ return CREDITS_PROGRAM_KEYS.claim_unbond_public.verifyingKey();
1110
+ case CREDITS_PROGRAM_KEYS.fee_private.verifier:
1111
+ return CREDITS_PROGRAM_KEYS.fee_private.verifyingKey();
1112
+ case CREDITS_PROGRAM_KEYS.fee_public.verifier:
1113
+ return CREDITS_PROGRAM_KEYS.fee_public.verifyingKey();
1114
+ case CREDITS_PROGRAM_KEYS.inclusion.verifier:
1115
+ return CREDITS_PROGRAM_KEYS.inclusion.verifyingKey();
1116
+ case CREDITS_PROGRAM_KEYS.join.verifier:
1117
+ return CREDITS_PROGRAM_KEYS.join.verifyingKey();
1118
+ case CREDITS_PROGRAM_KEYS.set_validator_state.verifier:
1119
+ return CREDITS_PROGRAM_KEYS.set_validator_state.verifyingKey();
1120
+ case CREDITS_PROGRAM_KEYS.split.verifier:
1121
+ return CREDITS_PROGRAM_KEYS.split.verifyingKey();
1122
+ case CREDITS_PROGRAM_KEYS.transfer_private.verifier:
1123
+ return CREDITS_PROGRAM_KEYS.transfer_private.verifyingKey();
1124
+ case CREDITS_PROGRAM_KEYS.transfer_private_to_public.verifier:
1125
+ return CREDITS_PROGRAM_KEYS.transfer_private_to_public.verifyingKey();
1126
+ case CREDITS_PROGRAM_KEYS.transfer_public.verifier:
1127
+ return CREDITS_PROGRAM_KEYS.transfer_public.verifyingKey();
1128
+ case CREDITS_PROGRAM_KEYS.transfer_public_as_signer.verifier:
1129
+ return CREDITS_PROGRAM_KEYS.transfer_public_as_signer.verifyingKey();
1130
+ case CREDITS_PROGRAM_KEYS.transfer_public_to_private.verifier:
1131
+ return CREDITS_PROGRAM_KEYS.transfer_public_to_private.verifyingKey();
1132
+ case CREDITS_PROGRAM_KEYS.unbond_public.verifier:
1133
+ return CREDITS_PROGRAM_KEYS.unbond_public.verifyingKey();
1134
+ default:
1135
+ try {
1136
+ /// Try to fetch the verifying key from the network as a string
1137
+ const response = await get(verifierUri);
1138
+ const text = await response.text();
1139
+ return VerifyingKey.fromString(text);
1140
+ }
1141
+ catch (e) {
1142
+ /// If that fails, try to fetch the verifying key from the network as bytes
1143
+ try {
1144
+ return VerifyingKey.fromBytes(await this.fetchBytes(verifierUri));
1145
+ }
1146
+ catch (inner) {
1147
+ throw new Error("Invalid verifying key. Error: " + inner.message);
1148
+ }
1149
+ }
1150
+ }
1151
+ }
1152
+ unBondPublicKeys() {
1153
+ return this.fetchCreditsKeys(CREDITS_PROGRAM_KEYS.unbond_public);
1154
+ }
1155
+ }
1156
+
1157
+ /**
1158
+ * The ProgramManager class is used to execute and deploy programs on the Aleo network and create value transfers.
1159
+ */
1160
+ class ProgramManager {
1161
+ account;
1162
+ keyProvider;
1163
+ host;
1164
+ networkClient;
1165
+ recordProvider;
1166
+ /** Create a new instance of the ProgramManager
1167
+ *
1168
+ * @param { string | undefined } host A host uri running the official Aleo API
1169
+ * @param { FunctionKeyProvider | undefined } keyProvider A key provider that implements {@link FunctionKeyProvider} interface
1170
+ * @param { RecordProvider | undefined } recordProvider A record provider that implements {@link RecordProvider} interface
1171
+ */
1172
+ constructor(host, keyProvider, recordProvider) {
1173
+ this.host = host ? host : 'https://api.explorer.provable.com/v1';
1174
+ this.networkClient = new AleoNetworkClient(this.host);
1175
+ this.keyProvider = keyProvider ? keyProvider : new AleoKeyProvider();
1176
+ this.recordProvider = recordProvider;
1177
+ }
1178
+ /**
1179
+ * Set the account to use for transaction submission to the Aleo network
1180
+ *
1181
+ * @param {Account} account Account to use for transaction submission
1182
+ */
1183
+ setAccount(account) {
1184
+ this.account = account;
1185
+ }
1186
+ /**
1187
+ * Set the key provider that provides the proving and verifying keys for programs
1188
+ *
1189
+ * @param {FunctionKeyProvider} keyProvider
1190
+ */
1191
+ setKeyProvider(keyProvider) {
1192
+ this.keyProvider = keyProvider;
1193
+ }
1194
+ /**
1195
+ * Set the host peer to use for transaction submission to the Aleo network
1196
+ *
1197
+ * @param host {string} Peer url to use for transaction submission
1198
+ */
1199
+ setHost(host) {
1200
+ this.host = host;
1201
+ this.networkClient.setHost(host);
1202
+ }
1203
+ /**
1204
+ * Set the record provider that provides records for transactions
1205
+ *
1206
+ * @param {RecordProvider} recordProvider
1207
+ */
1208
+ setRecordProvider(recordProvider) {
1209
+ this.recordProvider = recordProvider;
1210
+ }
1211
+ /**
1212
+ * Deploy an Aleo program to the Aleo network
1213
+ *
1214
+ * @param {string} program Program source code
1215
+ * @param {number} fee Fee to pay for the transaction
1216
+ * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
1217
+ * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for searching for a record to use
1218
+ * pay the deployment fee
1219
+ * @param {string | RecordPlaintext | undefined} feeRecord Optional Fee record to use for the transaction
1220
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the transaction
1221
+ * @returns {string} The transaction id of the deployed program or a failure message from the network
1222
+ *
1223
+ * @example
1224
+ * // Create a new NetworkClient, KeyProvider, and RecordProvider
1225
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1226
+ * const keyProvider = new AleoKeyProvider();
1227
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1228
+ *
1229
+ * // Initialize a program manager with the key provider to automatically fetch keys for deployments
1230
+ * 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";
1231
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1232
+ *
1233
+ * // Define a fee in credits
1234
+ * const fee = 1.2;
1235
+ *
1236
+ * // Deploy the program
1237
+ * const tx_id = await programManager.deploy(program, fee);
1238
+ *
1239
+ * // Verify the transaction was successful
1240
+ * const transaction = await programManager.networkClient.getTransaction(tx_id);
1241
+ */
1242
+ async deploy(program, fee, privateFee, recordSearchParams, feeRecord, privateKey) {
1243
+ // Ensure the program is valid and does not exist on the network
1244
+ try {
1245
+ const programObject = Program.fromString(program);
1246
+ let programSource;
1247
+ try {
1248
+ programSource = await this.networkClient.getProgram(programObject.id());
1249
+ }
1250
+ catch (e) {
1251
+ // Program does not exist on the network, deployment can proceed
1252
+ console.log(`Program ${programObject.id()} does not exist on the network, deploying...`);
1253
+ }
1254
+ if (typeof programSource == "string") {
1255
+ throw (`Program ${programObject.id()} already exists on the network, please rename your program`);
1256
+ }
1257
+ }
1258
+ catch (e) {
1259
+ logAndThrow(`Error validating program: ${e.message}`);
1260
+ }
1261
+ // Get the private key from the account if it is not provided in the parameters
1262
+ let deploymentPrivateKey = privateKey;
1263
+ if (typeof privateKey === "undefined" && typeof this.account !== "undefined") {
1264
+ deploymentPrivateKey = this.account.privateKey();
1265
+ }
1266
+ if (typeof deploymentPrivateKey === "undefined") {
1267
+ throw ("No private key provided and no private key set in the ProgramManager");
1268
+ }
1269
+ // Get the fee record from the account if it is not provided in the parameters
1270
+ try {
1271
+ feeRecord = privateFee ? await this.getCreditsRecord(fee, [], feeRecord, recordSearchParams) : undefined;
1272
+ }
1273
+ catch (e) {
1274
+ 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.`);
1275
+ }
1276
+ // Get the proving and verifying keys from the key provider
1277
+ let feeKeys;
1278
+ try {
1279
+ feeKeys = privateFee ? await this.keyProvider.feePrivateKeys() : await this.keyProvider.feePublicKeys();
1280
+ }
1281
+ catch (e) {
1282
+ logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
1283
+ }
1284
+ const [feeProvingKey, feeVerifyingKey] = feeKeys;
1285
+ // Resolve the program imports if they exist
1286
+ let imports;
1287
+ try {
1288
+ imports = await this.networkClient.getProgramImports(program);
1289
+ }
1290
+ catch (e) {
1291
+ 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.`);
1292
+ }
1293
+ // Build a deployment transaction and submit it to the network
1294
+ const tx = await ProgramManager$1.buildDeploymentTransaction(deploymentPrivateKey, program, fee, feeRecord, this.host, imports, feeProvingKey, feeVerifyingKey);
1295
+ return await this.networkClient.submitTransaction(tx);
1296
+ }
1297
+ /**
1298
+ * Builds an execution transaction for submission to the Aleo network.
1299
+ *
1300
+ * @param {ExecuteOptions} options - The options for the execution transaction.
1301
+ * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error.
1302
+ *
1303
+ * @example
1304
+ * // Create a new NetworkClient, KeyProvider, and RecordProvider using official Aleo record, key, and network providers
1305
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1306
+ * const keyProvider = new AleoKeyProvider();
1307
+ * keyProvider.useCache = true;
1308
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1309
+ *
1310
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions
1311
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1312
+ *
1313
+ * // Build and execute the transaction
1314
+ * const transaction = await programManager.buildExecutionTransaction({
1315
+ * programName: "hello_hello.aleo",
1316
+ * functionName: "hello_hello",
1317
+ * fee: 0.020,
1318
+ * privateFee: false,
1319
+ * inputs: ["5u32", "5u32"],
1320
+ * keySearchParams: { "cacheKey": "hello_hello:hello" }
1321
+ * });
1322
+ * const result = await programManager.networkClient.submitTransaction(transaction);
1323
+ */
1324
+ async buildExecutionTransaction(options) {
1325
+ // Destructure the options object to access the parameters
1326
+ const { programName, functionName, fee, privateFee, inputs, recordSearchParams, keySearchParams, privateKey, offlineQuery } = options;
1327
+ let feeRecord = options.feeRecord;
1328
+ let provingKey = options.provingKey;
1329
+ let verifyingKey = options.verifyingKey;
1330
+ let program = options.program;
1331
+ let imports = options.imports;
1332
+ // Ensure the function exists on the network
1333
+ if (program === undefined) {
1334
+ try {
1335
+ program = (await this.networkClient.getProgram(programName));
1336
+ }
1337
+ catch (e) {
1338
+ 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.`);
1339
+ }
1340
+ }
1341
+ else if (program instanceof Program) {
1342
+ program = program.toString();
1343
+ }
1344
+ // Get the private key from the account if it is not provided in the parameters
1345
+ let executionPrivateKey = privateKey;
1346
+ if (typeof privateKey === "undefined" && typeof this.account !== "undefined") {
1347
+ executionPrivateKey = this.account.privateKey();
1348
+ }
1349
+ if (typeof executionPrivateKey === "undefined") {
1350
+ throw ("No private key provided and no private key set in the ProgramManager");
1351
+ }
1352
+ // Get the fee record from the account if it is not provided in the parameters
1353
+ try {
1354
+ feeRecord = privateFee ? await this.getCreditsRecord(fee, [], feeRecord, recordSearchParams) : undefined;
1355
+ }
1356
+ catch (e) {
1357
+ 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.`);
1358
+ }
1359
+ // Get the fee proving and verifying keys from the key provider
1360
+ let feeKeys;
1361
+ try {
1362
+ feeKeys = privateFee ? await this.keyProvider.feePrivateKeys() : await this.keyProvider.feePublicKeys();
1363
+ }
1364
+ catch (e) {
1365
+ logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
1366
+ }
1367
+ const [feeProvingKey, feeVerifyingKey] = feeKeys;
1368
+ // If the function proving and verifying keys are not provided, attempt to find them using the key provider
1369
+ if (!provingKey || !verifyingKey) {
1370
+ try {
1371
+ [provingKey, verifyingKey] = await this.keyProvider.functionKeys(keySearchParams);
1372
+ }
1373
+ catch (e) {
1374
+ console.log(`Function keys not found. Key finder response: '${e}'. The function keys will be synthesized`);
1375
+ }
1376
+ }
1377
+ // Resolve the program imports if they exist
1378
+ const numberOfImports = Program.fromString(program).getImports().length;
1379
+ if (numberOfImports > 0 && !imports) {
1380
+ try {
1381
+ imports = await this.networkClient.getProgramImports(programName);
1382
+ }
1383
+ catch (e) {
1384
+ 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.`);
1385
+ }
1386
+ }
1387
+ // Build an execution transaction and submit it to the network
1388
+ return await ProgramManager$1.buildExecutionTransaction(executionPrivateKey, program, functionName, inputs, fee, feeRecord, this.host, imports, provingKey, verifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery);
1389
+ }
1390
+ /**
1391
+ * Builds an execution transaction for submission to the Aleo network.
1392
+ *
1393
+ * @param {ExecuteOptions} options - The options for the execution transaction.
1394
+ * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error.
1395
+ *
1396
+ * @example
1397
+ * // Create a new NetworkClient, KeyProvider, and RecordProvider using official Aleo record, key, and network providers
1398
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1399
+ * const keyProvider = new AleoKeyProvider();
1400
+ * keyProvider.useCache = true;
1401
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1402
+ *
1403
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions
1404
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1405
+ *
1406
+ * // Build and execute the transaction
1407
+ * const transaction = await programManager.execute({
1408
+ * programName: "hello_hello.aleo",
1409
+ * functionName: "hello_hello",
1410
+ * fee: 0.020,
1411
+ * privateFee: false,
1412
+ * inputs: ["5u32", "5u32"],
1413
+ * keySearchParams: { "cacheKey": "hello_hello:hello" }
1414
+ * });
1415
+ * const result = await programManager.networkClient.submitTransaction(transaction);
1416
+ */
1417
+ async execute(options) {
1418
+ const tx = await this.buildExecutionTransaction(options);
1419
+ return await this.networkClient.submitTransaction(tx);
1420
+ }
1421
+ /**
1422
+ * Run an Aleo program in offline mode
1423
+ *
1424
+ * @param {string} program Program source code containing the function to be executed
1425
+ * @param {string} function_name Function name to execute
1426
+ * @param {string[]} inputs Inputs to the function
1427
+ * @param {number} proveExecution Whether to prove the execution of the function and return an execution transcript
1428
+ * that contains the proof.
1429
+ * @param {string[] | undefined} imports Optional imports to the program
1430
+ * @param {KeySearchParams | undefined} keySearchParams Optional parameters for finding the matching proving &
1431
+ * verifying keys for the function
1432
+ * @param {ProvingKey | undefined} provingKey Optional proving key to use for the transaction
1433
+ * @param {VerifyingKey | undefined} verifyingKey Optional verifying key to use for the transaction
1434
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the transaction
1435
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1436
+ * @returns {Promise<string>}
1437
+ *
1438
+ * @example
1439
+ * import { Account, Program } from '@provablehq/sdk';
1440
+ *
1441
+ * /// Create the source for the "helloworld" program
1442
+ * 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";
1443
+ * const programManager = new ProgramManager();
1444
+ *
1445
+ * /// Create a temporary account for the execution of the program
1446
+ * const account = new Account();
1447
+ * programManager.setAccount(account);
1448
+ *
1449
+ * /// Get the response and ensure that the program executed correctly
1450
+ * const executionResponse = await programManager.run(program, "hello", ["5u32", "5u32"]);
1451
+ * const result = executionResponse.getOutputs();
1452
+ * assert(result === ["10u32"]);
1453
+ */
1454
+ async run(program, function_name, inputs, proveExecution, imports, keySearchParams, provingKey, verifyingKey, privateKey, offlineQuery) {
1455
+ // Get the private key from the account if it is not provided in the parameters
1456
+ let executionPrivateKey = privateKey;
1457
+ if (typeof privateKey === "undefined" && typeof this.account !== "undefined") {
1458
+ executionPrivateKey = this.account.privateKey();
1459
+ }
1460
+ if (typeof executionPrivateKey === "undefined") {
1461
+ throw ("No private key provided and no private key set in the ProgramManager");
1462
+ }
1463
+ // If the function proving and verifying keys are not provided, attempt to find them using the key provider
1464
+ if (!provingKey || !verifyingKey) {
1465
+ try {
1466
+ [provingKey, verifyingKey] = await this.keyProvider.functionKeys(keySearchParams);
1467
+ }
1468
+ catch (e) {
1469
+ console.log(`Function keys not found. Key finder response: '${e}'. The function keys will be synthesized`);
1470
+ }
1471
+ }
1472
+ // Run the program offline and return the result
1473
+ console.log("Running program offline");
1474
+ console.log("Proving key: ", provingKey);
1475
+ console.log("Verifying key: ", verifyingKey);
1476
+ return ProgramManager$1.executeFunctionOffline(executionPrivateKey, program, function_name, inputs, proveExecution, false, imports, provingKey, verifyingKey, this.host, offlineQuery);
1477
+ }
1478
+ /**
1479
+ * Join two credits records into a single credits record
1480
+ *
1481
+ * @param {RecordPlaintext | string} recordOne First credits record to join
1482
+ * @param {RecordPlaintext | string} recordTwo Second credits record to join
1483
+ * @param {number} fee Fee in credits pay for the join transaction
1484
+ * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
1485
+ * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the fee record to use
1486
+ * to pay the fee for the join transaction
1487
+ * @param {RecordPlaintext | string | undefined} feeRecord Fee record to use for the join transaction
1488
+ * @param {PrivateKey | undefined} privateKey Private key to use for the join transaction
1489
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1490
+ * @returns {Promise<string>}
1491
+ */
1492
+ async join(recordOne, recordTwo, fee, privateFee, recordSearchParams, feeRecord, privateKey, offlineQuery) {
1493
+ // Get the private key from the account if it is not provided in the parameters
1494
+ let executionPrivateKey = privateKey;
1495
+ if (typeof privateKey === "undefined" && typeof this.account !== "undefined") {
1496
+ executionPrivateKey = this.account.privateKey();
1497
+ }
1498
+ if (typeof executionPrivateKey === "undefined") {
1499
+ throw ("No private key provided and no private key set in the ProgramManager");
1500
+ }
1501
+ // Get the proving and verifying keys from the key provider
1502
+ let feeKeys;
1503
+ let joinKeys;
1504
+ try {
1505
+ feeKeys = privateFee ? await this.keyProvider.feePrivateKeys() : await this.keyProvider.feePublicKeys();
1506
+ joinKeys = await this.keyProvider.joinKeys();
1507
+ }
1508
+ catch (e) {
1509
+ logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
1510
+ }
1511
+ const [feeProvingKey, feeVerifyingKey] = feeKeys;
1512
+ const [joinProvingKey, joinVerifyingKey] = joinKeys;
1513
+ // Get the fee record from the account if it is not provided in the parameters
1514
+ try {
1515
+ feeRecord = privateFee ? await this.getCreditsRecord(fee, [], feeRecord, recordSearchParams) : undefined;
1516
+ }
1517
+ catch (e) {
1518
+ 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.`);
1519
+ }
1520
+ // Validate the records provided are valid plaintext records
1521
+ try {
1522
+ recordOne = recordOne instanceof RecordPlaintext ? recordOne : RecordPlaintext.fromString(recordOne);
1523
+ recordTwo = recordTwo instanceof RecordPlaintext ? recordTwo : RecordPlaintext.fromString(recordTwo);
1524
+ }
1525
+ catch (e) {
1526
+ logAndThrow('Records provided are not valid. Please ensure they are valid plaintext records.');
1527
+ }
1528
+ // Build an execution transaction and submit it to the network
1529
+ const tx = await ProgramManager$1.buildJoinTransaction(executionPrivateKey, recordOne, recordTwo, fee, feeRecord, this.host, joinProvingKey, joinVerifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery);
1530
+ return await this.networkClient.submitTransaction(tx);
1531
+ }
1532
+ /**
1533
+ * Split credits into two new credits records
1534
+ *
1535
+ * @param {number} splitAmount Amount in microcredits to split from the original credits record
1536
+ * @param {RecordPlaintext | string} amountRecord Amount record to use for the split transaction
1537
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the split transaction
1538
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1539
+ * @returns {Promise<string>}
1540
+ *
1541
+ * @example
1542
+ * // Create a new NetworkClient, KeyProvider, and RecordProvider
1543
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1544
+ * const keyProvider = new AleoKeyProvider();
1545
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1546
+ *
1547
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions
1548
+ * const programName = "hello_hello.aleo";
1549
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1550
+ * const record = "{ owner: aleo184vuwr5u7u0ha5f5k44067dd2uaqewxx6pe5ltha5pv99wvhfqxqv339h4.private, microcredits: 45000000u64.private, _nonce: 4106205762862305308495708971985748592380064201230396559307556388725936304984group.public}"
1551
+ * const tx_id = await programManager.split(25000000, record);
1552
+ * const transaction = await programManager.networkClient.getTransaction(tx_id);
1553
+ */
1554
+ async split(splitAmount, amountRecord, privateKey, offlineQuery) {
1555
+ // Get the private key from the account if it is not provided in the parameters
1556
+ let executionPrivateKey = privateKey;
1557
+ if (typeof executionPrivateKey === "undefined" && typeof this.account !== "undefined") {
1558
+ executionPrivateKey = this.account.privateKey();
1559
+ }
1560
+ if (typeof executionPrivateKey === "undefined") {
1561
+ throw ("No private key provided and no private key set in the ProgramManager");
1562
+ }
1563
+ // Get the split keys from the key provider
1564
+ let splitKeys;
1565
+ try {
1566
+ splitKeys = await this.keyProvider.splitKeys();
1567
+ }
1568
+ catch (e) {
1569
+ logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
1570
+ }
1571
+ const [splitProvingKey, splitVerifyingKey] = splitKeys;
1572
+ // Validate the record to be split
1573
+ try {
1574
+ amountRecord = amountRecord instanceof RecordPlaintext ? amountRecord : RecordPlaintext.fromString(amountRecord);
1575
+ }
1576
+ catch (e) {
1577
+ logAndThrow("Record provided is not valid. Please ensure it is a valid plaintext record.");
1578
+ }
1579
+ // Build an execution transaction and submit it to the network
1580
+ const tx = await ProgramManager$1.buildSplitTransaction(executionPrivateKey, splitAmount, amountRecord, this.host, splitProvingKey, splitVerifyingKey, offlineQuery);
1581
+ return await this.networkClient.submitTransaction(tx);
1582
+ }
1583
+ /**
1584
+ * Pre-synthesize proving and verifying keys for a program
1585
+ *
1586
+ * @param program {string} The program source code to synthesize keys for
1587
+ * @param function_id {string} The function id to synthesize keys for
1588
+ * @param inputs {Array<string>} Sample inputs to the function
1589
+ * @param privateKey {PrivateKey | undefined} Optional private key to use for the key synthesis
1590
+ *
1591
+ * @returns {Promise<FunctionKeyPair>}
1592
+ */
1593
+ async synthesizeKeys(program, function_id, inputs, privateKey) {
1594
+ // Resolve the program imports if they exist
1595
+ let imports;
1596
+ let executionPrivateKey = privateKey;
1597
+ if (typeof executionPrivateKey === "undefined") {
1598
+ if (typeof this.account !== "undefined") {
1599
+ executionPrivateKey = this.account.privateKey();
1600
+ }
1601
+ else {
1602
+ executionPrivateKey = new PrivateKey();
1603
+ }
1604
+ }
1605
+ // Attempt to run an offline execution of the program and extract the proving and verifying keys
1606
+ try {
1607
+ imports = await this.networkClient.getProgramImports(program);
1608
+ const keyPair = await ProgramManager$1.synthesizeKeyPair(executionPrivateKey, program, function_id, inputs, imports);
1609
+ return [keyPair.provingKey(), keyPair.verifyingKey()];
1610
+ }
1611
+ catch (e) {
1612
+ logAndThrow(`Could not synthesize keys - error ${e.message}. Please ensure the program is valid and the inputs are correct.`);
1613
+ }
1614
+ }
1615
+ /**
1616
+ * Build a transaction to transfer credits to another account for later submission to the Aleo network
1617
+ *
1618
+ * @param {number} amount The amount of credits to transfer
1619
+ * @param {string} recipient The recipient of the transfer
1620
+ * @param {string} transferType The type of transfer to perform - options: 'private', 'privateToPublic', 'public', 'publicToPrivate'
1621
+ * @param {number} fee The fee to pay for the transfer
1622
+ * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
1623
+ * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the amount and fee
1624
+ * records for the transfer transaction
1625
+ * @param {RecordPlaintext | string} amountRecord Optional amount record to use for the transfer
1626
+ * @param {RecordPlaintext | string} feeRecord Optional fee record to use for the transfer
1627
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
1628
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1629
+ * @returns {Promise<string>} The transaction id of the transfer transaction
1630
+ *
1631
+ * @example
1632
+ * // Create a new NetworkClient, KeyProvider, and RecordProvider
1633
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1634
+ * const keyProvider = new AleoKeyProvider();
1635
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1636
+ *
1637
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions
1638
+ * const programName = "hello_hello.aleo";
1639
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1640
+ * await programManager.initialize();
1641
+ * const tx_id = await programManager.transfer(1, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "private", 0.2)
1642
+ * const transaction = await programManager.networkClient.getTransaction(tx_id);
1643
+ */
1644
+ async buildTransferTransaction(amount, recipient, transferType, fee, privateFee, recordSearchParams, amountRecord, feeRecord, privateKey, offlineQuery) {
1645
+ // Validate the transfer type
1646
+ transferType = validateTransferType(transferType);
1647
+ // Get the private key from the account if it is not provided in the parameters
1648
+ let executionPrivateKey = privateKey;
1649
+ if (typeof executionPrivateKey === "undefined" && typeof this.account !== "undefined") {
1650
+ executionPrivateKey = this.account.privateKey();
1651
+ }
1652
+ if (typeof executionPrivateKey === "undefined") {
1653
+ throw ("No private key provided and no private key set in the ProgramManager");
1654
+ }
1655
+ // Get the proving and verifying keys from the key provider
1656
+ let feeKeys;
1657
+ let transferKeys;
1658
+ try {
1659
+ feeKeys = privateFee ? await this.keyProvider.feePrivateKeys() : await this.keyProvider.feePublicKeys();
1660
+ transferKeys = await this.keyProvider.transferKeys(transferType);
1661
+ }
1662
+ catch (e) {
1663
+ logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
1664
+ }
1665
+ const [feeProvingKey, feeVerifyingKey] = feeKeys;
1666
+ const [transferProvingKey, transferVerifyingKey] = transferKeys;
1667
+ // Get the amount and fee record from the account if it is not provided in the parameters
1668
+ try {
1669
+ // Track the nonces of the records found so no duplicate records are used
1670
+ const nonces = [];
1671
+ if (requiresAmountRecord(transferType)) {
1672
+ // If the transfer type is private and requires an amount record, get it from the record provider
1673
+ amountRecord = await this.getCreditsRecord(fee, [], amountRecord, recordSearchParams);
1674
+ nonces.push(amountRecord.nonce());
1675
+ }
1676
+ else {
1677
+ amountRecord = undefined;
1678
+ }
1679
+ feeRecord = privateFee ? await this.getCreditsRecord(fee, nonces, feeRecord, recordSearchParams) : undefined;
1680
+ }
1681
+ catch (e) {
1682
+ 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.`);
1683
+ }
1684
+ // Build an execution transaction and submit it to the network
1685
+ return await ProgramManager$1.buildTransferTransaction(executionPrivateKey, amount, recipient, transferType, amountRecord, fee, feeRecord, this.host, transferProvingKey, transferVerifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery);
1686
+ }
1687
+ /**
1688
+ * Build a transfer_public transaction to transfer credits to another account for later submission to the Aleo network
1689
+ *
1690
+ * @param {number} amount The amount of credits to transfer
1691
+ * @param {string} recipient The recipient of the transfer
1692
+ * @param {string} transferType The type of transfer to perform - options: 'private', 'privateToPublic', 'public', 'publicToPrivate'
1693
+ * @param {number} fee The fee to pay for the transfer
1694
+ * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
1695
+ * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the amount and fee
1696
+ * records for the transfer transaction
1697
+ * @param {RecordPlaintext | string} amountRecord Optional amount record to use for the transfer
1698
+ * @param {RecordPlaintext | string} feeRecord Optional fee record to use for the transfer
1699
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
1700
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1701
+ * @returns {Promise<string>} The transaction id of the transfer transaction
1702
+ */
1703
+ async buildTransferPublicTransaction(amount, recipient, fee, privateKey, offlineQuery) {
1704
+ return this.buildTransferTransaction(amount, recipient, "public", fee, false, undefined, undefined, undefined, privateKey, offlineQuery);
1705
+ }
1706
+ /**
1707
+ * Build a transfer_public_as_signer transaction to transfer credits to another account for later submission to the Aleo network
1708
+ *
1709
+ * @param {number} amount The amount of credits to transfer
1710
+ * @param {string} recipient The recipient of the transfer
1711
+ * @param {string} transferType The type of transfer to perform - options: 'private', 'privateToPublic', 'public', 'publicToPrivate'
1712
+ * @param {number} fee The fee to pay for the transfer
1713
+ * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
1714
+ * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the amount and fee
1715
+ * records for the transfer transaction
1716
+ * @param {RecordPlaintext | string} amountRecord Optional amount record to use for the transfer
1717
+ * @param {RecordPlaintext | string} feeRecord Optional fee record to use for the transfer
1718
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
1719
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1720
+ * @returns {Promise<string>} The transaction id of the transfer transaction
1721
+ */
1722
+ async buildTransferPublicAsSignerTransaction(amount, recipient, fee, privateKey, offlineQuery) {
1723
+ return this.buildTransferTransaction(amount, recipient, "public", fee, false, undefined, undefined, undefined, privateKey, offlineQuery);
1724
+ }
1725
+ /**
1726
+ * Transfer credits to another account
1727
+ *
1728
+ * @param {number} amount The amount of credits to transfer
1729
+ * @param {string} recipient The recipient of the transfer
1730
+ * @param {string} transferType The type of transfer to perform - options: 'private', 'privateToPublic', 'public', 'publicToPrivate'
1731
+ * @param {number} fee The fee to pay for the transfer
1732
+ * @param {boolean} privateFee Use a private record to pay the fee. If false this will use the account's public credit balance
1733
+ * @param {RecordSearchParams | undefined} recordSearchParams Optional parameters for finding the amount and fee
1734
+ * records for the transfer transaction
1735
+ * @param {RecordPlaintext | string} amountRecord Optional amount record to use for the transfer
1736
+ * @param {RecordPlaintext | string} feeRecord Optional fee record to use for the transfer
1737
+ * @param {PrivateKey | undefined} privateKey Optional private key to use for the transfer transaction
1738
+ * @param {OfflineQuery | undefined} offlineQuery Optional offline query if creating transactions in an offline environment
1739
+ * @returns {Promise<string>} The transaction id of the transfer transaction
1740
+ *
1741
+ * @example
1742
+ * // Create a new NetworkClient, KeyProvider, and RecordProvider
1743
+ * const networkClient = new AleoNetworkClient("https://api.explorer.provable.com/v1");
1744
+ * const keyProvider = new AleoKeyProvider();
1745
+ * const recordProvider = new NetworkRecordProvider(account, networkClient);
1746
+ *
1747
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions
1748
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
1749
+ * await programManager.initialize();
1750
+ * const tx_id = await programManager.transfer(1, "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "private", 0.2)
1751
+ * const transaction = await programManager.networkClient.getTransaction(tx_id);
1752
+ */
1753
+ async transfer(amount, recipient, transferType, fee, privateFee, recordSearchParams, amountRecord, feeRecord, privateKey, offlineQuery) {
1754
+ const tx = await this.buildTransferTransaction(amount, recipient, transferType, fee, privateFee, recordSearchParams, amountRecord, feeRecord, privateKey, offlineQuery);
1755
+ return await this.networkClient.submitTransaction(tx);
1756
+ }
1757
+ /**
1758
+ * Build transaction to bond credits to a validator for later submission to the Aleo Network
1759
+ *
1760
+ * @example
1761
+ * // Create a keyProvider to handle key management
1762
+ * const keyProvider = new AleoKeyProvider();
1763
+ * keyProvider.useCache = true;
1764
+ *
1765
+ * // Create a new ProgramManager with the key that will be used to bond credits
1766
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1767
+ * programManager.setAccount(new Account("YourPrivateKey"));
1768
+ *
1769
+ * // Create the bonding transaction object for later submission
1770
+ * const tx = await programManager.buildBondPublicTransaction("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
1771
+ * console.log(tx);
1772
+ *
1773
+ * // The transaction can be later submitted to the network using the network client.
1774
+ * const result = await programManager.networkClient.submitTransaction(tx);
1775
+ *
1776
+ * @returns string
1777
+ * @param {string} staker_address Address of the staker who is bonding the credits
1778
+ * @param {string} validator_address Address of the validator to bond to, if this address is the same as the staker (i.e. the
1779
+ * executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently
1780
+ * requires a minimum of 10,000,000 credits to bond (subject to change). If the address is specified is an existing
1781
+ * validator and is different from the address of the executor of this function, it will bond the credits to that
1782
+ * validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
1783
+ * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
1784
+ * @param {number} amount The amount of credits to bond
1785
+ * @param {Partial<ExecuteOptions>} options - Override default execution options.
1786
+ */
1787
+ async buildBondPublicTransaction(staker_address, validator_address, withdrawal_address, amount, options = {}) {
1788
+ const scaledAmount = Math.trunc(amount * 1000000);
1789
+ const { programName = "credits.aleo", functionName = "bond_public", fee = options.fee || 0.86, privateFee = false, inputs = [staker_address, validator_address, withdrawal_address, `${scaledAmount.toString()}u64`], keySearchParams = new AleoKeyProviderParams({
1790
+ proverUri: CREDITS_PROGRAM_KEYS.bond_public.prover,
1791
+ verifierUri: CREDITS_PROGRAM_KEYS.bond_public.verifier,
1792
+ cacheKey: "credits.aleo/bond_public"
1793
+ }), program = this.creditsProgram(), ...additionalOptions } = options;
1794
+ const executeOptions = {
1795
+ programName,
1796
+ functionName,
1797
+ fee,
1798
+ privateFee,
1799
+ inputs,
1800
+ keySearchParams,
1801
+ ...additionalOptions
1802
+ };
1803
+ return await this.buildExecutionTransaction(executeOptions);
1804
+ }
1805
+ /**
1806
+ * Bond credits to validator.
1807
+ *
1808
+ * @example
1809
+ * // Create a keyProvider to handle key management
1810
+ * const keyProvider = new AleoKeyProvider();
1811
+ * keyProvider.useCache = true;
1812
+ *
1813
+ * // Create a new ProgramManager with the key that will be used to bond credits
1814
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1815
+ * programManager.setAccount(new Account("YourPrivateKey"));
1816
+ *
1817
+ * // Create the bonding transaction
1818
+ * const tx_id = await programManager.bondPublic("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
1819
+ *
1820
+ * @returns string
1821
+ * @param {string} staker_address Address of the staker who is bonding the credits
1822
+ * @param {string} validator_address Address of the validator to bond to, if this address is the same as the signer (i.e. the
1823
+ * executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently
1824
+ * requires a minimum of 1,000,000 credits to bond (subject to change). If the address is specified is an existing
1825
+ * validator and is different from the address of the executor of this function, it will bond the credits to that
1826
+ * validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
1827
+ * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
1828
+ * @param {number} amount The amount of credits to bond
1829
+ * @param {Options} options Options for the execution
1830
+ */
1831
+ async bondPublic(staker_address, validator_address, withdrawal_address, amount, options = {}) {
1832
+ const tx = await this.buildBondPublicTransaction(staker_address, validator_address, withdrawal_address, amount, options);
1833
+ return await this.networkClient.submitTransaction(tx);
1834
+ }
1835
+ /**
1836
+ * Build a bond_validator transaction for later submission to the Aleo Network.
1837
+ *
1838
+ * @example
1839
+ * // Create a keyProvider to handle key management
1840
+ * const keyProvider = new AleoKeyProvider();
1841
+ * keyProvider.useCache = true;
1842
+ *
1843
+ * // Create a new ProgramManager with the key that will be used to bond credits
1844
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1845
+ * programManager.setAccount(new Account("YourPrivateKey"));
1846
+ *
1847
+ * // Create the bond validator transaction object for later use.
1848
+ * const tx = await programManager.buildBondValidatorTransaction("aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
1849
+ * console.log(tx);
1850
+ *
1851
+ * // The transaction can later be submitted to the network using the network client.
1852
+ * const tx_id = await programManager.networkClient.submitTransaction(tx);
1853
+ *
1854
+ * @returns string
1855
+ * @param {string} validator_address Address of the validator to bond to, if this address is the same as the staker (i.e. the
1856
+ * executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently
1857
+ * requires a minimum of 10,000,000 credits to bond (subject to change). If the address is specified is an existing
1858
+ * validator and is different from the address of the executor of this function, it will bond the credits to that
1859
+ * validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
1860
+ * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
1861
+ * @param {number} amount The amount of credits to bond
1862
+ * @param {number} commission The commission rate for the validator (must be between 0 and 100 - an error will be thrown if it is not)
1863
+ * @param {Partial<ExecuteOptions>} options - Override default execution options.
1864
+ */
1865
+ async buildBondValidatorTransaction(validator_address, withdrawal_address, amount, commission, options = {}) {
1866
+ const scaledAmount = Math.trunc(amount * 1000000);
1867
+ const adjustedCommission = Math.trunc(commission);
1868
+ const { programName = "credits.aleo", functionName = "bond_validator", fee = options.fee || 0.86, privateFee = false, inputs = [validator_address, withdrawal_address, `${scaledAmount.toString()}u64`, `${adjustedCommission.toString()}u8`], keySearchParams = new AleoKeyProviderParams({
1869
+ proverUri: CREDITS_PROGRAM_KEYS.bond_validator.prover,
1870
+ verifierUri: CREDITS_PROGRAM_KEYS.bond_validator.verifier,
1871
+ cacheKey: "credits.aleo/bond_validator"
1872
+ }), program = this.creditsProgram(), ...additionalOptions } = options;
1873
+ const executeOptions = {
1874
+ programName,
1875
+ functionName,
1876
+ fee,
1877
+ privateFee,
1878
+ inputs,
1879
+ keySearchParams,
1880
+ ...additionalOptions
1881
+ };
1882
+ return await this.buildExecutionTransaction(executeOptions);
1883
+ }
1884
+ /**
1885
+ * Build transaction to bond a validator.
1886
+ *
1887
+ * @example
1888
+ * // Create a keyProvider to handle key management
1889
+ * const keyProvider = new AleoKeyProvider();
1890
+ * keyProvider.useCache = true;
1891
+ *
1892
+ * // Create a new ProgramManager with the key that will be used to bond credits
1893
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1894
+ * programManager.setAccount(new Account("YourPrivateKey"));
1895
+ *
1896
+ * // Create the bonding transaction
1897
+ * const tx_id = await programManager.bondValidator("aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px", "aleo1feya8sjy9k2zflvl2dx39pdsq5tju28elnp2ektnn588uu9ghv8s84msv9", 2000000);
1898
+ *
1899
+ * @returns string
1900
+ * @param {string} validator_address Address of the validator to bond to, if this address is the same as the staker (i.e. the
1901
+ * executor of this function), it will attempt to bond the credits as a validator. Bonding as a validator currently
1902
+ * requires a minimum of 10,000,000 credits to bond (subject to change). If the address is specified is an existing
1903
+ * validator and is different from the address of the executor of this function, it will bond the credits to that
1904
+ * validator's staking committee as a delegator. A minimum of 10 credits is required to bond as a delegator.
1905
+ * @param {string} withdrawal_address Address to withdraw the staked credits to when unbond_public is called.
1906
+ * @param {number} amount The amount of credits to bond
1907
+ * @param {number} commission The commission rate for the validator (must be between 0 and 100 - an error will be thrown if it is not)
1908
+ * @param {Partial<ExecuteOptions>} options - Override default execution options.
1909
+ */
1910
+ async bondValidator(validator_address, withdrawal_address, amount, commission, options = {}) {
1911
+ const tx = await this.buildBondValidatorTransaction(validator_address, withdrawal_address, amount, commission, options);
1912
+ return await this.networkClient.submitTransaction(tx);
1913
+ }
1914
+ /**
1915
+ * Build a transaction to unbond public credits from a validator in the Aleo network.
1916
+ *
1917
+ * @param {string} staker_address - The address of the staker who is unbonding the credits.
1918
+ * @param {number} amount - The amount of credits to unbond (scaled by 1,000,000).
1919
+ * @param {Partial<ExecuteOptions>} options - Override default execution options.
1920
+ * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error message.
1921
+ *
1922
+ * @example
1923
+ * // Create a keyProvider to handle key management.
1924
+ * const keyProvider = new AleoKeyProvider();
1925
+ * keyProvider.useCache = true;
1926
+ *
1927
+ * // Create a new ProgramManager with the key that will be used to unbond credits.
1928
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1929
+ * const tx = await programManager.buildUnbondPublicTransaction("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", 2000000);
1930
+ * console.log(tx);
1931
+ *
1932
+ * // The transaction can be submitted later to the network using the network client.
1933
+ * programManager.networkClient.submitTransaction(tx);
1934
+ */
1935
+ async buildUnbondPublicTransaction(staker_address, amount, options = {}) {
1936
+ const scaledAmount = Math.trunc(amount * 1000000);
1937
+ const { programName = "credits.aleo", functionName = "unbond_public", fee = options.fee || 1.3, privateFee = false, inputs = [staker_address, `${scaledAmount.toString()}u64`], keySearchParams = new AleoKeyProviderParams({
1938
+ proverUri: CREDITS_PROGRAM_KEYS.unbond_public.prover,
1939
+ verifierUri: CREDITS_PROGRAM_KEYS.unbond_public.verifier,
1940
+ cacheKey: "credits.aleo/unbond_public"
1941
+ }), program = this.creditsProgram(), ...additionalOptions } = options;
1942
+ const executeOptions = {
1943
+ programName,
1944
+ functionName,
1945
+ fee,
1946
+ privateFee,
1947
+ inputs,
1948
+ keySearchParams,
1949
+ ...additionalOptions
1950
+ };
1951
+ return this.buildExecutionTransaction(executeOptions);
1952
+ }
1953
+ /**
1954
+ * Unbond a specified amount of staked credits.
1955
+ *
1956
+ * @example
1957
+ * // Create a keyProvider to handle key management
1958
+ * const keyProvider = new AleoKeyProvider();
1959
+ * keyProvider.useCache = true;
1960
+ *
1961
+ * // Create a new ProgramManager with the key that will be used to bond credits
1962
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1963
+ * programManager.setAccount(new Account("YourPrivateKey"));
1964
+ *
1965
+ * // Create the bonding transaction and send it to the network
1966
+ * const tx_id = await programManager.unbondPublic("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j", 10);
1967
+ *
1968
+ * @returns string
1969
+ * @param {string} staker_address Address of the staker who is unbonding the credits
1970
+ * @param {number} amount Amount of credits to unbond. If the address of the executor of this function is an
1971
+ * existing validator, it will subtract this amount of credits from the validator's staked credits. If there are
1972
+ * less than 1,000,000 credits staked pool after the unbond, the validator will be removed from the validator set.
1973
+ * If the address of the executor of this function is not a validator and has credits bonded as a delegator, it will
1974
+ * subtract this amount of credits from the delegator's staked credits. If there are less than 10 credits bonded
1975
+ * after the unbond operation, the delegator will be removed from the validator's staking pool.
1976
+ * @param {ExecuteOptions} options Options for the execution
1977
+ */
1978
+ async unbondPublic(staker_address, amount, options = {}) {
1979
+ const tx = await this.buildUnbondPublicTransaction(staker_address, amount, options);
1980
+ return await this.networkClient.submitTransaction(tx);
1981
+ }
1982
+ /**
1983
+ * Build a transaction to claim unbonded public credits in the Aleo network.
1984
+ *
1985
+ * @param {string} staker_address - The address of the staker who is claiming the credits.
1986
+ * @param {Partial<ExecuteOptions>} options - Override default execution options.
1987
+ * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error message.
1988
+ *
1989
+ * @example
1990
+ * // Create a keyProvider to handle key management
1991
+ * const keyProvider = new AleoKeyProvider();
1992
+ * keyProvider.useCache = true;
1993
+ *
1994
+ * // Create a new ProgramManager with the key that will be used to claim unbonded credits.
1995
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
1996
+ *
1997
+ * // Create the claim unbonded transaction object for later use.
1998
+ * const tx = await programManager.buildClaimUnbondPublicTransaction("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j");
1999
+ * console.log(tx);
2000
+ *
2001
+ * // The transaction can be submitted later to the network using the network client.
2002
+ * programManager.networkClient.submitTransaction(tx);
2003
+ */
2004
+ async buildClaimUnbondPublicTransaction(staker_address, options = {}) {
2005
+ const { programName = "credits.aleo", functionName = "claim_unbond_public", fee = options.fee || 2, privateFee = false, inputs = [staker_address], keySearchParams = new AleoKeyProviderParams({
2006
+ proverUri: CREDITS_PROGRAM_KEYS.claim_unbond_public.prover,
2007
+ verifierUri: CREDITS_PROGRAM_KEYS.claim_unbond_public.verifier,
2008
+ cacheKey: "credits.aleo/claim_unbond_public"
2009
+ }), program = this.creditsProgram(), ...additionalOptions } = options;
2010
+ const executeOptions = {
2011
+ programName,
2012
+ functionName,
2013
+ fee,
2014
+ privateFee,
2015
+ inputs,
2016
+ keySearchParams,
2017
+ ...additionalOptions
2018
+ };
2019
+ return await this.buildExecutionTransaction(executeOptions);
2020
+ }
2021
+ /**
2022
+ * Claim unbonded credits. If credits have been unbonded by the account executing this function, this method will
2023
+ * claim them and add them to the public balance of the account.
2024
+ *
2025
+ * @example
2026
+ * // Create a keyProvider to handle key management
2027
+ * const keyProvider = new AleoKeyProvider();
2028
+ * keyProvider.useCache = true;
2029
+ *
2030
+ * // Create a new ProgramManager with the key that will be used to bond credits
2031
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
2032
+ * programManager.setAccount(new Account("YourPrivateKey"));
2033
+ *
2034
+ * // Create the bonding transaction
2035
+ * const tx_id = await programManager.claimUnbondPublic("aleo1jx8s4dvjepculny4wfrzwyhs3tlyv65r58ns3g6q2gm2esh7ps8sqy9s5j");
2036
+ *
2037
+ * @param {string} staker_address Address of the staker who is claiming the credits
2038
+ * @param {ExecuteOptions} options
2039
+ * @returns string
2040
+ */
2041
+ async claimUnbondPublic(staker_address, options = {}) {
2042
+ const tx = await this.buildClaimUnbondPublicTransaction(staker_address, options);
2043
+ return await this.networkClient.submitTransaction(tx);
2044
+ }
2045
+ /**
2046
+ * Build a set_validator_state transaction for later usage.
2047
+ *
2048
+ * This function allows a validator to set their state to be either opened or closed to new stakers.
2049
+ * When the validator is open to new stakers, any staker (including the validator) can bond or unbond from the validator.
2050
+ * When the validator is closed to new stakers, existing stakers can still bond or unbond from the validator, but new stakers cannot bond.
2051
+ *
2052
+ * This function serves two primary purposes:
2053
+ * 1. Allow a validator to leave the committee, by closing themselves to stakers and then unbonding all of their stakers.
2054
+ * 2. Allow a validator to maintain their % of stake, by closing themselves to allowing more stakers to bond to them.
2055
+ *
2056
+ * @example
2057
+ * // Create a keyProvider to handle key management
2058
+ * const keyProvider = new AleoKeyProvider();
2059
+ * keyProvider.useCache = true;
2060
+ *
2061
+ * // Create a new ProgramManager with the key that will be used to bond credits
2062
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
2063
+ * programManager.setAccount(new Account("ValidatorPrivateKey"));
2064
+ *
2065
+ * // Create the bonding transaction
2066
+ * const tx = await programManager.buildSetValidatorStateTransaction(true);
2067
+ *
2068
+ * // The transaction can be submitted later to the network using the network client.
2069
+ * programManager.networkClient.submitTransaction(tx);
2070
+ *
2071
+ * @returns string
2072
+ * @param {boolean} validator_state
2073
+ * @param {Partial<ExecuteOptions>} options - Override default execution options
2074
+ */
2075
+ async buildSetValidatorStateTransaction(validator_state, options = {}) {
2076
+ const { programName = "credits.aleo", functionName = "set_validator_state", fee = 1, privateFee = false, inputs = [validator_state.toString()], keySearchParams = new AleoKeyProviderParams({
2077
+ proverUri: CREDITS_PROGRAM_KEYS.set_validator_state.prover,
2078
+ verifierUri: CREDITS_PROGRAM_KEYS.set_validator_state.verifier,
2079
+ cacheKey: "credits.aleo/set_validator_state"
2080
+ }), ...additionalOptions } = options;
2081
+ const executeOptions = {
2082
+ programName,
2083
+ functionName,
2084
+ fee,
2085
+ privateFee,
2086
+ inputs,
2087
+ keySearchParams,
2088
+ ...additionalOptions
2089
+ };
2090
+ return await this.execute(executeOptions);
2091
+ }
2092
+ /**
2093
+ * Submit a set_validator_state transaction to the Aleo Network.
2094
+ *
2095
+ * This function allows a validator to set their state to be either opened or closed to new stakers.
2096
+ * When the validator is open to new stakers, any staker (including the validator) can bond or unbond from the validator.
2097
+ * When the validator is closed to new stakers, existing stakers can still bond or unbond from the validator, but new stakers cannot bond.
2098
+ *
2099
+ * This function serves two primary purposes:
2100
+ * 1. Allow a validator to leave the committee, by closing themselves to stakers and then unbonding all of their stakers.
2101
+ * 2. Allow a validator to maintain their % of stake, by closing themselves to allowing more stakers to bond to them.
2102
+ *
2103
+ * @example
2104
+ * // Create a keyProvider to handle key management
2105
+ * const keyProvider = new AleoKeyProvider();
2106
+ * keyProvider.useCache = true;
2107
+ *
2108
+ * // Create a new ProgramManager with the key that will be used to bond credits
2109
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, undefined);
2110
+ * programManager.setAccount(new Account("ValidatorPrivateKey"));
2111
+ *
2112
+ * // Create the bonding transaction
2113
+ * const tx_id = await programManager.setValidatorState(true);
2114
+ *
2115
+ * @returns string
2116
+ * @param {boolean} validator_state
2117
+ * @param {Partial<ExecuteOptions>} options - Override default execution options
2118
+ */
2119
+ async setValidatorState(validator_state, options = {}) {
2120
+ const tx = await this.buildSetValidatorStateTransaction(validator_state, options);
2121
+ return this.networkClient.submitTransaction(tx);
2122
+ }
2123
+ /**
2124
+ * Verify a proof of execution from an offline execution
2125
+ *
2126
+ * @param {executionResponse} executionResponse
2127
+ * @returns {boolean} True if the proof is valid, false otherwise
2128
+ */
2129
+ verifyExecution(executionResponse) {
2130
+ try {
2131
+ const execution = executionResponse.getExecution();
2132
+ const function_id = executionResponse.getFunctionId();
2133
+ const program = executionResponse.getProgram();
2134
+ const verifyingKey = executionResponse.getVerifyingKey();
2135
+ return verifyFunctionExecution(execution, verifyingKey, program, function_id);
2136
+ }
2137
+ catch (e) {
2138
+ console.warn("The execution was not found in the response, cannot verify the execution");
2139
+ return false;
2140
+ }
2141
+ }
2142
+ /**
2143
+ * Create a program object from a program's source code
2144
+ *
2145
+ * @param {string} program Program source code
2146
+ * @returns {Program} The program object
2147
+ */
2148
+ createProgramFromSource(program) {
2149
+ return Program.fromString(program);
2150
+ }
2151
+ /**
2152
+ * Get the credits program object
2153
+ *
2154
+ * @returns {Program} The credits program object
2155
+ */
2156
+ creditsProgram() {
2157
+ return Program.getCreditsProgram();
2158
+ }
2159
+ /**
2160
+ * Verify a program is valid
2161
+ *
2162
+ * @param {string} program The program source code
2163
+ */
2164
+ verifyProgram(program) {
2165
+ try {
2166
+ Program.fromString(program);
2167
+ return true;
2168
+ }
2169
+ catch (e) {
2170
+ return false;
2171
+ }
2172
+ }
2173
+ // Internal utility function for getting a credits.aleo record
2174
+ async getCreditsRecord(amount, nonces, record, params) {
2175
+ try {
2176
+ return record instanceof RecordPlaintext ? record : RecordPlaintext.fromString(record);
2177
+ }
2178
+ catch (e) {
2179
+ try {
2180
+ const recordProvider = this.recordProvider;
2181
+ return (await recordProvider.findCreditsRecord(amount, true, nonces, params));
2182
+ }
2183
+ catch (e) {
2184
+ 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.`);
2185
+ }
2186
+ }
2187
+ }
2188
+ }
2189
+ // Ensure the transfer type requires an amount record
2190
+ function requiresAmountRecord(transferType) {
2191
+ return PRIVATE_TRANSFER_TYPES.has(transferType);
2192
+ }
2193
+ // Validate the transfer type
2194
+ function validateTransferType(transferType) {
2195
+ return VALID_TRANSFER_TYPES.has(transferType) ? transferType :
2196
+ logAndThrow(`Invalid transfer type '${transferType}'. Valid transfer types are 'private', 'privateToPublic', 'public', and 'publicToPrivate'.`);
2197
+ }
2198
+
2199
+ 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 };
2200
+ //# sourceMappingURL=program-manager-a25c2f23.js.map