@provablehq/sdk 0.9.18 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (39) hide show
  1. package/dist/mainnet/browser.d.ts +6 -4
  2. package/dist/mainnet/browser.js +394 -16
  3. package/dist/mainnet/browser.js.map +1 -1
  4. package/dist/mainnet/external-signing.d.ts +76 -0
  5. package/dist/mainnet/keys/keystore/error.d.ts +5 -4
  6. package/dist/mainnet/keys/keystore/file.d.ts +64 -104
  7. package/dist/mainnet/keys/keystore/interface.d.ts +106 -30
  8. package/dist/mainnet/models/external-signing.d.ts +123 -0
  9. package/dist/mainnet/models/input/inputJSON.d.ts +1 -0
  10. package/dist/mainnet/models/input/inputObject.d.ts +1 -0
  11. package/dist/mainnet/models/output/outputJSON.d.ts +1 -0
  12. package/dist/mainnet/models/output/outputObject.d.ts +1 -0
  13. package/dist/mainnet/network-client.d.ts +1 -0
  14. package/dist/mainnet/node.js +112 -138
  15. package/dist/mainnet/node.js.map +1 -1
  16. package/dist/mainnet/program-manager.d.ts +100 -4
  17. package/dist/mainnet/record-scanner.d.ts +1 -0
  18. package/dist/mainnet/wasm.d.ts +1 -1
  19. package/dist/testnet/browser.d.ts +6 -4
  20. package/dist/testnet/browser.js +394 -16
  21. package/dist/testnet/browser.js.map +1 -1
  22. package/dist/testnet/external-signing.d.ts +76 -0
  23. package/dist/testnet/keys/keystore/error.d.ts +5 -4
  24. package/dist/testnet/keys/keystore/file.d.ts +64 -104
  25. package/dist/testnet/keys/keystore/interface.d.ts +106 -30
  26. package/dist/testnet/models/external-signing.d.ts +123 -0
  27. package/dist/testnet/models/input/inputJSON.d.ts +1 -0
  28. package/dist/testnet/models/input/inputObject.d.ts +1 -0
  29. package/dist/testnet/models/output/outputJSON.d.ts +1 -0
  30. package/dist/testnet/models/output/outputObject.d.ts +1 -0
  31. package/dist/testnet/network-client.d.ts +1 -0
  32. package/dist/testnet/node.js +112 -138
  33. package/dist/testnet/node.js.map +1 -1
  34. package/dist/testnet/program-manager.d.ts +100 -4
  35. package/dist/testnet/record-scanner.d.ts +1 -0
  36. package/dist/testnet/wasm.d.ts +1 -1
  37. package/package.json +2 -2
  38. package/dist/mainnet/models/keyHolder.d.ts +0 -2
  39. package/dist/testnet/models/keyHolder.d.ts +0 -2
@@ -54,17 +54,19 @@ import { FunctionKeyProvider, KeySearchParams } from "./keys/provider/interface.
54
54
  import { AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams } from "./keys/provider/memory.js";
55
55
  import { KeyFingerprint, KeyMetadata, KeyVerificationError, KeyVerifier, sha256Hex } from "./keys/verifier/interface.js";
56
56
  import { MemKeyVerifier } from "./keys/verifier/memory.js";
57
- import { InvalidLocatorError, InvalidLocatorReason, KeyLocator, KeyStore } from "./keys/keystore/interface.js";
57
+ import { BaseFunctionKeyLocator, InvalidLocatorError, InvalidLocatorReason, KeyLocator, KeyStore, KeyType, ProvingKeyLocator, TranslationKeyLocator, VerifyingKeyLocator, provingKeyLocator, verifyingKeyLocator, translationKeyLocator } from "./keys/keystore/interface.js";
58
58
  import { OfflineKeyProvider, OfflineSearchParams } from "./keys/provider/offline.js";
59
59
  import { BlockHeightSearch, NetworkRecordProvider, RecordProvider } from "./record-provider.js";
60
60
  import { RecordScanner, RecordScannerJWTData, RecordScannerOptions } from "./record-scanner.js";
61
61
  import { SealanceMerkleTree } from "./integrations/sealance/merkle-tree.js";
62
62
  declare function initializeWasm(): Promise<void>;
63
- export { ProgramManager, ProvingRequestOptions, ExecuteOptions, FeeAuthorizationOptions, AuthorizationOptions } from "./program-manager.js";
63
+ export { ProgramManager, ProvingRequestOptions, ExecuteOptions, FeeAuthorizationOptions, AuthorizationOptions, VerificationOptions, BatchVerificationOptions, inputsToFields, verifyProof, verifyBatchProof } from "./program-manager.js";
64
64
  export { logAndThrow } from "./utils.js";
65
- 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";
65
+ 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, Proof, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Signature, Scalar, stringToField, Transaction, Transition, U8, U16, U32, U64, U128, Value, VerifyingKey, ViewKey, initThreadPool, getOrInitConsensusVersionTestHeights, snarkVerify, snarkVerifyBatch, verifyFunctionExecution, } from "./wasm.js";
66
66
  export { initializeWasm };
67
67
  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";
