@provablehq/sdk 0.9.3 → 0.9.4-offline-rc

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