@provablehq/sdk 0.7.2 → 0.7.4

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