68
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, BroadcastResponse, BroadcastResult, CachedKeyPair, ConfirmedTransactionJSON, CryptoBoxPubKey, DeploymentJSON, DeploymentObject, EncryptedProvingRequest, EncryptedRecord, EncryptedRegistrationRequest, EncryptedRecordsResult, EncryptedRecordsSuccess, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionInput, FunctionObject, FunctionKeyPair, FunctionKeyProvider, Header, isProvingResponse, isProveApiErrorBody, ImportedPrograms, ImportedVerifyingKeys, InputJSON, InputObject, InvalidLocatorError, InvalidLocatorReason, KeyFingerprint, KeyLocator, KeyMetadata, KeyStore, KeyVerificationError, KeyVerifier, MemKeyVerifier, KeySearchParams, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnedRecordsResult, OwnedRecordsResponseFilter, OwnedRecordsSuccess, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProveApiErrorBody, ProvingFailure, ProvingRequestError, ProvingRequestJSON, ProvingResult, ProvingSuccess, ProvingResponse, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordScannerErrorBody, RecordScannerFailure, RecordScannerJWTData, RecordScannerOptions, DecryptionNotEnabledError, RecordNotFoundError, RecordScannerRequestError, ViewKeyNotStoredError, RecordSearchParams, RegisterResult, RegisterSuccess, RegistrationRequest, RegistrationResponse, RevokeResult, RevokeSuccess, RevokeResponse, SealanceMerkleTree, SerialNumbersResult, SerialNumbersSuccess, sha256Hex, SolutionJSON, SolutionsJSON, StatusResponse, StatusResult, StatusSuccess, TagsResult, TagsSuccess, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, UUIDError, VerifyingKeys, };
68
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoKeyProviderInitParams, AleoNetworkClient, BlockJSON, BlockHeightSearch, BroadcastResponse, BroadcastResult, CachedKeyPair, ConfirmedTransactionJSON, CryptoBoxPubKey, DecryptionNotEnabledError, DeploymentJSON, DeploymentObject, EncryptedProvingRequest, EncryptedRecord, EncryptedRegistrationRequest, EncryptedRecordsResult, EncryptedRecordsSuccess, ExecutionJSON, ExecutionObject, FeeExecutionJSON, FeeExecutionObject, FinalizeJSON, FunctionInput, FunctionObject, FunctionKeyPair, FunctionKeyProvider, Header, isProvingResponse, isProveApiErrorBody, ImportedPrograms, ImportedVerifyingKeys, InputJSON, InputObject, InvalidLocatorError, InvalidLocatorReason, BaseFunctionKeyLocator, KeyFingerprint, KeyLocator, KeyMetadata, KeySearchParams, KeyStore, KeyType, KeyVerificationError, ProvingKeyLocator, provingKeyLocator, TranslationKeyLocator, translationKeyLocator, VerifyingKeyLocator, verifyingKeyLocator, KeyVerifier, MemKeyVerifier, Metadata, NetworkRecordProvider, OfflineKeyProvider, OfflineSearchParams, OutputJSON, OutputObject, OwnedFilter, OwnedRecord, OwnedRecordsResult, OwnedRecordsResponseFilter, OwnedRecordsSuccess, OwnerJSON, PartialSolutionJSON, PlaintextArray, PlaintextLiteral, PlaintextObject, PlaintextStruct, ProgramImports, ProveApiErrorBody, ProvingFailure, ProvingRequestError, ProvingRequestJSON, ProvingResult, ProvingSuccess, ProvingResponse, RatificationJSON, RecordsFilter, RecordsResponseFilter, RecordProvider, RecordScanner, RecordScannerErrorBody, RecordScannerFailure, RecordScannerJWTData, RecordScannerOptions, RecordNotFoundError, RecordScannerRequestError, ViewKeyNotStoredError, RecordSearchParams, RegisterResult, RegisterSuccess, RegistrationRequest, RegistrationResponse, RevokeResult, RevokeSuccess, RevokeResponse, SealanceMerkleTree, SerialNumbersResult, SerialNumbersSuccess, sha256Hex, SolutionJSON, SolutionsJSON, StatusResponse, StatusResult, StatusSuccess, TagsResult, TagsSuccess, TransactionJSON, TransactionObject, TransitionJSON, TransitionObject, UUIDError, VerifyingKeys, };
69
69
  export { KeyVerificationError as ChecksumMismatchError, KeyVerifier as FunctionKeyVerifier, } from "./keys/verifier/interface.js";
70
70
  export { encryptAuthorization, encryptProvingRequest, encryptViewKey, encryptRegistrationRequest, zeroizeBytes } from "./security.js";
71
+ export { toField, toGroup, toViewKey, toSignature, toAddress, isViewKeyStrategy, isInputIdStrategy, isRecordViewKeyStrategy, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, } from "./external-signing.js";
72
+ export type { FieldLike, GroupLike, ViewKeyLike, SignatureLike, AddressLike, InputID, ExecutionRequestParams, RecordViewKeyStrategy, ViewKeyStrategy, InputIdStrategy, InputStrategy, ExternalSigningInput, ExternalSigningOptions, RequestSignInput, OutputFormat, FieldOutput, } from "./external-signing.js";
@@ -1,6 +1,6 @@
1
1
  import 'core-js/proposals/json-parse-with-source.js';
