@provablehq/sdk 0.9.10-testnet-rc → 0.9.11

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.
@@ -0,0 +1,8 @@
1
+ interface Networks {
2
+ "testnet": typeof import("../testnet/browser"),
3
+ "mainnet": typeof import("../mainnet/browser"),
4
+ }
5
+
6
+ export { Networks };
7
+
8
+ export declare function loadNetwork<Key extends keyof Networks>(name: Key): Promise<Networks[Key]>;
@@ -0,0 +1,8 @@
1
+ const networks = {
2
+ "testnet": () => import("../testnet/browser.js"),
3
+ "mainnet": () => import("../mainnet/browser.js"),
4
+ };
5
+
6
+ export function loadNetwork(name) {
7
+ return networks[name]();
8
+ }
@@ -0,0 +1,8 @@
1
+ interface Networks {
2
+ "testnet": typeof import("../testnet/node"),
3
+ "mainnet": typeof import("../mainnet/node"),
4
+ }
5
+
6
+ export { Networks };
7
+
8
+ export declare function loadNetwork<Key extends keyof Networks>(name: Key): Promise<Networks[Key]>;
@@ -0,0 +1,8 @@
1
+ const networks = {
2
+ "testnet": () => import("../testnet/node.js"),
3
+ "mainnet": () => import("../mainnet/node.js"),
4
+ };
5
+
6
+ export function loadNetwork(name) {
7
+ return networks[name]();
8
+ }
@@ -37,10 +37,11 @@ import { AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, Cach
37
37
  import { OfflineKeyProvider, OfflineSearchParams } from "./offline-key-provider.js";
38
38
  import { BlockHeightSearch, NetworkRecordProvider, RecordProvider } from "./record-provider.js";
39
39
  import { RecordScanner } from "./record-scanner.js";
40
+ import { SealanceMerkleTree } from "./integrations/sealance/merkle-tree.js";
40
41
  declare function initializeWasm(): Promise<void>;
41
42
  export { ProgramManager, ProvingRequestOptions, ExecuteOptions, FeeAuthorizationOptions, AuthorizationOptions } from "./program-manager.js";
42
43
  export { logAndThrow } from "./utils.js";
43
44
  export { Address, Authorization, Boolean, BHP256, BHP512, BHP768, BHP1024, Ciphertext, ComputeKey, Execution as FunctionExecution, ExecutionRequest, ExecutionResponse, EncryptionToolkit, Field, GraphKey, Group, I8, I16, I32, I64, I128, OfflineQuery, Pedersen64, Pedersen128, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramManager as ProgramManagerBase, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Signature, Scalar, Transaction, Transition, U8, U16, U32, U64, U128, VerifyingKey, ViewKey, initThreadPool, getOrInitConsensusVersionTestHeights, verifyFunctionExecution, } from "./wasm.js";
44
45
  export { initializeWasm };
45
46
  export { Key, CREDITS_PROGRAM_KEYS, KEY_STORE, PRIVATE_TRANSFER, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, PUBLIC_TO_PRIVATE_TRANSFER, RECORD_DOMAIN, VALID_TRANSFER_TYPES, } from "./constants.js";
46
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, CachedKeyPair, ConfirmedTransactionJSON, DeploymentJSON, DeploymentObject, EncryptedRecord, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionObject, FunctionKeyPair, FunctionKeyProvider, Header, ImportedPrograms, ImportedVerifyingKeys, InputJSON, InputObject, KeySearchParams, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProvingRequestJSON, ProvingResponse, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordSearchParams, SolutionJSON, SolutionsJSON, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, VerifyingKeys, };
47
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, CachedKeyPair, ConfirmedTransactionJSON, DeploymentJSON, DeploymentObject, EncryptedRecord, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionObject, FunctionKeyPair, FunctionKeyProvider, Header, ImportedPrograms, ImportedVerifyingKeys, InputJSON, InputObject, KeySearchParams, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProvingRequestJSON, ProvingResponse, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordSearchParams, SealanceMerkleTree, SolutionJSON, SolutionsJSON, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, VerifyingKeys, };
@@ -1,6 +1,7 @@
1
1
  import 'core-js/proposals/json-parse-with-source.js';
