@provablehq/sdk 0.6.13 → 0.7.0

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