2
- import { ViewKey, ComputeKey, Address, PrivateKeyCiphertext, PrivateKey, RecordCiphertext, EncryptionToolkit, Group, Metadata, VerifyingKey, Program, Plaintext, Transaction, ProvingRequest, ProvingKey, RecordPlaintext, Field, Poseidon4, ProgramManager as ProgramManager$1, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
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';
2
+ import { ViewKey, ComputeKey, Address, PrivateKeyCiphertext, PrivateKey, RecordCiphertext, EncryptionToolkit, Group, Metadata, VerifyingKey, Program, Plaintext, Transaction, ProvingRequest, ProvingKey, RecordPlaintext, Field, Poseidon4, ProgramManager as ProgramManager$1, ExecutionRequest, verifyFunctionExecution, Value, Proof, Signature } from '@provablehq/wasm/mainnet.js';
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, Proof, ProvingKey, ProvingRequest, RecordCiphertext, RecordPlaintext, Scalar, Signature, Transaction, Transition, U128, U16, U32, U64, U8, Value, VerifyingKey, ViewKey, getOrInitConsensusVersionTestHeights, initThreadPool, snarkVerify, snarkVerifyBatch, stringToField, verifyFunctionExecution } from '@provablehq/wasm/mainnet.js';
4
4
  import sodium from 'libsodium-wrappers';
5
5
  import { bech32m } from '@scure/base';
6
6
 
@@ -823,6 +823,7 @@ const FIVE_MINUTES = 5 * 60 * 1000; // 5 minutes in milliseconds
823
823
  */