2
2
  import { ViewKey, ComputeKey, Address, PrivateKeyCiphertext, PrivateKey, RecordCiphertext, EncryptionToolkit, Group, Program, Plaintext, Transaction, ProvingRequest, Metadata, VerifyingKey, ProvingKey, RecordPlaintext, Field, Poseidon4, ProgramManager as ProgramManager$1, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
3
3
  export { Address, Authorization, BHP1024, BHP256, BHP512, BHP768, Boolean, Ciphertext, ComputeKey, EncryptionToolkit, ExecutionRequest, ExecutionResponse, Field, Execution as FunctionExecution, GraphKey, Group, I128, I16, I32, I64, I8, OfflineQuery, Pedersen128, Pedersen64, Plaintext, Poseidon2, Poseidon4, Poseidon8, PrivateKey, PrivateKeyCiphertext, Program, ProgramManager as ProgramManagerBase, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Scalar, Signature, Transaction, Transition, U128, U16, U32, U64, U8, VerifyingKey, ViewKey, getOrInitConsensusVersionTestHeights, initThreadPool, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
4
+ import { bech32m } from '@scure/base';
4
5
 
5
6
  /**
6
7
  * Key Management class. Enables the creation of a new Aleo Account, importation of an existing account from
@@ -424,7 +425,12 @@ async function post(url, options) {
424
425
  options.method = "POST";
425
426
  const response = await fetch(url, options);
426
427
  if (!response.ok) {
427
- throw new Error(response.status + " could not post URL " + url);
428
+ const error = await response.text();
429
+ let message = `${response.status} error received from ${url}`;
430
+ if (error) {
431
+ message = `${error}`;
432
+ }
433
+ throw new Error(message);
428
434
  }
429
435
  return response;
430
436
  }
@@ -491,7 +497,7 @@ class AleoNetworkClient {
491
497
  else {
492
498
  this.headers = {
493
499
  // This is replaced by the actual version by a Rollup plugin
494
- "X-Aleo-SDK-Version": "0.9.10-testnet-rc",
500
+ "X-Aleo-SDK-Version": "0.9.11",
495
501
  "X-Aleo-environment": environment(),
496
502
  };
497
503
  }
@@ -1806,7 +1812,7 @@ class AleoNetworkClient {
1806
1812
  }
1807
1813
  }
1808
1814
  catch (error) {
1809
- throw new Error(`Error posting transaction: No response received: ${error.message}`);
1815
+ throw new Error(`Error posting transaction: ${error}`);
1810
1816
  }
1811
1817
  }
1812
1818
  /**
@@ -2045,6 +2051,10 @@ const PUBLIC_TO_PRIVATE_TRANSFER = new Set([
2045
2051
  "transferPublicToPrivate",
2046
2052
  ]);
2047
2053
  const RECORD_DOMAIN = "RecordScannerV0";
2054
+ /**
2055
+ * Zero address on Aleo blockchain that corresponds to field element 0. Used as padding in Merkle trees and as a sentinel value.
2056
+ */
2057
+ const ZERO_ADDRESS = "aleo1qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq3ljyzc";
2048
2058
 
2049
2059
  /**
2050
2060
  * AleoKeyProviderParams search parameter for the AleoKeyProvider. It allows for the specification of a proverUri and
@@ -3587,6 +3597,222 @@ class RecordScanner {
3587
3597
  }
3588
3598
  }
3589
3599
 
3600
+ /**
3601
+ * Client library that encapsulates methods for constructing Merkle exclusion proofs for compliant stablecoin programs following the Sealance architecture.
3602
+ *
3603
+
3604
+ * @example
3605
+ * Construct a Merkle exclusion proof.
3606
+ * ```typescript
3607
+ * const sealance = new SealanceMerkleTree();
3608
+ * const leaves = [
3609
+ * "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px",
3610
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
3611
+ * "aleo1s3ws5tra87fjycnjrwsjcrnw2qxr8jfqqdugnf0xzqqw29q9m5pqem2u4t",
3612
+ * ];
3613
+ * const result = sealance.generateLeaves(leaves);
3614
+ * const tree = sealance.buildTree(result);
3615
+ * const [leftIdx, rightIdx] = sealance.getLeafIndices(tree, "aleo1kypwp5m7qtk9mwazgcpg0tq8aal23mnrvwfvug65qgcg9xvsrqgspyjm6n");
3616
+ * const proof_left = sealance.getSiblingPath(tree, leftIdx, 15);
3617
+ * const proof_right = sealance.getSiblingPath(tree, rightIdx, 15);
3618
+ * const exclusion_proof = [proof_left, proof_right];
3619
+ * ```
3620
+ */
3621
+ class SealanceMerkleTree {
3622
+ static hasher = new Poseidon4();
3623
+ /**
3624
+ * Converts an Aleo blockchain address to a field element.
3625
+ *
3626
+ * This function decodes a bech32m-encoded Aleo address and converts it to a field element
3627
+ * represented as a BigInt. The address format follows the Aleo protocol specification,
3628
+ * starting with the prefix "aleo1" followed by encoded data.
3629
+ *
3630
+ * @param address - The Aleo blockchain address (e.g., "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px")
3631
+ * @returns A BigInt representing the field element.
3632
+ * @throws Error if the address is invalid or cannot be decoded.
3633
+ *
3634
+ * @example
3635
+ * ```typescript
3636
+ * const address = "aleo1rhgdu77hgyqd3xjj8ucu3jj9r2krwz6mnzyd80gncr5fxcwlh5rsvzp9px";
3637
+ * const fieldValue = convertAddressToField(address);
3638
+ * console.log(fieldValue); // 123456789...n
3639
+ * ```
3640
+ */
3641
+ convertAddressToField(address) {
3642
+ const { words } = bech32m.decode(address);
3643
+ const bytes = bech32m.fromWords(words);
3644
+ // Convert bytes to BigInt (little-endian)
3645
+ let fieldValue = BigInt(0);
3646
+ for (let i = 0; i < bytes.length; i++) {
3647
+ fieldValue |= BigInt(bytes[i]) << BigInt(i * 8);
3648
+ }
3649
+ return fieldValue;
3650
+ }
3651
+ /**
3652
+ * Hashes two elements using Poseidon4 hash function
3653
+ * @param prefix - Prefix for the hash (e.g., "0field" for nodes, "1field" for leaves)
3654
+ * @param el1 - First element to hash
3655
+ * @param el2 - Second element to hash
3656
+ * @returns The hash result as a Field
3657
+ * @throws {Error} If inputs are empty or invalid
3658
+ */
3659
+ hashTwoElements(prefix, el1, el2) {
3660
+ if (!el1 || !el2) {
3661
+ throw new Error("Invalid inputs: elements cannot be empty");
3662
+ }
3663
+ const fields = [Field.fromString(prefix), Field.fromString(el1), Field.fromString(el2)];
3664
+ const arrayPlaintext = Plaintext.fromString(`[${fields.map(f => f.toString()).join(",")}]`);
3665
+ return SealanceMerkleTree.hasher.hash(arrayPlaintext.toFields());
3666
+ }
3667
+ /**
3668
+ * Builds a Merkle tree from given leaves. The tree is built bottom-up, hashing pairs of elements at each level.
3669
+ *
3670
+ * @param leaves - Array of leaf elements (must have even number of elements).
3671
+ * @returns Array representing the complete Merkle tree as BigInts.
3672
+ * @throws {Error} If leaves array is empty or has odd number of elements.
3673
+ *
3674
+ * @example
3675
+ * ```typescript
3676
+ * const leaves = ["0field", "1field", "2field", "3field"];
3677
+ * const tree = buildTree(leaves);
3678
+ * const root = tree[tree.length - 1]; // Get the Merkle root
3679
+ * ```
3680
+ */
3681
+ buildTree(leaves) {
3682
+ if (leaves.length === 0) {
3683
+ throw new Error("Leaves array cannot be empty");
3684
+ }
3685
+ if (leaves.length % 2 !== 0) {
3686
+ throw new Error("Leaves array must have even number of elements");
3687
+ }
3688
+ let currentLevel = leaves;
3689
+ let tree = [...currentLevel];
3690
+ let levelSize = currentLevel.length;
3691
+ while (levelSize > 1) {
3692
+ const nextLevel = [];
3693
+ for (let i = 0; i < levelSize; i += 2) {
3694
+ const left = currentLevel[i];
3695
+ const right = currentLevel[i + 1];
3696
+ const prefix = leaves.length === levelSize ? "1field" : "0field";
3697
+ const hash = this.hashTwoElements(prefix, left, right);
3698
+ nextLevel.push(hash.toString());
3699
+ }
3700
+ tree = [...tree, ...nextLevel];
3701
+ currentLevel = nextLevel;
3702
+ levelSize = currentLevel.length;
3703
+ }
3704
+ return tree.map(element => BigInt(element.slice(0, element.length - "field".length)));
3705
+ }
3706
+ /**
3707
+ * Converts Aleo addresses to field elements, sorts them, pads with zero fields, and returns an array. This prepares addresses for Merkle tree construction.
3708
+ *
3709
+ * @param addresses - Array of Aleo addresses.
3710
+ * @param maxTreeDepth - Maximum depth of the Merkle tree (default: 15).
3711
+ * @returns Array of field elements ready for Merkle tree construction.
3712
+ * @throws {Error} If the number of addresses exceeds the maximum capacity.
3713
+ *
3714
+ * @example
3715
+ * ```typescript
3716
+ * const addresses = [
3717
+ * "aleo1...",
3718
+ * "aleo1..."
3719
+ * ];
3720
+ * const leaves = generateLeaves(addresses, 15);
3721
+ * const tree = buildTree(leaves);
3722
+ * ```
3723
+ */
3724
+ generateLeaves(addresses, maxTreeDepth = 15) {
3725
+ const maxNumLeaves = Math.floor(2 ** (maxTreeDepth - 1));
3726
+ // Filter out zero addresses
3727
+ addresses = addresses.filter(addr => addr !== ZERO_ADDRESS);
3728
+ let numLeaves = 0;
3729
+ if (addresses.length === 0 || addresses.length === 1) {
3730
+ numLeaves = 2;
3731
+ }
3732
+ else {
3733
+ numLeaves = Math.pow(2, Math.ceil(Math.log2(addresses.length)));
3734
+ }
3735
+ if (addresses.length > maxNumLeaves) {
3736
+ throw new Error(`Leaves limit exceeded. Max: ${maxNumLeaves}, provided: ${addresses.length}`);
3737
+ }
3738
+ // Convert addresses to fields
3739
+ const addressFields = addresses.map(addr => ({
3740
+ address: addr,
3741
+ field: this.convertAddressToField(addr),
3742
+ }));
3743
+ // Sort by field value
3744
+ const sortedFields = addressFields.sort((a, b) => (a.field < b.field ? -1 : 1)).map(item => item.field);
3745
+ // Convert to field strings
3746
+ const sortedFieldElements = sortedFields.map(field => field.toString() + "field");
3747
+ // Pad with zeros to reach power of 2
3748
+ const fullTree = Array(Math.max(numLeaves - sortedFieldElements.length, 0)).fill("0field");
3749
+ return fullTree.concat(sortedFieldElements);
3750
+ }
3751
+ /**
3752
+ * Finds the leaf indices for non-inclusion proof of an address and returns the indices of the two adjacent leaves that surround the target address.
3753
+ *
3754
+ * @param merkleTree - The complete Merkle tree as array of BigInts.
3755
+ * @param address - The Aleo address for which to find indices.
3756
+ * @returns Tuple of [leftLeafIndex, rightLeafIndex].
3757
+ *
3758
+ * @example
3759
+ * ```typescript
3760
+ * const tree = buildTree(leaves);
3761
+ * const [leftIdx, rightIdx] = getLeafIndices(tree, "aleo1...");
3762
+ * ```
3763
+ */
3764
+ getLeafIndices(merkleTree, address) {
3765
+ const num_leaves = Math.floor((merkleTree.length + 1) / 2);
3766
+ const addressBigInt = this.convertAddressToField(address);
3767
+ const leaves = merkleTree.slice(0, num_leaves);
3768
+ let rightLeafIndex = leaves.findIndex((leaf) => addressBigInt <= leaf);
3769
+ let leftLeafIndex = rightLeafIndex - 1;
3770
+ if (rightLeafIndex === -1) {
3771
+ rightLeafIndex = leaves.length - 1;
3772
+ leftLeafIndex = leaves.length - 1;
3773
+ }
3774
+ if (rightLeafIndex === 0) {
3775
+ leftLeafIndex = 0;
3776
+ }
3777
+ return [leftLeafIndex, rightLeafIndex];
3778
+ }
3779
+ /**
3780
+ * Generates the sibling path (Merkle proof) for a given leaf index
3781
+ *
3782
+ * @param tree - The complete Merkle tree.
3783
+ * @param leafIndex - Index of the leaf for which to generate the proof.
3784
+ * @param depth - Maximum depth of the tree.
3785
+ * @returns Object containing siblings array and leaf_index.
3786
+ *
3787
+ * @example
3788
+ * ```typescript
3789
+ * const tree = buildTree(leaves);
3790
+ * const proof = getSiblingPath(tree, 0, 15);
3791
+ * // proof = { siblings: [0n, 1n, ...], leaf_index: 0 }
3792
+ * ```
3793
+ */
3794
+ getSiblingPath(tree, leafIndex, depth) {
3795
+ let num_leaves = Math.floor((tree.length + 1) / 2);
3796
+ const siblingPath = [];
3797
+ let index = leafIndex;
3798
+ let parentIndex = num_leaves;
3799
+ siblingPath.push(tree[index]);
3800
+ let level = 1;
3801
+ while (parentIndex < tree.length) {
3802
+ let siblingIndex = index % 2 === 0 ? index + 1 : index - 1; // Get the sibling index
3803
+ siblingPath.push(tree[siblingIndex]);
3804
+ index = parentIndex + Math.floor(leafIndex / 2 ** level); // Move up to the parent node
3805
+ parentIndex += Math.floor(num_leaves / 2 ** level); // Halve the number of nodes for the next level
3806
+ level++;
3807
+ }
3808
+ while (level < depth) {
3809
+ siblingPath.push(0n);
3810
+ level++;
3811
+ }
3812
+ return { siblings: siblingPath, leaf_index: leafIndex };
3813
+ }
3814
+ }
3815
+
3590
3816
  /**
3591
3817
  * The ProgramManager class is used to execute and deploy programs on the Aleo network and create value transfers.
3592
3818
  */
@@ -3976,6 +4202,147 @@ class ProgramManager {
3976
4202
  // Build an execution transaction
3977
4203
  return await ProgramManager$1.buildExecutionTransaction(executionPrivateKey, program, functionName, inputs, priorityFee, feeRecord, this.host, imports, provingKey, verifyingKey, feeProvingKey, feeVerifyingKey, offlineQuery, edition);
3978
4204
  }
4205
+ /**
4206
+ * Builds an execution transaction for submission to the Aleo network from an Authorization and Fee Authorization.
4207
+ * This method is helpful if signing and authorization needs to be done in a secure environment separate from where
4208
+ * transactions are built.
4209
+ *
4210
+ * @param {ExecuteAuthorizationOptions} options - The options for executing the authorizations.
4211
+ * @returns {Promise<Transaction>} - A promise that resolves to the transaction or an error.
4212
+ *
4213
+ * @example
4214
+ * import { AleoKeyProvider, PrivateKey, initThreadPool, ProgramManager } from "@provablehq/sdk";
4215
+ *
4216
+ * await initThreadPool();
4217
+ *
4218
+ * // Create a new KeyProvider.
4219
+ * const keyProvider = new AleoKeyProvider();
4220
+ * keyProvider.useCache(true);
4221
+ *
4222
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions.
4223
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider);
4224
+ *
4225
+ * // Build the `Authorization`.
4226
+ * const privateKey = new PrivateKey(); // Change this to a private key that has an aleo credit balance.
4227
+ * const authorization = await programManager.buildAuthorization({
4228
+ * programName: "credits.aleo",
4229
+ * functionName: "transfer_public",
4230
+ * privateKey,
4231
+ * inputs: [
4232
+ * "aleo1vwls2ete8dk8uu2kmkmzumd7q38fvshrht8hlc0a5362uq8ftgyqnm3w08",
4233
+ * "10000000u64",
4234
+ * ],
4235
+ * });
4236
+ *
4237
+ * console.log("Getting execution id");
4238
+ *
4239
+ * // Derive the execution ID and base fee.
4240
+ * const executionId = authorization.toExecutionId().toString();
4241
+ *
4242
+ * console.log("Estimating fee");
4243
+ *
4244
+ * // Get the base fee in microcredits.
4245
+ * const baseFeeMicrocredits = await programManager.estimateFeeForAuthorization(authorization, "credits.aleo");
4246
+ * const baseFeeCredits = Number(baseFeeMicrocredits)/1000000;
4247
+ *
4248
+ * console.log("Building fee authorization");
4249
+ *
4250
+ * // Build a credits.aleo/fee_public `Authorization`.
4251
+ * const feeAuthorization = await programManager.buildFeeAuthorization({
4252
+ * deploymentOrExecutionId: executionId,
4253
+ * baseFeeCredits,
4254
+ * privateKey
4255
+ * });
4256
+ *
4257
+ * console.log("Executing authorizations");
4258
+ *
4259
+ * // Build and execute the transaction.
4260
+ * const tx = await programManager.buildTransactionFromAuthorization({
4261
+ * programName: "credits.aleo",
4262
+ * authorization,
4263
+ * feeAuthorization,
4264
+ * });
4265
+ *
4266
+ * // Submit the transaction to the network.
4267
+ * await programManager.networkClient.submitTransaction(tx.toString());
4268
+ *
4269
+ * // Verify the transaction was successful.
4270
+ * setTimeout(async () => {
4271
+ * const transaction = await programManager.networkClient.getTransaction(tx.id());
4272
+ * console.log(transaction);
4273
+ * }, 10000);
4274
+ */
4275
+ async buildTransactionFromAuthorization(options) {
4276
+ // Destructure the options object to access the parameters.
4277
+ const { programName, authorization, } = options;
4278
+ const feeAuthorization = options.feeAuthorization;
4279
+ const keySearchParams = options.keySearchParams;
4280
+ const offlineQuery = options.offlineQuery;
4281
+ let provingKey = options.provingKey;
4282
+ let verifyingKey = options.verifyingKey;
4283
+ let program = options.program;
4284
+ let imports = options.imports;
4285
+ // Ensure the function exists on the network.
4286
+ if (program === undefined) {
4287
+ try {
4288
+ program = (await this.networkClient.getProgram(programName));
4289
+ }
4290
+ catch (e) {
4291
+ 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.`);
4292
+ }
4293
+ }
4294
+ else if (program instanceof Program) {
4295
+ program = program.toString();
4296
+ }
4297
+ // Get the fee proving and verifying keys from the key provider.
4298
+ let feeKeys;
4299
+ const privateFee = feeAuthorization ? feeAuthorization.isFeePrivate() : false;
4300
+ try {
4301
+ feeKeys = privateFee
4302
+ ? await this.keyProvider.feePrivateKeys()
4303
+ : await this.keyProvider.feePublicKeys();
4304
+ }
4305
+ catch (e) {
4306
+ logAndThrow(`Error finding fee keys. Key finder response: '${e.message}'. Please ensure your key provider is configured correctly.`);
4307
+ }
4308
+ const [feeProvingKey, feeVerifyingKey] = feeKeys;
4309
+ // If the function proving and verifying keys are not provided, attempt to find them using the key provider.
4310
+ if (!provingKey || !verifyingKey) {
4311
+ try {
4312
+ [provingKey, verifyingKey] = (await this.keyProvider.functionKeys(keySearchParams));
4313
+ }
4314
+ catch (e) {
4315
+ console.log(`Function keys not found. Key finder response: '${e}'. The function keys will be synthesized`);
4316
+ }
4317
+ }
4318
+ // Resolve the program imports if they exist.
4319
+ console.log("Resolving program imports");
4320
+ const numberOfImports = Program.fromString(program).getImports().length;
4321
+ if (numberOfImports > 0 && !imports) {
4322
+ try {
4323
+ imports = (await this.networkClient.getProgramImports(programName));
4324
+ }
4325
+ catch (e) {
4326
+ 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.`);
4327
+ }
4328
+ }
4329
+ // If the offline query exists, add the inclusion key.
4330
+ if (offlineQuery && !this.inclusionKeysLoaded) {
4331
+ console.log("Loading inclusion keys for offline proving.");
4332
+ try {
4333
+ const inclusionKeys = await this.keyProvider.inclusionKeys();
4334
+ ProgramManager$1.loadInclusionProver(inclusionKeys[0]);
4335
+ this.inclusionKeysLoaded = true;
4336
+ console.log("Successfully loaded inclusion key");
4337
+ }
4338
+ catch {
4339
+ logAndThrow(`Inclusion key bytes not loaded, please ensure the program manager is initialized with a KeyProvider that includes the inclusion key.`);
4340
+ }
4341
+ }
4342
+ // Build an execution transaction from the authorization.
4343
+ console.log("Executing authorizations");
4344
+ return await ProgramManager$1.executeAuthorization(authorization, feeAuthorization, program, provingKey, verifyingKey, feeProvingKey, feeVerifyingKey, imports, this.host, offlineQuery);
4345
+ }
3979
4346
  /**
3980
4347
  * Builds a SnarkVM `Authorization` for a specific function.
3981
4348
  *
@@ -4164,7 +4531,6 @@ class ProgramManager {
4164
4531
  * const provingRequest = await programManager.provingRequest({
4165
4532
  * programName: "credits.aleo",
4166
4533
  * functionName: "transfer_public",
4167
- * baseFee: 100000,
4168
4534
  * priorityFee: 0,
4169
4535
  * privateFee: false,
4170
4536
  * inputs: [
@@ -4176,8 +4542,9 @@ class ProgramManager {
4176
4542
  */
4177
4543
  async provingRequest(options) {
4178
4544
  // Destructure the options object to access the parameters.
4179
- const { functionName, baseFee, priorityFee, privateFee, inputs, recordSearchParams, broadcast = false, unchecked = false, } = options;
4545
+ const { functionName, priorityFee, privateFee, inputs, recordSearchParams, broadcast = false, unchecked = false, } = options;
4180
4546
  const privateKey = options.privateKey;
4547
+ const baseFee = options.baseFee ? options.baseFee : 0;
4181
4548
  let program = options.programSource;
4182
4549
  let programName = options.programName;
4183
4550
  let feeRecord = options.feeRecord;
@@ -4258,14 +4625,14 @@ class ProgramManager {
4258
4625
  * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider, recordProvider);
4259
4626
  *
4260
4627
  * // Build a credits.aleo/fee_public `Authorization`.
4261
- * const feePublicAuthorization = await programManager.authorizeFee({
4628
+ * const feePublicAuthorization = await programManager.buildFeeAuthorization({
4262
4629
  * deploymentOrExecutionId: "2423957656946557501636078245035919227529640894159332581642187482178647335171field",
4263
4630
  * baseFeeCredits: 0.1,
4264
4631
  * });
4265
4632
  *
4266
4633
  * // Build a credits.aleo/fee_private `Authorization`.
4267
4634
  * const record = "{ owner: aleo1j7qxyunfldj2lp8hsvy7mw5k8zaqgjfyr72x2gh3x4ewgae8v5gscf5jh3.private, microcredits: 1500000000000000u64.private, _nonce: 3077450429259593211617823051143573281856129402760267155982965992208217472983group.public }";
4268
- * const feePrivateAuthorization = await programManager.authorizeFee({
4635
+ * const feePrivateAuthorization = await programManager.buildFeeAuthorization({
4269
4636
  * deploymentOrExecutionId: "2423957656946557501636078245035919227529640894159332581642187482178647335171field",
4270
4637
  * baseFeeCredits: 0.1,
4271
4638
  * feeRecord: record,
@@ -5372,15 +5739,6 @@ class ProgramManager {
5372
5739
  return false;
5373
5740
  }
5374
5741
  }
5375
- /**
5376
- * Set the inclusion key bytes.
5377
- *
5378
- * @param {executionResponse} executionResponse The response from an offline function execution (via the `programManager.run` method)
5379
- * @param {ImportedPrograms} imports The imported programs used in the execution. Specified as { "programName": "programSourceCode", ... }
5380
- * @param {ImportedVerifyingKeys} importedVerifyingKeys The verifying keys in the execution. Specified as { "programName": [["functionName", "verifyingKey"], ...], ... }
5381
- * @returns {boolean} True if the proof is valid, false otherwise
5382
- *
5383
-
5384
5742
  /**
5385
5743
  * Create a program object from a program's source code
5386
5744
  *
@@ -5412,6 +5770,109 @@ class ProgramManager {
5412
5770
  return false;
5413
5771
  }
5414
5772
  }
5773
+ /**
5774
+ * Estimate the execution fee for an authorization.
5775
+ *
5776
+ * @param {FeeEstimateOptions} options Options for fee estimate.
5777
+ *
5778
+ * @example
5779
+ * import { AleoKeyProvider, PrivateKey, initThreadPool, ProgramManager } from "@provablehq/sdk";
5780
+ *
5781
+ * await initThreadPool();
5782
+ *
5783
+ * // Create a new KeyProvider.
5784
+ * const keyProvider = new AleoKeyProvider();
5785
+ * keyProvider.useCache(true);
5786
+ *
5787
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions.
5788
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider);
5789
+ *
5790
+ * // Build the `Authorization`.
5791
+ * const privateKey = new PrivateKey(); // Change this to a private key that has an aleo credit balance.
5792
+ * const authorization = await programManager.buildAuthorization({
5793
+ * programName: "credits.aleo",
5794
+ * functionName: "transfer_public",
5795
+ * privateKey,
5796
+ * inputs: [
5797
+ * "aleo1vwls2ete8dk8uu2kmkmzumd7q38fvshrht8hlc0a5362uq8ftgyqnm3w08",
5798
+ * "10000000u64",
5799
+ * ],
5800
+ * });
5801
+ *
5802
+ * console.log("Getting execution id");
5803
+ *
5804
+ * // Derive the execution ID and base fee.
5805
+ * const executionId = authorization.toExecutionId().toString();
5806
+ *
5807
+ * console.log("Estimating fee");
5808
+ *
5809
+ * // Get the base fee in microcredits.
5810
+ * const baseFeeMicrocredits = await programManager.estimateFeeForAuthorization({
5811
+ * authorization,
5812
+ * programName: "credits.aleo"
5813
+ * });
5814
+ * const baseFeeCredits = Number(baseFeeMicrocredits)/1000000;
5815
+ *
5816
+ * console.log("Building fee authorization");
5817
+ *
5818
+ * // Build a credits.aleo/fee_public `Authorization`.
5819
+ * const feeAuthorization = await programManager.buildFeeAuthorization({
5820
+ * deploymentOrExecutionId: executionId,
5821
+ * baseFeeCredits,
5822
+ * privateKey
5823
+ * });
5824
+ */
5825
+ async estimateFeeForAuthorization(options) {
5826
+ const { authorization, programName, program, imports, edition } = options;
5827
+ if (!authorization) {
5828
+ throw new Error("Authorization must be provided if estimating fee for Authorization.");
5829
+ }
5830
+ const programSource = program ? program.toString() : await this.networkClient.getProgram(programName, edition);
5831
+ const programImports = imports ? imports : await this.networkClient.getProgramImports(programSource);
5832
+ console.log(JSON.stringify(programImports));
5833
+ if (Object.keys(programImports)) {
5834
+ return ProgramManager$1.estimateFeeForAuthorization(authorization, programSource, programImports, edition);
5835
+ }
5836
+ return ProgramManager$1.estimateFeeForAuthorization(authorization, programSource, imports, edition);
5837
+ }
5838
+ /**
5839
+ * Estimate the execution fee for an Aleo function.
5840
+ *
5841
+ * @param {FeeEstimateOptions} options Options for the fee estimate.
5842
+ *
5843
+ * @returns {Promise<bigint>} Execution fee in microcredits for the authorization.
5844
+ *
5845
+ * @example
5846
+ * import { AleoKeyProvider, PrivateKey, initThreadPool, ProgramManager } from "@provablehq/sdk";
5847
+ *
5848
+ * // Initialize a program manager with the key provider to automatically fetch keys for executions.
5849
+ * const programManager = new ProgramManager("https://api.explorer.provable.com/v1", keyProvider);
5850
+ *
5851
+ * // Get the base fee in microcredits.
5852
+ * const baseFeeMicrocredits = await programManager.estimateExecutionFee({programName: "credits.aleo"});
5853
+ * const baseFeeCredits = Number(baseFeeMicrocredits)/1000000;
5854
+ *
5855
+ * console.log("Building fee authorization");
5856
+ *
5857
+ * // Build a credits.aleo/fee_public `Authorization`.
5858
+ * const baseFeeMicrocredits = await programManager.estimateFeeForAuthorization({
5859
+ * programName: "credits.aleo",
5860
+ * functionName: "transfer_public",
5861
+ * });
5862
+ * const baseFeeCredits = Number(baseFeeMicrocredits)/1000000;
5863
+ */
5864
+ async estimateExecutionFee(options) {
5865
+ const { functionName, programName, program, imports, edition } = options;
5866
+ if (!functionName) {
5867
+ throw new Error("Function name must be specified when estimating fee.");
5868
+ }
5869
+ const programSource = program ? program.toString() : await this.networkClient.getProgram(programName, edition);
5870
+ const programImports = imports ? imports : await this.networkClient.getProgramImports(programSource);
5871
+ if (Object.keys(programImports)) {
5872
+ return ProgramManager$1.estimateExecutionFee(programSource, functionName, programImports, edition);
5873
+ }
5874
+ return ProgramManager$1.estimateExecutionFee(programSource, functionName, imports, edition);
5875
+ }
5415
5876
  // Internal utility function for getting a credits.aleo record
5416
5877
  async getCreditsRecord(amount, nonces, record, params) {
5417
5878
  try {
@@ -5454,5 +5915,5 @@ async function initializeWasm() {
5454
5915
  console.warn("initializeWasm is deprecated, you no longer need to use it");
5455
5916
  }
5456
5917
 
5457
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KEY_STORE, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, ProgramManager, RECORD_DOMAIN, RecordScanner, VALID_TRANSFER_TYPES, initializeWasm, logAndThrow };
5918
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KEY_STORE, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, PRIVATE_TO_PUBLIC_TRANSFER, PRIVATE_TRANSFER, PRIVATE_TRANSFER_TYPES, PUBLIC_TO_PRIVATE_TRANSFER, PUBLIC_TRANSFER, PUBLIC_TRANSFER_AS_SIGNER, ProgramManager, RECORD_DOMAIN, RecordScanner, SealanceMerkleTree, VALID_TRANSFER_TYPES, initializeWasm, logAndThrow };
5458
5919
  //# sourceMappingURL=browser.js.map