@provablehq/sdk 0.8.1 → 0.8.2

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