824
824
  class AleoNetworkClient {
825
825
  host;
826
+ baseUrl;
826
827
  headers;
827
828
  account;
828
829
  ctx;
@@ -834,6 +835,9 @@ class AleoNetworkClient {
834
835
  proverUri;
835
836
  recordScannerUri;
836
837
  constructor(host, options) {
838
+ // baseUrl is the API root (origin only) — used for JWT refresh which
839
+ // lives at /jwts/{consumerId} on the API root, not under the versioned path.
840
+ this.baseUrl = new URL(host).origin;
837
841
  this.host = host + "/mainnet";
838
842
  this.network = "mainnet";
839
843
  this.ctx = {};
@@ -845,7 +849,7 @@ class AleoNetworkClient {
845
849
  else {
846
850
  this.headers = {
847
851
  // This is replaced by the actual version by a Rollup plugin
848
- "X-Aleo-SDK-Version": "0.9.18",
852
+ "X-Aleo-SDK-Version": "0.10.0",
849
853
  "X-Aleo-environment": environment(),
850
854
  };
851
855
  }
@@ -861,7 +865,7 @@ class AleoNetworkClient {
861
865
  else {
862
866
  this.headers = {
863
867
  // This is replaced by the actual version by a Rollup plugin
864
- "X-Aleo-SDK-Version": "0.9.18",
868
+ "X-Aleo-SDK-Version": "0.10.0",
865
869
  "X-Aleo-environment": environment(),
866
870
  };
867
871
  }
@@ -2249,7 +2253,7 @@ class AleoNetworkClient {
2249
2253
  if (!apiKey || !consumerId) {
2250
2254
  throw new Error('API key and consumer ID are required to refresh JWT');
2251
2255
  }
2252
- const response = await post(`https://api.provable.com/jwts/${consumerId}`, {
2256
+ const response = await post(`${this.baseUrl}/jwts/${consumerId}`, {
2253
2257
  headers: {
2254
2258
  'X-Provable-API-Key': apiKey
2255
2259
  }
@@ -2336,7 +2340,7 @@ class AleoNetworkClient {
2336
2340
  // Check to see if the JWT needs refreshing.
2337
2341
  const isExpired = jwtData && Date.now() >= jwtData.expiration - FIVE_MINUTES;
2338
2342
  if (!jwtData || isExpired) {
2339
- if (options.apiKey && options.consumerId) {
2343
+ if (apiKey && consumerId) {
2340
2344
  jwtData = await this.refreshJwt(apiKey, consumerId);
2341
2345
  this.jwtData = jwtData;
2342
2346
  options.jwtData = jwtData;
@@ -3151,6 +3155,51 @@ class InvalidLocatorError extends Error {
3151
3155
  }
3152
3156
  }
3153
3157
 
3158
+ /**
3159
+ * Creates a {@link ProvingKeyLocator}.
3160
+ *
3161
+ * @param {string} program - The program name (e.g. "credits.aleo").
3162
+ * @param {string} functionName - The function name (e.g. "transfer_private").
3163
+ * @param {number} [edition=1] - The program edition.
3164
+ * @param {number} [amendment=0] - The program amendment.
3165
+ * @param {string} [network] - The network name. Defaults to the build-time network.
3166
+ * @param {string} [checksum] - Optional SHA-256 checksum for key verification.
3167
+ * @returns {ProvingKeyLocator}
3168
+ */
3169
+ function provingKeyLocator(program, functionName, edition = 1, amendment = 0, network = "mainnet", checksum) {
3170
+ return { program, functionName, edition, amendment, network, keyType: "prover", ...(checksum !== undefined && { checksum }) };
3171
+ }
3172
+ /**
3173
+ * Creates a {@link VerifyingKeyLocator}.
3174
+ *
3175
+ * @param {string} program - The program name (e.g. "credits.aleo").
3176
+ * @param {string} functionName - The function name (e.g. "transfer_private").
3177
+ * @param {number} [edition=1] - The program edition.
3178
+ * @param {number} [amendment=0] - The program amendment.
3179
+ * @param {string} [network] - The network name. Defaults to the build-time network.
3180
+ * @param {string} [checksum] - Optional SHA-256 checksum for key verification.
3181
+ * @returns {VerifyingKeyLocator}
3182
+ */
3183
+ function verifyingKeyLocator(program, functionName, edition = 1, amendment = 0, network = "mainnet", checksum) {
3184
+ return { program, functionName, edition, amendment, network, keyType: "verifier", ...(checksum !== undefined && { checksum }) };
3185
+ }
3186
+ /**
3187
+ * Creates a {@link TranslationKeyLocator}.
3188
+ *
3189
+ * @param {string} program - The program name (e.g. "credits.aleo").
3190
+ * @param {string} functionName - The function name (e.g. "transfer_private").
3191
+ * @param {string} recordName - The record name associated with the translation key.
3192
+ * @param {number} recordInputPosition - The record input position in the function signature.
3193
+ * @param {number} [edition=1] - The program edition.
3194
+ * @param {number} [amendment=0] - The program amendment.
3195
+ * @param {string} [network] - The network name. Defaults to the build-time network.
3196
+ * @param {string} [checksum] - Optional SHA-256 checksum for key verification.
3197
+ * @returns {TranslationKeyLocator}
3198
+ */
3199
+ function translationKeyLocator(program, functionName, recordName, recordInputPosition, edition = 1, amendment = 0, network = "mainnet", checksum) {
3200
+ return { program, functionName, edition, amendment, network, keyType: "translation", recordName, recordInputPosition, ...(checksum !== undefined && { checksum }) };
3201
+ }
3202
+
3154
3203
  /**
3155
3204
  * Search parameters for the offline key provider. This class implements the KeySearchParams interface and includes
3156
3205
  * a convenience method for creating a new instance of this class for each function of the credits.aleo program.
@@ -4012,6 +4061,7 @@ class BlockHeightSearch {
4012
4061
  class RecordScanner {
4013
4062
  cacheViewKeysOnRegister;
4014
4063
  url;
4064
+ baseUrl;
4015
4065
  apiKey;
4016
4066
  consumerId;
4017
4067
  jwtData;
@@ -4031,6 +4081,9 @@ class RecordScanner {
4031
4081
  throw new Error("The record scanning url should not include the specific network, this is automatically configured by the Provable SDK.");
4032
4082
  }
4033
4083
  // Configure the url to use the network the SDK is using.
4084
+ // baseUrl is the API root (origin only) — used for JWT refresh which
4085
+ // lives at /jwts/{consumerId} on the API root, not under /scanner.
4086
+ this.baseUrl = new URL(options.url).origin;
4034
4087
  this.url = options.url + network;
4035
4088
  // Get any view keys passed in the options.
4036
4089
  this.viewKeys = options.viewKeys ?
@@ -4159,7 +4212,7 @@ class RecordScanner {
4159
4212
  * @returns {Promise<RecordScannerJWTData>} The new JWT data.
4160
4213
  */
4161
4214
  async refreshJwt(apiKey, consumerId) {
4162
- const response = await post(`${this.url}/jwts/${consumerId}`, {
4215
+ const response = await post(`${this.baseUrl}/jwts/${consumerId}`, {
4163
4216
  headers: {
4164
4217
  "X-Provable-API-Key": apiKey,
4165
4218
  },
@@ -5976,7 +6029,7 @@ class ProgramManager {
5976
6029
  return await ProgramManager$1.buildAuthorizationUnchecked(executionPrivateKey, program, functionName, inputs, imports, edition);
5977
6030
  }
5978
6031
  /**
5979
- * Builds a `ProvingRequest` for submission to a prover for execution.
6032
+ * Builds a `ProvingRequest` for submission to a prover for execution. If building a proving request with an ExecutionRequest, a private key must be explicitly provided.
5980
6033
  *
5981
6034
  * @param {ProvingRequestOptions} options - The options for building the proving request
5982
6035
  * @returns {Promise<ProvingRequest>} - A promise that resolves to the transaction or an error.
@@ -6017,6 +6070,9 @@ class ProgramManager {
6017
6070
  let feeRecord = options.feeRecord;
6018
6071
  let imports = options.programImports;
6019
6072
  let edition = options.edition;
6073
+ if (!inputs && !options.executionRequest) {
6074
+ throw new Error("Either function inputs or an execution request must be provided to form a proving request");
6075
+ }
6020
6076
  // Ensure the function exists on the network.
6021
6077
  if (program === undefined) {
6022
6078
  try {
@@ -6045,12 +6101,10 @@ class ProgramManager {
6045
6101
  // Get the private key from the account if it is not provided in the parameters.
6046
6102
  let executionPrivateKey = privateKey;
6047
6103
  if (typeof privateKey === "undefined" &&
6048
- typeof this.account !== "undefined") {
6104
+ typeof this.account !== "undefined" &&
6105
+ typeof options.executionRequest === "undefined") {
6049
6106
  executionPrivateKey = this.account.privateKey();
6050
6107
  }
6051
- if (typeof executionPrivateKey === "undefined") {
6052
- throw "No private key provided and no private key set in the ProgramManager";
6053
- }
6054
6108
  // Resolve the program imports if they exist.
6055
6109
  const numberOfImports = Program.fromString(program).getImports().length;
6056
6110
  if (numberOfImports > 0 && !imports) {
@@ -6063,7 +6117,7 @@ class ProgramManager {
6063
6117
  }
6064
6118
  // Get the fee record from the account if it is not provided in the parameters
6065
6119
  try {
6066
- if (privateFee && !useFeeMaster) {
6120
+ if (privateFee && !useFeeMaster && !options.executionRequest) {
6067
6121
  let fee = priorityFee;
6068
6122
  // If a fee record wasn't provided, estimate the fee that needs to be paid.
6069
6123
  if (!feeRecord) {
@@ -6081,8 +6135,21 @@ class ProgramManager {
6081
6135
  catch (e) {
6082
6136
  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.`);
6083
6137
  }
6084
- // Build and return the `ProvingRequest`.
6085
- return await ProgramManager$1.buildProvingRequest(executionPrivateKey, program, functionName, inputs, baseFee, priorityFee, feeRecord, imports, broadcast, unchecked, edition, useFeeMaster);
6138
+ if (options.executionRequest instanceof ExecutionRequest) {
6139
+ return await ProgramManager$1.buildProvingRequestFromExecutionRequest(options.executionRequest, program, unchecked, broadcast, edition, imports, executionPrivateKey);
6140
+ }
6141
+ else {
6142
+ // Ensure the private key exists.
6143
+ if (!executionPrivateKey) {
6144
+ throw new Error("No private key provided and no private key set in the ProgramManager");
6145
+ }
6146
+ // Ensure the inputs exist.
6147
+ if (!inputs) {
6148
+ throw new Error("No inputs provided to build a proving request");
6149
+ }
6150
+ // Build and return the `ProvingRequest`.
6151
+ return await ProgramManager$1.buildProvingRequest(executionPrivateKey, program, functionName, inputs, baseFee, priorityFee, feeRecord, imports, broadcast, unchecked, edition, useFeeMaster);
6152
+ }
6086
6153
  }
6087
6154
  /**
6088
6155
  * 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.
@@ -7763,11 +7830,322 @@ function validateTransferType(transferType) {
7763
7830
  ? transferType
7764
7831
  : logAndThrow(`Invalid transfer type '${transferType}'. Valid transfer types are 'private', 'privateToPublic', 'public', and 'publicToPrivate'.`);
7765
7832
  }
7833
+ /**
7834
+ * Convert an array of Aleo type strings to field element strings.
7835
+ *
7836
+ * Inputs that are already field elements (e.g. "1field") are passed through directly.
7837
+ * Other Aleo values (e.g. "1u32", records, futures, dynamic records) are parsed via
7838
+ * Value and converted to their field representation.
7839
+ *
7840
+ * @param {string[]} inputs Array of Aleo value strings
7841
+ * @returns {string[]} Array of field element strings
7842
+ */
7843
+ function inputsToFields(inputs) {
7844
+ const fields = [];
7845
+ for (const input of inputs) {
7846
+ if (input.endsWith("field")) {
7847
+ fields.push(input);
7848
+ }
7849
+ else {
7850
+ const value = Value.fromString(input);
7851
+ let valueFields;
7852
+ try {
7853
+ valueFields = value.toFields();
7854
+ for (const f of valueFields) {
7855
+ fields.push(f.toString());
7856
+ }
7857
+ }
7858
+ finally {
7859
+ if (valueFields) {
7860
+ for (const f of valueFields) {
7861
+ f.free();
7862
+ }
7863
+ }
7864
+ value.free();
7865
+ }
7866
+ }
7867
+ }
7868
+ return fields;
7869
+ }
7870
+ /**
7871
+ * Verify an Aleo zkSnark proof against a verifying key and public inputs.
7872
+ *
7873
+ * This verifies a proof produced by an Aleo program that may not be deployed on chain.
7874
+ * It directly invokes the Varuna proof verification from snarkVM.
7875
+ *
7876
+ * **Note:** The proof must have been generated with the Fiat-Shamir domain separator
7877
+ * "snark_verify". Proofs generated via snarkVM with a different function name will fail
7878
+ * verification even if the circuit and inputs are correct.
7879
+ *
7880
+ * Inputs can be raw field element strings (e.g. "1field") or Aleo type strings
7881
+ * (e.g. "1u32", "true", "{ x: 1u8, y: 2u8 }"). Non-field inputs are automatically
7882
+ * converted to their field representation via Value.toFields().
7883
+ *
7884
+ * @param {VerificationOptions} options The verification parameters
7885
+ * @returns {boolean} True if the proof is valid, false otherwise
7886
+ *
7887
+ * @example
7888
+ * import { verifyProof } from "@provablehq/sdk/mainnet.js";
7889
+ *
7890
+ * // Using raw field elements:
7891
+ * const isValid = verifyProof({
7892
+ * verifyingKey: "verifier1...",
7893
+ * inputs: ["1field", "2field"],
7894
+ * proof: "proof1...",
7895
+ * });
7896
+ *
7897
+ * // Using Aleo types (automatically converted to fields):
7898
+ * const isValid2 = verifyProof({
7899
+ * verifyingKey: "verifier1...",
7900
+ * inputs: ["1u32", "2u32"],
7901
+ * proof: "proof1...",
7902
+ * });
7903
+ */
7904
+ function verifyProof(options) {
7905
+ const fieldInputs = inputsToFields(options.inputs);
7906
+ let verifyingKey;
7907
+ let proof;
7908
+ try {
7909
+ verifyingKey = VerifyingKey.fromString(options.verifyingKey);
7910
+ proof = Proof.fromString(options.proof);
7911
+ return verifyingKey.verify(fieldInputs, proof);
7912
+ }
7913
+ finally {
7914
+ if (verifyingKey)
7915
+ verifyingKey.free();
7916
+ if (proof)
7917
+ proof.free();
7918
+ }
7919
+ }
7920
+ /**
7921
+ * Verify a batch Aleo zkSnark proof against multiple verifying keys and their corresponding public inputs.
7922
+ *
7923
+ * Each verifying key is paired with one or more sets of public inputs (instances).
7924
+ * Inputs can be raw field element strings or Aleo type strings — non-field inputs
7925
+ * are automatically converted to their field representation.
7926
+ *
7927
+ * **Note:** The proof must have been generated with the Fiat-Shamir domain separator
7928
+ * "snark_verify_batch". Proofs generated with a different function name will fail
7929
+ * verification even if the circuits and inputs are correct.
7930
+ *
7931
+ * @param {BatchVerificationOptions} options The batch verification parameters
7932
+ * @returns {boolean} True if the batch proof is valid, false otherwise
7933
+ *
7934
+ * @example
7935
+ * import { verifyBatchProof } from "@provablehq/sdk/mainnet.js";
7936
+ *
7937
+ * const isValid = verifyBatchProof({
7938
+ * verifyingKeys: ["verifier1...", "verifier2..."],
7939
+ * inputs: [[["1field", "2field"]], [["3field"]]],
7940
+ * proof: "proof1...",
7941
+ * });
7942
+ */
7943
+ function verifyBatchProof(options) {
7944
+ const fieldInputs = options.inputs.map(circuit => circuit.map(instance => inputsToFields(instance)));
7945
+ const proof = Proof.fromString(options.proof);
7946
+ try {
7947
+ return VerifyingKey.verifyBatch(options.verifyingKeys, fieldInputs, proof);
7948
+ }
7949
+ finally {
7950
+ proof.free();
7951
+ }
7952
+ }
7953
+
7954
+ // ---------------------------------------------------------------------------
7955
+ // Converters
7956
+ // ---------------------------------------------------------------------------
7957
+ function toField(value) {
7958
+ if (value instanceof Field)
7959
+ return value;
7960
+ if (typeof value === "string")
7961
+ return Field.fromString(value);
7962
+ if (value instanceof Uint8Array)
7963
+ return Field.fromBytesLe(value);
7964
+ throw new Error("toField: expected Field, string, or Uint8Array");
7965
+ }
7966
+ function toGroup(value) {
7967
+ if (value instanceof Group)
7968
+ return value;
7969
+ if (value instanceof Field)
7970
+ return Group.fromField(value);
7971
+ if (typeof value === "string") {
7972
+ // If the string contains "field", treat it as an x-coordinate
7973
+ if (value.includes("field"))
7974
+ return Group.fromFieldString(value);
7975
+ return Group.fromString(value);
7976
+ }
7977
+ if (value instanceof Uint8Array) {
7978
+ // Try group deserialization first, fall back to field-to-group
7979
+ try {
7980
+ return Group.fromBytesLe(value);
7981
+ }
7982
+ catch {
7983
+ return Group.fromField(Field.fromBytesLe(value));
7984
+ }
7985
+ }
7986
+ throw new Error("toGroup: expected Group, Field, string, or Uint8Array");
7987
+ }
7988
+ function toViewKey(value) {
7989
+ if (value instanceof ViewKey)
7990
+ return value;
7991
+ if (typeof value === "string")
7992
+ return ViewKey.from_string(value);
7993
+ if (value instanceof Uint8Array)
7994
+ return ViewKey.fromBytesLe(value);
7995
+ throw new Error("toViewKey: expected ViewKey, string, or Uint8Array");
7996
+ }
7997
+ function toSignature(value) {
7998
+ if (value instanceof Signature)
7999
+ return value;
8000
+ if (typeof value === "string")
8001
+ return Signature.from_string(value);
8002
+ if (value instanceof Uint8Array)
8003
+ return Signature.fromBytesLe(value);
8004
+ throw new Error("toSignature: expected Signature, string, or Uint8Array");
8005
+ }
8006
+ function toAddress(value) {
8007
+ if (value instanceof Address)
8008
+ return value;
8009
+ if (typeof value === "string")
8010
+ return Address.from_string(value);
8011
+ if (value instanceof Uint8Array)
8012
+ return Address.fromBytesLe(value);
8013
+ throw new Error("toAddress: expected Address, string, or Uint8Array");
8014
+ }
8015
+ // ---------------------------------------------------------------------------
8016
+ // Type guards
8017
+ // ---------------------------------------------------------------------------
8018
+ /** Returns `true` if the strategy provides a `viewKey` for deriving record view keys. */
8019
+ function isViewKeyStrategy(r) {
8020
+ return r != null && "viewKey" in r;
8021
+ }
8022
+ /** Returns `true` if the strategy provides pre-computed `inputIds`. */
8023
+ function isInputIdStrategy(r) {
8024
+ return r != null && "inputIds" in r;
8025
+ }
8026
+ /** Returns `true` if the strategy provides explicit `recordViewKeys` (or is the default empty variant). */
8027
+ function isRecordViewKeyStrategy(r) {
8028
+ if (r == null || isViewKeyStrategy(r) || isInputIdStrategy(r))
8029
+ return false;
8030
+ const keys = Object.keys(r);
8031
+ return keys.length === 0 || keys.every((k) => k === "recordViewKeys" || k === "gammas");
8032
+ }
8033
+
8034
+ // ---------------------------------------------------------------------------
8035
+ // buildExecutionRequestFromExternallySignedData
8036
+ // ---------------------------------------------------------------------------
8037
+ /**
8038
+ * Build an ExecutionRequest from externally signed data.
8039
+ *
8040
+ * The `strategy` parameter determines how record input IDs are resolved:
8041
+ * - `{ recordViewKeys?, gammas? }` — explicit record view keys and gammas
8042
+ * - `{ viewKey, gammas? }` — derive record view keys from a ViewKey
8043
+ * - `{ inputIds }` — pre-computed input IDs (Field or [Field, Group, Field, Field, Field] tuples)
8044
+ *
8045
+ * @throws {Error} If `strategy` is not a valid `InputStrategy` variant.
8046
+ *
8047
+ * @example
8048
+ * // With explicit record view keys
8049
+ * buildExecutionRequestFromExternallySignedData(
8050
+ * { programId, functionName, inputs, inputTypes, signature, tvk, signer, skTag },
8051
+ * { recordViewKeys: [...], gammas: [...] },
8052
+ * );
8053
+ *
8054
+ * // With a view key
8055
+ * buildExecutionRequestFromExternallySignedData(
8056
+ * { programId, functionName, inputs, inputTypes, signature, tvk, signer, skTag },
8057
+ * { viewKey: "AViewKey1..." },
8058
+ * );
8059
+ *
8060
+ * // With pre-computed input IDs
8061
+ * buildExecutionRequestFromExternallySignedData(
8062
+ * { programId, functionName, inputs, inputTypes, signature, tvk, signer, skTag },
8063
+ * { inputIds: [...] },
8064
+ * );
8065
+ */
8066
+ function buildExecutionRequestFromExternallySignedData(params, strategy = {}) {
8067
+ const { programId, functionName, inputs, inputTypes, signature, tvk, signer, skTag } = params;
8068
+ const sig = toSignature(signature);
8069
+ const tvkField = toField(tvk);
8070
+ const signerAddr = toAddress(signer);
8071
+ const skTagField = toField(skTag);
8072
+ if (isInputIdStrategy(strategy)) {
8073
+ const convertedIds = strategy.inputIds.map((id) => {
8074
+ if (Array.isArray(id)) {
8075
+ return [toField(id[0]), toGroup(id[1]), toField(id[2]), toField(id[3]), toField(id[4])];
8076
+ }
8077
+ return toField(id);
8078
+ });
8079
+ return ExecutionRequest.fromExternallySignedDataWithInputIds(programId, functionName, inputs, inputTypes, sig, tvkField, signerAddr, skTagField, convertedIds);
8080
+ }
8081
+ if (isViewKeyStrategy(strategy)) {
8082
+ return ExecutionRequest.fromExternallySignedDataWithViewKey(programId, functionName, inputs, inputTypes, sig, tvkField, signerAddr, skTagField, toViewKey(strategy.viewKey), strategy.gammas ? strategy.gammas.map(toGroup) : undefined);
8083
+ }
8084
+ if (isRecordViewKeyStrategy(strategy)) {
8085
+ return ExecutionRequest.fromExternallySignedData(programId, functionName, inputs, inputTypes, sig, tvkField, signerAddr, skTagField, strategy.recordViewKeys ? strategy.recordViewKeys.map(toField) : undefined, strategy.gammas ? strategy.gammas.map(toGroup) : undefined);
8086
+ }
8087
+ throw new Error("buildExecutionRequestFromExternallySignedData: strategy must be a RecordViewKeyStrategy ({ recordViewKeys?, gammas? }), "
8088
+ + "ViewKeyStrategy ({ viewKey, gammas? }), or InputIdStrategy ({ inputIds }). "
8089
+ + `Received: ${JSON.stringify(strategy)}`);
8090
+ }
8091
+ async function computeExternalSigningInputs(options) {
8092
+ const { programName, functionName, inputs, inputTypes, isRoot, checksum, viewKey, outputFormat = "string" } = options;
8093
+ // Convert FieldLike/ViewKeyLike to WASM types (or null)
8094
+ const checksumField = checksum != null ? toField(checksum) : null;
8095
+ const viewKeyObj = viewKey != null ? toViewKey(viewKey) : null;
8096
+ try {
8097
+ const raw = (await ExecutionRequest.computeExternalSigningInputs(programName, functionName, inputs, inputTypes, isRoot, checksumField, viewKeyObj));
8098
+ // Normalize camelCase: WASM may return function_id
8099
+ const functionIdStr = (raw.functionId ?? raw.function_id);
8100
+ const isRootBool = raw.isRoot === "1field";
8101
+ if (outputFormat === "bytes") {
8102
+ return {
8103
+ functionId: fieldStringToBytes(functionIdStr),
8104
+ isRoot: isRootBool,
8105
+ requestInputs: raw.requestInputs.map(serializeRequestSignInputToBytes),
8106
+ checksum: raw.checksum ? fieldStringToBytes(raw.checksum) : undefined,
8107
+ signer: raw.signer ? raw.signer.to_string() : undefined,
8108
+ skTag: raw.skTag ? raw.skTag.toString() : undefined,
8109
+ };
8110
+ }
8111
+ return {
8112
+ functionId: functionIdStr,
8113
+ isRoot: isRootBool,
8114
+ requestInputs: raw.requestInputs,
8115
+ checksum: raw.checksum ?? undefined,
8116
+ signer: raw.signer ? raw.signer.to_string() : undefined,
8117
+ skTag: raw.skTag ? raw.skTag.toString() : undefined,
8118
+ };
8119
+ }
8120
+ catch (e) {
8121
+ const msg = e instanceof Error ? e.message : String(e);
8122
+ logAndThrow(`Error computing public message payload: ${msg}`);
8123
+ }
8124
+ }
8125
+ // ---------------------------------------------------------------------------
8126
+ // Bytes conversion helpers
8127
+ // ---------------------------------------------------------------------------
8128
+ /** Convert a field-element string (e.g. `"123field"`) to little-endian bytes. */
8129
+ function fieldStringToBytes(s) {
8130
+ return Field.fromString(s).toBytesLe();
8131
+ }
8132
+ /** Convert a {@link RequestSignInput<"string">} to its bytes-serialised equivalent. */
8133
+ function serializeRequestSignInputToBytes(input) {
8134
+ return {
8135
+ signingInputType: input.signingInputType,
8136
+ index: fieldStringToBytes(input.index),
8137
+ data: input.data.map(fieldStringToBytes),
8138
+ name: input.name,
8139
+ h: input.h ? fieldStringToBytes(input.h) : undefined,
8140
+ tag: input.tag ? fieldStringToBytes(input.tag) : undefined,
8141
+ recordViewKey: input.recordViewKey ? fieldStringToBytes(input.recordViewKey) : undefined,
8142
+ };
8143
+ }
7766
8144
 
7767
8145
  // @TODO: This function is no longer needed, remove it.
7768
8146
  async function initializeWasm() {
7769
8147
  console.warn("initializeWasm is deprecated, you no longer need to use it");
7770
8148
  }
7771
8149
 
7772
- export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KeyVerificationError as ChecksumMismatchError, DecryptionNotEnabledError, InvalidLocatorError, KEY_STORE, KeyVerificationError, MemKeyVerifier, 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, RecordNotFoundError, RecordScanner, RecordScannerRequestError, SealanceMerkleTree, UUIDError, VALID_TRANSFER_TYPES, ViewKeyNotStoredError, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptViewKey, initializeWasm, isProveApiErrorBody, isProvingResponse, logAndThrow, sha256Hex, zeroizeBytes };
8150
+ export { Account, AleoKeyProvider, AleoKeyProviderParams, AleoNetworkClient, BlockHeightSearch, CREDITS_PROGRAM_KEYS, KeyVerificationError as ChecksumMismatchError, DecryptionNotEnabledError, InvalidLocatorError, KEY_STORE, KeyVerificationError, MemKeyVerifier, 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, RecordNotFoundError, RecordScanner, RecordScannerRequestError, SealanceMerkleTree, UUIDError, VALID_TRANSFER_TYPES, ViewKeyNotStoredError, buildExecutionRequestFromExternallySignedData, computeExternalSigningInputs, encryptAuthorization, encryptProvingRequest, encryptRegistrationRequest, encryptViewKey, initializeWasm, inputsToFields, isInputIdStrategy, isProveApiErrorBody, isProvingResponse, isRecordViewKeyStrategy, isViewKeyStrategy, logAndThrow, provingKeyLocator, sha256Hex, toAddress, toField, toGroup, toSignature, toViewKey, translationKeyLocator, verifyBatchProof, verifyProof, verifyingKeyLocator, zeroizeBytes };
7773
8151
  //# sourceMappingURL=browser.js.map