@provablehq/veil-aleo-sdk 0.4.0 → 0.5.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.
package/dist/index.d.ts CHANGED
@@ -231,6 +231,7 @@ interface AleoSdk {
231
231
  consumerId?: string;
232
232
  account?: LocalAccount<'privateKey'>;
233
233
  confirmationTimeout?: number;
234
+ useFeeMaster?: boolean;
234
235
  }): ProvingConfig;
235
236
  /**
236
237
  * Creates a record scanner backed by Provable's Record Scanner Service.
@@ -286,6 +287,7 @@ interface AleoSdk {
286
287
  proverUrl?: string;
287
288
  apiKey?: string;
288
289
  consumerId?: string;
290
+ useFeeMaster?: boolean;
289
291
  /**
290
292
  * Record provider for `requestRecords`. Not wired by default — pass
291
293
  * `aleo.createRemoteScanner(...)` or any
package/dist/index.js CHANGED
@@ -318,7 +318,8 @@ function buildSdk(initialNetwork, initialSdk) {
318
318
  inputs: execOptions.inputs,
319
319
  priorityFee,
320
320
  privateFee: execOptions.privateFee ?? false,
321
- broadcast: true
321
+ broadcast: true,
322
+ useFeeMaster: options.useFeeMaster ?? true
322
323
  });
323
324
  const dpsClient = new AleoNetworkClient(options.proverUrl);
324
325
  response = await dpsClient.submitProvingRequest({
@@ -523,7 +524,8 @@ function buildSdk(initialNetwork, initialSdk) {
523
524
  proverUrl: options.proverUrl,
524
525
  apiKey: options.apiKey,
525
526
  consumerId: options.consumerId,
526
- account
527
+ account,
528
+ ...options.useFeeMaster !== void 0 ? { useFeeMaster: options.useFeeMaster } : {}
527
529
  });
528
530
  const publicClient = createPublicClient({ transport });
529
531
  if (options.records) {
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/mnemonic.ts"],"sourcesContent":["/**\n * @provablehq/veil-aleo-sdk\n *\n * Loads `@provablehq/sdk` for a specific Aleo network and exposes the SDK's\n * functionality bound to that network's setup parameters.\n *\n * Usage:\n * import { loadNetwork } from '@provablehq/veil-aleo-sdk'\n * import { http } from '@provablehq/veil-core'\n *\n * const aleo = await loadNetwork('mainnet')\n *\n * const account = aleo.privateKeyToAccount('APrivateKey1...')\n * const { publicClient, walletClient } = aleo.createAleoClient({\n * privateKey: 'APrivateKey1...',\n * networkUrl: 'https://api.provable.com/v2',\n * })\n *\n * Switching networks: load a new handle. Existing accounts remain valid —\n * Aleo private keys, view keys, and addresses are network-agnostic.\n */\n\nimport { loadNetwork as loadSdk } from '@provablehq/sdk/dynamic.js'\nimport {\n Account,\n AleoKeyProvider,\n Program,\n ProgramManager,\n RecordCiphertext as StaticRecordCiphertext,\n ViewKey as StaticViewKey,\n getOrInitConsensusVersionTestHeights,\n} from '@provablehq/sdk'\nimport { DEVNODE_PRIVATE_KEY, DEVNODE_ADDR } from '@provablehq/veil-aleo-devnode'\nexport { DEVNODE_PRIVATE_KEY, DEVNODE_ADDR }\nimport type { LocalAccount } from '@provablehq/veil-core'\nimport type { ProvingConfig, BuildTransactionOptions, BuildDeploymentOptions, SimulateOptions, ExecuteOptions, RawSimulateResult, RawExecuteResult } from '@provablehq/veil-core'\nimport type { OwnedRecord, RecordProvider, StandaloneRecordScanner, RequestRecordsParameters } from '@provablehq/veil-core'\nimport type { Network, PublicClient, WalletClient } from '@provablehq/veil-core'\nimport {\n createPublicClient,\n createWalletClient,\n http,\n BaseError,\n ProvingError,\n ConfigurationError,\n classifyBroadcastError,\n classifyProvingError,\n waitForConfirmation,\n extractTransitions,\n} from '@provablehq/veil-core'\nimport type { Decryptor } from '@provablehq/veil-core'\nimport { generateMnemonic, mnemonicToHDKey, type AleoDerivationId } from './mnemonic.js'\n\nexport {\n BLS12377HDKey,\n generateMnemonic,\n validateMnemonic,\n validateWord,\n mnemonicToSeed,\n mnemonicToHDKey,\n STANDARD_PATH,\n LEGACY_PATH,\n type AleoDerivationId,\n} from './mnemonic.js'\n\n/** Networks supported by `@provablehq/sdk/dynamic.js`. */\nexport type SupportedNetwork = 'mainnet' | 'testnet'\n\n// `loadSdk('testnet')` and `loadSdk('mainnet')` return modules whose runtime\n// classes have the same shape. The narrowed-to-testnet type is used as the\n// canonical handle to avoid TS's union-of-modules confusion.\ntype SdkModule = Awaited<ReturnType<typeof loadSdk<'testnet'>>>\n\n/**\n * A network-bound SDK handle. All functions on this handle use the binary\n * set loaded for the named network.\n *\n * Most key/account operations (`privateKeyToAccount`, `mnemonicToAccount`,\n * `generateAccount`, `decryptRecord`, `verifySignature`) are mathematically\n * network-agnostic — the same private key (or mnemonic) derives the same\n * address and view key regardless of which network's binary was loaded.\n * Proving and program operations (`createProvingConfig`, `createAleoClient`,\n * scanners) are network-bound.\n */\nexport interface AleoSdk {\n /** The network this handle is bound to. */\n readonly network: SupportedNetwork\n\n /** Creates a `LocalAccount` from an Aleo private key. */\n privateKeyToAccount(privateKey: string): LocalAccount<'privateKey'>\n\n /**\n * Creates a `LocalAccount` from a BIP39 mnemonic phrase using Aleo's\n * BLS12-377 HD derivation (matches Shield wallet derivation).\n *\n * Defaults to the SLIP-0044 Aleo coin type path `m/44'/683'`, account\n * index 0. Pass `derivation: 'legacy'` to use the pre-registration path\n * `m/44'/0'` for compatibility with older wallets.\n */\n mnemonicToAccount(\n mnemonic: string,\n options?: { index?: number; derivation?: AleoDerivationId },\n ): LocalAccount<'mnemonic'>\n\n /**\n * Generates a fresh BIP39 mnemonic and derives its Aleo account in one call.\n * Pure and local — no network access. The caller MUST persist the returned\n * mnemonic; it is the only way to re-derive the account.\n *\n * @param options.strength Entropy bits: 128 (12 words, default) or 256 (24 words).\n * @param options.index Account index on the derivation path. Defaults to 0.\n * @param options.derivation Derivation path id. Defaults to `'standard'`\n * (`m/44'/683'`); pass `'legacy'` for pre-registration `m/44'/0'` wallets.\n * @returns The generated mnemonic and the account derived from it.\n *\n * @example\n * const { mnemonic, account } = aleo.generateMnemonicAccount()\n * // store `mnemonic` safely; `account.address` is ready to use\n */\n generateMnemonicAccount(options?: {\n strength?: 128 | 256\n index?: number\n derivation?: AleoDerivationId\n }): { mnemonic: string; account: LocalAccount<'mnemonic'> }\n\n /** Creates a new random Aleo account. */\n generateAccount(): LocalAccount<'privateKey'>\n\n /** Decrypts a record ciphertext using a view key. */\n decryptRecord(viewKey: string, ciphertext: string): string\n\n /** Verifies a signature against a message and address. */\n verifySignature(address: string, message: Uint8Array, signature: string): boolean\n\n /** Creates an `AleoNetworkClient` for direct SDK access. */\n createNetworkClient(url: string): InstanceType<SdkModule['AleoNetworkClient']>\n\n /** Creates a `ProvingConfig` for `createWalletClient({ proving })`. */\n createProvingConfig(options: {\n mode: 'delegated' | 'local'\n networkUrl: string\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n account?: LocalAccount<'privateKey'>\n confirmationTimeout?: number\n }): ProvingConfig\n\n /**\n * Creates a record scanner backed by Provable's Record Scanner Service.\n *\n * The first `requestRecords` call registers the account's view key with the\n * service (a network round-trip) to obtain the UUID scanning requires;\n * subsequent calls reuse it. `setAccount` resets the registration.\n *\n * The provider implements `switchNetwork`, so a wallet client carrying it\n * re-targets record scanning when `switchChain` runs — the scanner rebuilds\n * against the new network and re-registers lazily on the next scan.\n *\n * @param options.url Base URL of the service (the SDK appends the network\n * segment — do not include it).\n * @param options.consumerId Consumer id used for JWT refresh.\n * @param options.apiKey Optional API key for the authenticated service\n * (e.g. the hosted Provable RSS). Omit for an open/unauthenticated service.\n * @param options.startBlock Optional block height to begin scanning from at\n * registration. Defaults to 0 (full history).\n */\n createRemoteScanner(options: {\n url: string\n consumerId: string\n apiKey?: string\n startBlock?: number\n }): RecordProvider\n\n /**\n * Creates a standalone record scanner with an explicit view key.\n *\n * Like {@link createRemoteScanner}, the first `requestRecords` registers the\n * view key with the service (a network round-trip) to obtain the scanning UUID.\n *\n * @param options.url Base URL of the service (the SDK appends the network segment).\n * @param options.consumerId Consumer id used for JWT refresh.\n * @param options.viewKey The view key (`AViewKey1…`) to scan and decrypt with.\n * @param options.apiKey Optional API key for the authenticated service. Omit\n * for an open/unauthenticated service.\n * @param options.startBlock Optional block height to begin scanning from at\n * registration. Defaults to 0 (full history).\n */\n createStandaloneScanner(options: {\n url: string\n consumerId: string\n viewKey: string\n apiKey?: string\n startBlock?: number\n }): StandaloneRecordScanner\n\n /** Creates a fully-wired Aleo client from a private key and network URL. */\n createAleoClient(options: {\n privateKey: string\n networkUrl: string\n provingMode?: 'delegated' | 'local'\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n /**\n * Record provider for `requestRecords`. Not wired by default — pass\n * `aleo.createRemoteScanner(...)` or any\n * custom `RecordProvider`. `requestRecords` throws with a setup hint\n * when no provider is configured.\n */\n records?: RecordProvider\n }): { publicClient: PublicClient; walletClient: WalletClient; account: LocalAccount<'privateKey'> }\n}\n\n/**\n * Loads `@provablehq/sdk` for the named network and returns a network-bound\n * handle. The SDK module cache memoizes the load — calling twice for the\n * same network returns the same binary set without re-instantiating.\n */\nexport async function loadNetwork(name: SupportedNetwork): Promise<AleoSdk> {\n const sdk = (await loadSdk(name)) as SdkModule\n return buildSdk(name, sdk)\n}\n\nfunction buildSdk(initialNetwork: SupportedNetwork, initialSdk: SdkModule): AleoSdk {\n // Mutable handle so `createProvingConfig().switchNetwork()` can swap the\n // underlying binary set without rebuilding the wallet client.\n let currentSdk: SdkModule = initialSdk\n const network = initialNetwork\n const {\n Account,\n PrivateKey,\n Signature,\n Address,\n ViewKey,\n AleoNetworkClient,\n RecordScanner,\n RecordCiphertext,\n } = initialSdk\n\n\n\n function mnemonicToAccount(\n mnemonic: string,\n options?: { index?: number; derivation?: AleoDerivationId },\n ): LocalAccount<'mnemonic'> {\n const hd = mnemonicToHDKey(mnemonic, options)\n // wasm-bindgen exports the snake_case name; it is not a typo.\n const privateKey = (PrivateKey as unknown as {\n from_seed_unchecked: (seed: Uint8Array) => InstanceType<SdkModule['PrivateKey']>\n }).from_seed_unchecked(hd.key).to_string()\n return { ...privateKeyToAccount(privateKey), source: 'mnemonic' }\n }\n\n function generateMnemonicAccount(options?: {\n strength?: 128 | 256\n index?: number\n derivation?: AleoDerivationId\n }): { mnemonic: string; account: LocalAccount<'mnemonic'> } {\n const mnemonic = generateMnemonic(options?.strength ?? 128)\n const { strength: _strength, ...derivationOptions } = options ?? {}\n return { mnemonic, account: mnemonicToAccount(mnemonic, derivationOptions) }\n }\n\n function generateAccount(): LocalAccount<'privateKey'> {\n const sdkAccount = new Account()\n return privateKeyToAccount(sdkAccount.privateKey().to_string())\n }\n\n function decryptRecord(viewKeyString: string, ciphertext: string): string {\n return ViewKey.from_string(viewKeyString).decrypt(ciphertext)\n }\n\n function verifySignature(\n addressString: string,\n message: Uint8Array,\n signatureString: string,\n ): boolean {\n const sig = Signature.from_string(signatureString)\n const addr = Address.from_string(addressString)\n return sig.verify(addr, message)\n }\n\n function createNetworkClient(url: string): InstanceType<SdkModule['AleoNetworkClient']> {\n return new AleoNetworkClient(url)\n }\n\n function createProvingConfig(options: {\n mode: 'delegated' | 'local'\n networkUrl: string\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n account?: LocalAccount<'privateKey'>\n /** Timeout in ms for waiting for transaction confirmation (default: 300_000 = 5 min) */\n confirmationTimeout?: number\n }): ProvingConfig {\n // Each call reads from currentSdk so switchNetwork can swap the binary set\n // without rebuilding the wallet client.\n let networkUrl = options.networkUrl\n let keyProvider = new currentSdk.AleoKeyProvider()\n keyProvider.useCache(true)\n\n return {\n mode: options.mode,\n url: options.proverUrl,\n\n buildTransaction: async (txOptions: BuildTransactionOptions) => {\n const programManager = new currentSdk.ProgramManager(\n networkUrl,\n keyProvider,\n undefined,\n )\n\n if (options.account) {\n const sdkAccount = new currentSdk.Account({ privateKey: options.account.privateKey })\n programManager.setAccount(sdkAccount)\n }\n\n // The user-facing API takes dynamic-dispatch import names (`string[]`);\n // the SDK needs a name → source map covering BOTH the program's static\n // imports (declared in the `import` block) and the user's dynamic ones.\n // Auto-discover static imports first, then add the user-provided\n // dynamic ones on top. The SDK's ProgramImports values can be string\n // or Program; its return type is mirrored instead of reconstructed.\n type SdkProgramImports = Awaited<\n ReturnType<InstanceType<SdkModule['AleoNetworkClient']>['getProgramImports']>\n >\n let resolvedImports: SdkProgramImports | undefined\n if (txOptions.imports && txOptions.imports.length > 0) {\n const programSource = await programManager.networkClient.getProgram(txOptions.programName)\n const staticImports = await programManager.networkClient.getProgramImports(programSource)\n const merged: SdkProgramImports = { ...staticImports }\n for (const name of txOptions.imports) {\n merged[name] = await programManager.networkClient.getProgram(name)\n }\n resolvedImports = merged\n }\n\n const tx = await programManager.buildExecutionTransaction({\n programName: txOptions.programName,\n functionName: txOptions.functionName,\n priorityFee: 0,\n privateFee: txOptions.privateFee ?? false,\n inputs: txOptions.inputs,\n ...(resolvedImports ? { imports: resolvedImports } : {}),\n })\n\n return JSON.parse(tx.toString())\n },\n\n buildDeployment: async (deployOptions: BuildDeploymentOptions) => {\n const programManager = new currentSdk.ProgramManager(\n networkUrl,\n keyProvider,\n undefined,\n )\n\n if (options.account) {\n const sdkAccount = new currentSdk.Account({ privateKey: options.account.privateKey })\n programManager.setAccount(sdkAccount)\n }\n\n const tx = await programManager.buildDeploymentTransaction(\n deployOptions.program,\n 0,\n deployOptions.privateFee ?? false,\n )\n\n return JSON.parse(tx.toString())\n },\n\n simulate: async (simOptions: SimulateOptions): Promise<RawSimulateResult> => {\n const programManager = new currentSdk.ProgramManager(networkUrl, keyProvider, undefined)\n if (options.account) {\n programManager.setAccount(new currentSdk.Account({ privateKey: options.account.privateKey }))\n }\n\n // Self-custody decryptor: same view-key-based decryptor as the execute path.\n const accountViewKey = options.account ? ViewKey.from_string(options.account.viewKey) : undefined\n const decryptor: Decryptor | undefined = accountViewKey\n ? (ciphertext: string) => {\n const ct = RecordCiphertext.fromString(ciphertext)\n return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : null\n }\n : undefined\n\n // `buildAuthorization` runs the function (with cross-program calls) and produces an\n // Authorization whose transitions carry program/function metadata and the actual\n // outputs — same structure a confirmed Transaction has, minus the proof.\n const authorization = await programManager.buildAuthorization({\n programName: simOptions.programName,\n functionName: simOptions.functionName,\n inputs: simOptions.inputs,\n programSource: simOptions.programSource,\n programImports: simOptions.programImports,\n })\n\n // Convert the wasm Transition objects into the wire-shaped tx that extractTransitions\n // consumes. Private outputs come back from an Authorization as TVK-encrypted ciphertexts\n // (Aleo's on-chain privacy model); decrypt with the caller's TVK first so plaintext\n // values are visible. `transition.toString()` emits the same wire-format JSON the chain\n // returns from `/transaction/confirmed/{id}` — Aleo-typed string values like '10u32',\n // 'aleo1...', or 'record1...' under each output's `value`.\n const tx = {\n execution: {\n transitions: authorization.transitions().map((t: any) => {\n let source = t\n if (accountViewKey) {\n try {\n source = t.decryptTransition(t.tvk(accountViewKey))\n } catch {\n // Foreign transition signed by another caller — leave outputs encrypted.\n }\n }\n return JSON.parse(source.toString())\n }),\n },\n }\n\n const { transitions, outputs } = extractTransitions(tx, decryptor)\n return { transitions, outputs }\n },\n\n execute: async (execOptions: ExecuteOptions): Promise<RawExecuteResult> => {\n const programManager = new currentSdk.ProgramManager(networkUrl, keyProvider, undefined)\n if (options.account) {\n programManager.setAccount(new currentSdk.Account({ privateKey: options.account.privateKey }))\n }\n\n /** Convert microcredits (Veil API) to credits (SDK API) for priority fee */\n const priorityFee = Number(execOptions.fee) / 1_000_000\n\n /** Self-custody decryptor: use the local account's view key to decrypt owned record ciphertexts. */\n const accountViewKey = options.account ? ViewKey.from_string(options.account.viewKey) : undefined\n const decryptor: Decryptor | undefined = accountViewKey\n ? (ciphertext: string) => {\n const ct = RecordCiphertext.fromString(ciphertext)\n return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : null\n }\n : undefined\n\n /** Build a Veil publicClient bound to the current networkUrl for chain polling. */\n const buildPollingClient = () =>\n createPublicClient({ transport: http(networkUrl, { network: network as Network }) })\n\n if (options.mode === 'delegated') {\n if (!options.proverUrl) throw new ConfigurationError('Delegated execution requires proverUrl. Pass proverUrl to createProvingConfig or createAleoClient.')\n\n let response: any\n try {\n const provingRequest = await programManager.provingRequest({\n programName: execOptions.programName,\n programSource: execOptions.programSource,\n programImports: execOptions.programImports,\n functionName: execOptions.functionName,\n inputs: execOptions.inputs,\n priorityFee,\n privateFee: execOptions.privateFee ?? false,\n broadcast: true,\n })\n\n const dpsClient = new AleoNetworkClient(options.proverUrl)\n response = await dpsClient.submitProvingRequest({\n provingRequest,\n url: options.proverUrl,\n apiKey: options.apiKey,\n consumerId: options.consumerId,\n })\n } catch (e) {\n if (e instanceof BaseError) throw e\n throw classifyProvingError(e)\n }\n\n const txId = response.transaction?.id\n if (!txId) throw new ConfigurationError('DPS response did not contain a transaction ID — check prover service configuration.')\n\n const confirmedTx = await waitForConfirmation(buildPollingClient(), txId, options.confirmationTimeout)\n const { transitions, outputs } = extractTransitions(confirmedTx, decryptor)\n return { transactionId: txId, transitions, outputs }\n\n } else {\n let tx: any\n try {\n tx = await programManager.buildExecutionTransaction({\n programName: execOptions.programName,\n functionName: execOptions.functionName,\n inputs: execOptions.inputs,\n priorityFee,\n privateFee: execOptions.privateFee ?? false,\n program: execOptions.programSource,\n imports: execOptions.programImports,\n })\n } catch (e) {\n if (e instanceof BaseError) throw e\n throw new ProvingError({ message: e instanceof Error ? e.message : String(e), cause: e as Error })\n }\n\n let txId: string\n try {\n const submitClient = new AleoNetworkClient(networkUrl)\n submitClient.setVerboseErrors(false)\n txId = await submitClient.submitTransaction(tx)\n } catch (e) {\n if (e instanceof BaseError) throw e\n throw classifyBroadcastError(e)\n }\n\n const confirmedTx = await waitForConfirmation(buildPollingClient(), txId, options.confirmationTimeout)\n const { transitions, outputs } = extractTransitions(confirmedTx, decryptor)\n return { transactionId: txId, transitions, outputs }\n }\n },\n\n decrypt: async (cipherText) => {\n if (!options.account?.viewKey) {\n throw new Error(\n 'decrypt requires an account with a viewKey on the proving config.',\n )\n }\n return currentSdk.ViewKey.from_string(options.account.viewKey).decrypt(cipherText)\n },\n\n switchNetwork: async (newNetwork) => {\n if (newNetwork !== 'mainnet' && newNetwork !== 'testnet') {\n throw new Error(\n `loadNetwork supports 'mainnet' or 'testnet' (received '${newNetwork}').`,\n )\n }\n currentSdk = (await loadSdk(newNetwork as SupportedNetwork)) as SdkModule\n keyProvider = new currentSdk.AleoKeyProvider()\n keyProvider.useCache(true)\n },\n }\n }\n\n // The RSS returns record fields in snake_case (record_plaintext,\n // program_name, …); the veil OwnedRecord contract is camelCase. Map them —\n // a bare cast silently leaves recordPlaintext undefined, which reads as an\n // unspendable wallet. Fields whose two casings coincide are read directly;\n // the rest accept either case so a future camelCase SDK build keeps working.\n // `uid` and `recordView` are privacy-wallet-adapter concepts the RSS does\n // not supply, so they are intentionally omitted.\n function toOwnedRecord(raw: Record<string, unknown>): OwnedRecord {\n const pick = (snake: string, camel: string): unknown => raw[snake] ?? raw[camel]\n return {\n blockHeight: pick('block_height', 'blockHeight') as number | undefined,\n blockTimestamp: pick('block_timestamp', 'blockTimestamp') as number | undefined,\n commitment: raw.commitment as string | undefined,\n functionName: pick('function_name', 'functionName') as string | undefined,\n outputIndex: pick('output_index', 'outputIndex') as number | undefined,\n owner: raw.owner as string | undefined,\n programName: pick('program_name', 'programName') as string,\n recordCiphertext: pick('record_ciphertext', 'recordCiphertext') as string | undefined,\n recordName: pick('record_name', 'recordName') as string | undefined,\n sender: raw.sender as string | undefined,\n spent: raw.spent as boolean | undefined,\n tag: raw.tag as string,\n transactionId: pick('transaction_id', 'transactionId') as string | undefined,\n transitionId: pick('transition_id', 'transitionId') as string | undefined,\n transactionIndex: pick('transaction_index', 'transactionIndex') as number | undefined,\n transitionIndex: pick('transition_index', 'transitionIndex') as number | undefined,\n recordPlaintext: (pick('record_plaintext', 'recordPlaintext') as string | undefined) ?? '',\n }\n }\n\n // A scanner's UUID is issued at registration; owned() rejects locally\n // without one. Register once, lazily, and memoize the in-flight promise so\n // concurrent scans share a single round-trip. Account or network changes\n // replace the whole object (one registration per scanner build).\n function makeRegisterOnce(startBlock: number) {\n let registration: Promise<void> | undefined\n return {\n ensure(\n scanner: InstanceType<SdkModule['RecordScanner']>,\n viewKey: ReturnType<SdkModule['ViewKey']['from_string']>,\n ): Promise<void> {\n if (!registration) {\n registration = (async () => {\n const result = await scanner.registerEncrypted(viewKey, startBlock)\n if (!result.ok) {\n registration = undefined // allow a later retry after a transient failure\n throw new Error(\n `Record scanner registration failed (HTTP ${result.status}): ${result.error?.message ?? 'unknown error'}`,\n )\n }\n })()\n }\n return registration\n },\n }\n }\n\n // Scans owned records with bounded retry. owned() returns a discriminated\n // result on HTTP error but *throws* on a network failure or an invalidated\n // UUID — both paths are retried here. A freshly-minted JWT can momentarily\n // hit an RSS backend that has not yet synced the credential (HTTP 401), and\n // the SDK caches that JWT for the scanner's lifetime — so between attempts it\n // is dropped (setJwtData(undefined) forces a re-mint), backed off, and retried,\n // giving the backend time to catch up. A non-transient status surfaces at once.\n //\n // 429/5xx are always transient; a 401/403 is only worth retrying when a JWT\n // can actually be re-minted (apiKey configured) — on an unauthenticated\n // scanner those are permanent, so retrying just burns backoff.\n async function scanOwned(\n scanner: InstanceType<SdkModule['RecordScanner']>,\n program: string,\n statusFilter: string | undefined,\n canReMint: boolean,\n ): Promise<OwnedRecord[]> {\n const ALWAYS_RETRY = new Set([429, 500, 502, 503, 504])\n const AUTH_RETRY = new Set([401, 403])\n const retryable = (status: number) => ALWAYS_RETRY.has(status) || (canReMint && AUTH_RETRY.has(status))\n const MAX_ATTEMPTS = 4\n let last = ''\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n try {\n const result = await scanner.owned({\n unspent: statusFilter !== 'spent',\n filter: { programs: [program] },\n })\n if (result.ok) return (result.data ?? []).map((r) => toOwnedRecord(r as Record<string, unknown>))\n last = `HTTP ${result.status}: ${result.error?.message ?? 'unknown error'}`\n if (!retryable(result.status)) break\n } catch (err) {\n // owned() throws (rather than returning a result) on a network failure\n // or an invalidated UUID — treat as transient and retry.\n last = err instanceof Error ? err.message : String(err)\n }\n if (attempt === MAX_ATTEMPTS - 1) break\n scanner.setJwtData(undefined) // drop the cached (rejected) JWT so the next call re-mints\n await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt))\n }\n throw new Error(`Record scan failed (${last})`)\n }\n\n function createRemoteScanner(options: {\n url: string\n consumerId: string\n apiKey?: string\n startBlock?: number\n }): RecordProvider {\n // The RecordScanner class is network-bound: a scanner built from a given\n // SDK module scans that module's network. Network switching rebuilds the\n // scanner (and the wasm view key) from the target network's module.\n let scannerSdk: Pick<SdkModule, 'RecordScanner' | 'ViewKey'> = { RecordScanner, ViewKey }\n let scanner: InstanceType<SdkModule['RecordScanner']> | undefined\n let viewKey: ReturnType<SdkModule['ViewKey']['from_string']> | undefined\n let viewKeyString: string | undefined\n let registration = makeRegisterOnce(options.startBlock ?? 0)\n\n function buildScanner() {\n if (!viewKeyString) return // no active account yet — nothing to rebuild\n viewKey = scannerSdk.ViewKey.from_string(viewKeyString)\n scanner = new scannerSdk.RecordScanner({\n url: options.url,\n consumerId: options.consumerId,\n ...(options.apiKey ? { apiKey: options.apiKey } : {}),\n viewKeys: [viewKey],\n decryptEnabled: true,\n autoReRegister: true,\n })\n // Each build gets its own registration: view keys register per account\n // AND per network, and the old promise stays bound to the scanner a\n // concurrent scan may still hold.\n registration = makeRegisterOnce(options.startBlock ?? 0)\n }\n\n return {\n setAccount: (account: { viewKey: string }) => {\n viewKeyString = account.viewKey\n buildScanner()\n },\n\n requestRecords: async (params: RequestRecordsParameters): Promise<OwnedRecord[]> => {\n if (!scanner) {\n throw new Error('No active account set on record scanner. Call setAccount() first.')\n }\n\n // Pin this scan to the current build: a concurrent setAccount or\n // switchNetwork swaps the closures, and mixing builds mid-scan would\n // register one scanner and scan another.\n const activeScanner = scanner\n const activeViewKey = viewKey!\n const activeRegistration = registration\n await activeRegistration.ensure(activeScanner, activeViewKey)\n return scanOwned(activeScanner, params.program, params.statusFilter, !!options.apiKey)\n },\n\n switchNetwork: async (newNetwork: string) => {\n if (newNetwork !== 'mainnet' && newNetwork !== 'testnet') {\n throw new Error(\n `Record scanning supports 'mainnet' or 'testnet' (received '${newNetwork}').`,\n )\n }\n scannerSdk = (await loadSdk(newNetwork as SupportedNetwork)) as SdkModule\n buildScanner()\n },\n }\n }\n\n function createStandaloneScanner(options: {\n url: string\n consumerId: string\n viewKey: string\n apiKey?: string\n startBlock?: number\n }): StandaloneRecordScanner {\n const viewKey = ViewKey.from_string(options.viewKey)\n const scanner = new RecordScanner({\n url: options.url,\n consumerId: options.consumerId,\n ...(options.apiKey ? { apiKey: options.apiKey } : {}),\n viewKeys: [viewKey],\n decryptEnabled: true,\n autoReRegister: true,\n })\n const registration = makeRegisterOnce(options.startBlock ?? 0)\n\n return {\n requestRecords: async (params: RequestRecordsParameters): Promise<OwnedRecord[]> => {\n await registration.ensure(scanner, viewKey)\n return scanOwned(scanner, params.program, params.statusFilter, !!options.apiKey)\n },\n }\n }\n\n function createAleoClient(options: {\n privateKey: string\n networkUrl: string\n provingMode?: 'delegated' | 'local'\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n records?: RecordProvider\n }): { publicClient: PublicClient; walletClient: WalletClient; account: LocalAccount<'privateKey'> } {\n const account = privateKeyToAccount(options.privateKey)\n const transport = http(options.networkUrl, { network: network as Network })\n\n const proving = createProvingConfig({\n mode: options.provingMode ?? 'delegated',\n networkUrl: options.networkUrl,\n proverUrl: options.proverUrl,\n apiKey: options.apiKey,\n consumerId: options.consumerId,\n account,\n })\n\n const publicClient = createPublicClient({ transport })\n\n if (options.records) {\n options.records.setAccount({ viewKey: account.viewKey })\n }\n\n const walletClient = createWalletClient({\n account,\n transport,\n proving,\n ...(options.records ? { recordProvider: options.records } : {}),\n })\n\n return { publicClient, walletClient, account }\n }\n\n return {\n network,\n privateKeyToAccount,\n mnemonicToAccount,\n generateMnemonicAccount,\n generateAccount,\n decryptRecord,\n verifySignature,\n createNetworkClient,\n createProvingConfig,\n createRemoteScanner,\n createStandaloneScanner,\n createAleoClient,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Standalone exports — synchronous helpers and devnode client factory.\n// These use the statically-imported SDK (testnet binaries) so they work\n// without an awaited loadNetwork() call.\n// ---------------------------------------------------------------------------\n\n// Consensus version activation heights the WASM layer assumes when building\n// devnode transactions. MUST mirror the CONSENSUS_VERSION_HEIGHTS default that\n// @provablehq/veil-aleo-devnode passes to the aleo-devnode process, so the transaction builder\n// and the node agree on which consensus version is active at each height. The\n// entry count must also equal the WASM SDK's consensus-version count exactly —\n// a shorter list panics with an opaque `unreachable` inside the WASM.\nconst DEVNODE_CONSENSUS_HEIGHTS = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16'\n\nfunction privateKeyToAccount(privateKey: string): LocalAccount<'privateKey'> {\n const sdkAccount = new Account({ privateKey })\n const address = sdkAccount.address().to_string()\n const viewKey = sdkAccount.viewKey().to_string()\n\n const signFn = async (message: Uint8Array): Promise<Uint8Array> => {\n const sig = sdkAccount.sign(message)\n return new TextEncoder().encode(sig.to_string())\n }\n\n return {\n type: 'local',\n source: 'privateKey',\n address,\n privateKey,\n viewKey,\n sign: signFn,\n signMessage: signFn,\n }\n}\n\n/** Creates a new random Aleo account (uses static SDK binaries). */\nexport function generateAccount(): LocalAccount<'privateKey'> {\n const sdkAccount = new Account()\n return privateKeyToAccount(sdkAccount.privateKey().to_string())\n}\n\n/**\n * Creates a fully-wired client pair pointing at a local Aleo Devnode instance.\n *\n * Devnode is a lightweight local Aleo node (similar to Foundry's Anvil) that\n * bypasses consensus and skips ZK proof generation, enabling rapid program iteration.\n * The seeded account is pre-funded; both key and socket address can be overridden.\n *\n * The returned wallet client supports `executeContract`. Its confirmation wait\n * resolves once the devnode includes the transaction in a block — automatic\n * after broadcast by default; under `manualBlockCreation` the caller must\n * advance blocks (e.g. a test client's `advanceBlock`) while the call is\n * pending. Record outputs owned by the client's account are decrypted to\n * plaintext in the result; foreign records are dropped.\n *\n * @example\n * ```ts\n * // Zero-config — uses seeded key and localhost:3030\n * const { publicClient, walletClient, account } = createDevnodeClient()\n *\n * // Custom key or socket address\n * const { publicClient, walletClient, account } = createDevnodeClient({\n * privateKey: 'APrivateKey1...',\n * socketAddr: '127.0.0.1:4040',\n * })\n * ```\n */\nexport function createDevnodeClient(options?: {\n privateKey?: string\n /** Socket address of the devnode, e.g. \"127.0.0.1:3030\" */\n socketAddr?: string\n}): { publicClient: PublicClient; walletClient: WalletClient; account: LocalAccount<'privateKey'> } {\n const url = `http://${options?.socketAddr ?? DEVNODE_ADDR}`\n const account = privateKeyToAccount(options?.privateKey ?? DEVNODE_PRIVATE_KEY)\n const sdkAccount = new Account({ privateKey: account.privateKey })\n const transport = http(url, { network: 'testnet' })\n\n const keyProvider = new AleoKeyProvider()\n keyProvider.useCache(true)\n\n // Initialize the wasm consensus heights before any wasm build or parse call\n // this client makes. Idempotent get-or-init: safe to call per client.\n getOrInitConsensusVersionTestHeights(DEVNODE_CONSENSUS_HEIGHTS)\n\n // Created before the proving config so `execute` can broadcast and poll\n // through the same transport-backed client the caller receives.\n const publicClient = createPublicClient({ transport })\n\n /**\n * Builds an unproven devnode execution transaction. `imports` must already\n * map program id → source; resolution of dynamic-dispatch import names\n * happens in `buildTransaction`, not here. Priority fees are always 0 on\n * the devnode path — a caller-supplied fee is ignored.\n */\n const buildExecutionTx = async (opts: {\n programName: string\n functionName: string\n inputs: string[]\n privateFee?: boolean | undefined\n imports?: Record<string, string> | undefined\n }) => {\n const programManager = new ProgramManager(url, keyProvider, undefined)\n programManager.setAccount(sdkAccount)\n return programManager.buildDevnodeExecutionTransaction({\n programName: opts.programName,\n functionName: opts.functionName,\n priorityFee: 0,\n privateFee: opts.privateFee ?? false,\n inputs: opts.inputs,\n ...(opts.imports ? { imports: opts.imports } : {}),\n })\n }\n\n const proving: ProvingConfig = {\n mode: 'devnode',\n buildDeployment: async (deployOptions: BuildDeploymentOptions) => {\n const programManager = new ProgramManager(url, keyProvider, undefined)\n programManager.setAccount(sdkAccount)\n const tx = await programManager.buildDevnodeDeploymentTransaction({\n program: deployOptions.program,\n priorityFee: 0,\n privateFee: deployOptions.privateFee ?? false,\n })\n return JSON.parse(tx.toString())\n },\n buildTransaction: async (txOptions: BuildTransactionOptions) => {\n // Fetch program sources for any call.dynamic targets the caller declared,\n // and recursively include their static imports as well.\n // Use direct REST calls instead of the SDK network client to avoid the\n // /latest_edition endpoint which returns 500 on the devnode.\n let imports: Record<string, string> | undefined\n if (txOptions.imports && txOptions.imports.length > 0) {\n const networkClient = new ProgramManager(url, keyProvider, undefined).networkClient\n imports = {}\n const queue = [...txOptions.imports]\n const seen = new Set<string>()\n while (queue.length > 0) {\n const name = queue.shift()!\n if (seen.has(name)) continue\n seen.add(name)\n const source = await networkClient.getProgram(name); // automatically throws.\n imports[name] = source;\n const importNames = Program.fromString(source).getImports(); // Invoke `wasm` to avoid regex.\n for (const dep of importNames) {\n if (dep && !seen.has(dep)) queue.push(dep)\n }\n }\n }\n\n const tx = await buildExecutionTx({\n programName: txOptions.programName,\n functionName: txOptions.functionName,\n inputs: txOptions.inputs,\n privateFee: txOptions.privateFee,\n imports,\n })\n return JSON.parse(tx.toString())\n },\n execute: async (execOptions: ExecuteOptions): Promise<RawExecuteResult> => {\n const tx = await buildExecutionTx({\n programName: execOptions.programName,\n functionName: execOptions.functionName,\n inputs: execOptions.inputs,\n privateFee: execOptions.privateFee,\n imports: execOptions.programImports,\n })\n\n // Broadcast through the same transport-backed request writeContract uses.\n const txId = (await publicClient.request({\n method: 'sendTransaction',\n params: { transaction: tx.toString() },\n })) as string\n\n // The devnode auto-produces a block after broadcast by default; under\n // manualBlockCreation the caller must advance blocks for this to resolve.\n const confirmedTx = await waitForConfirmation(publicClient, txId)\n\n // Self-custody decryptor: records owned by the devnode account surface\n // as plaintext; records owned by someone else (e.g. a compliance record\n // minted to an authority) pass through as ciphertext rather than being\n // dropped, so the outputs keep their transition positions — positional\n // consumers like the generated contract bindings depend on that.\n const accountViewKey = StaticViewKey.from_string(account.viewKey)\n const decryptor: Decryptor = (ciphertext: string) => {\n const ct = StaticRecordCiphertext.fromString(ciphertext)\n return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : ciphertext\n }\n const { transitions, outputs } = extractTransitions(confirmedTx, decryptor)\n return { transactionId: txId, transitions, outputs }\n },\n }\n\n const walletClient = createWalletClient({ account, transport, proving })\n\n return { publicClient, walletClient, account }\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as bip39 from '@scure/bip39'\nimport { wordlist } from '@scure/bip39/wordlists/english'\n\nconst HARDENED_OFFSET = 0x80000000\n\n// Aleo-specific HMAC key for HD master derivation (parallel to BIP32's\n// \"Bitcoin seed\", but for BLS12-377). Matches shield-core.\nconst BLS12_377_CURVE = 'bls12_377 seed'\n\nconst PATH_REGEX = /^m(\\/[0-9]+')+$/\n\n/**\n * Names the derivation-path convention used to turn a seed into Aleo keys.\n *\n * `'standard'` uses the SLIP-0044-registered Aleo coin type (`m/44'/683'`);\n * `'legacy'` uses the pre-registration path (`m/44'/0'`) some older wallets\n * chose. Pick `'legacy'` only to recover accounts created by such a wallet.\n */\nexport type AleoDerivationId = 'standard' | 'legacy'\n\n/** SLIP-0044 registered Aleo coin type. */\nexport const STANDARD_PATH = \"m/44'/683'\"\n\n/** Pre-SLIP-0044-registration derivation path. Some older wallets used this. */\nexport const LEGACY_PATH = \"m/44'/0'\"\n\n/** Maps each {@link AleoDerivationId} to its account-level derivation path. */\nexport const DERIVATION_PATHS: Record<AleoDerivationId, string> = {\n standard: STANDARD_PATH,\n legacy: LEGACY_PATH,\n}\n\ninterface IKeys {\n key: Uint8Array\n chainCode: Uint8Array\n}\n\nfunction uint32BE(n: number): Uint8Array {\n if (!Number.isInteger(n) || n < 0 || n > 0xffffffff) {\n throw new Error(`uint32BE: value out of range (got ${n})`)\n }\n const out = new Uint8Array(4)\n new DataView(out.buffer).setUint32(0, n, false)\n return out\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, p) => sum + p.length, 0)\n const out = new Uint8Array(total)\n let offset = 0\n for (const p of parts) {\n out.set(p, offset)\n offset += p.length\n }\n return out\n}\n\nfunction ckdPriv({ key, chainCode }: IKeys, index: number): IKeys {\n const data = concatBytes(new Uint8Array([0]), key, uint32BE(index))\n const I = hmac(sha512, chainCode, data)\n return { key: I.slice(0, 32), chainCode: I.slice(32) }\n}\n\nfunction getMasterKeyFromSeed(seed: Uint8Array): IKeys {\n const I = hmac(sha512, BLS12_377_CURVE, seed)\n return { key: I.slice(0, 32), chainCode: I.slice(32) }\n}\n\nfunction isValidPath(path: string): boolean {\n if (!PATH_REGEX.test(path)) return false\n return path\n .split('/')\n .slice(1)\n .map((s) => s.replace(\"'\", ''))\n .every((s) => Number.isFinite(Number(s)))\n}\n\n/**\n * Hierarchical-deterministic key node for the BLS12-377 curve Aleo uses.\n *\n * Follows the SLIP-0010 construction (HMAC-SHA512 chains, hardened-only\n * derivation) with an Aleo-specific master key tag, matching shield-core.\n * All operations are pure and local — nothing touches the network. Start\n * from {@link BLS12377HDKey.fromMasterSeed} (or {@link mnemonicToHDKey})\n * rather than the constructor; the 32-byte `key` of a derived node is the\n * seed for an Aleo private key.\n */\nexport class BLS12377HDKey {\n /**\n * Wraps raw node material. Callers normally use\n * {@link BLS12377HDKey.fromMasterSeed} instead of constructing directly.\n *\n * @param key 32-byte private key material of this node.\n * @param chainCode 32-byte chain code used to derive children.\n */\n constructor(\n public readonly key: Uint8Array,\n public readonly chainCode: Uint8Array,\n ) {}\n\n /**\n * Derives the master node from a BIP-39 seed. Pure and local.\n *\n * @param seed Seed bytes, typically the 64-byte output of\n * {@link mnemonicToSeed}.\n * @returns The root node from which paths are derived.\n */\n static fromMasterSeed(seed: Uint8Array): BLS12377HDKey {\n const master = getMasterKeyFromSeed(seed)\n return new BLS12377HDKey(master.key, master.chainCode)\n }\n\n /**\n * Derives the descendant node at a hardened path. Pure and local.\n *\n * @param path Path of the form `m/44'/683'` — every segment MUST be\n * hardened (trailing `'`) and below 2^31.\n * @returns A new node; this node is unchanged.\n * @throws If the path is malformed, contains a non-hardened segment, or a\n * segment is out of range.\n */\n derive(path: string): BLS12377HDKey {\n if (!isValidPath(path)) {\n throw new Error(\n `Invalid derivation path: ${path} (must match m/N'/N'/... — hardened only)`,\n )\n }\n const segments = path\n .split('/')\n .slice(1)\n .map((s) => parseInt(s.replace(\"'\", ''), 10))\n\n for (const seg of segments) {\n if (seg >= HARDENED_OFFSET) {\n throw new Error(\n `Derivation path segment out of range: ${seg} (must be < 2³¹)`,\n )\n }\n }\n\n const result = segments.reduce(\n (acc, segment) => ckdPriv(acc, segment + HARDENED_OFFSET),\n { key: this.key, chainCode: this.chainCode } as IKeys,\n )\n return new BLS12377HDKey(result.key, result.chainCode)\n }\n\n /** Alias for {@link BLS12377HDKey.derive}, kept for HD-key API parity. */\n derivePath(path: string): BLS12377HDKey {\n return this.derive(path)\n }\n\n /**\n * Derives the account node at `m/{index}'/0'` relative to this node. Pure\n * and local. Applied to a {@link DERIVATION_PATHS} node, this yields the\n * account at that index.\n *\n * @param index Zero-based account index, below 2^31; hardening is applied\n * internally.\n * @returns The account-level node.\n * @throws If the index is negative, fractional, or 2^31 or greater.\n */\n deriveChild(index: number): BLS12377HDKey {\n if (!Number.isInteger(index) || index < 0 || index >= HARDENED_OFFSET) {\n throw new Error(\n `Invalid child index: ${index} (must be integer in [0, 2³¹))`,\n )\n }\n return this.derive(`m/${index}'/0'`)\n }\n}\n\n/**\n * Generates a fresh BIP-39 mnemonic from the English wordlist.\n *\n * Draws entropy from the platform CSPRNG; no network access. The phrase is\n * the root secret for every account derived from it — the caller MUST store\n * it securely and never log it.\n *\n * @param strength Entropy in bits: 128 yields 12 words, 256 yields 24.\n * Defaults to 128.\n * @returns A space-separated mnemonic phrase.\n *\n * @example\n * import { generateMnemonic, mnemonicToHDKey } from '@provablehq/veil-aleo-sdk'\n *\n * const mnemonic = generateMnemonic()\n * const account0 = mnemonicToHDKey(mnemonic)\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n return bip39.generateMnemonic(wordlist, strength)\n}\n\n/**\n * Checks a full mnemonic phrase against BIP-39: English wordlist membership,\n * word count, and checksum. Pure and local.\n *\n * @param mnemonic Space-separated candidate phrase.\n * @returns True only if the phrase can be used for key derivation; a single\n * wrong or reordered word fails the checksum.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return bip39.validateMnemonic(mnemonic, wordlist)\n}\n\n/**\n * Checks whether a single word belongs to the English BIP-39 wordlist. Pure\n * and local. Use for per-word feedback while a phrase is being typed;\n * validating the complete phrase still requires {@link validateMnemonic}.\n *\n * @param word Candidate word, lowercase.\n * @returns True if the word is one of the 2048 list entries.\n */\nexport function validateWord(word: string): boolean {\n return wordlist.includes(word)\n}\n\n/**\n * Converts a mnemonic to its 64-byte BIP-39 seed via PBKDF2-HMAC-SHA512 with\n * an empty passphrase. Pure, local, and deterministic.\n *\n * The mnemonic is not validated here — call {@link validateMnemonic} first;\n * an invalid phrase still produces a seed, only for the wrong accounts.\n *\n * @param mnemonic Space-separated BIP-39 phrase.\n * @returns Seed bytes for {@link BLS12377HDKey.fromMasterSeed}.\n */\nexport function mnemonicToSeed(mnemonic: string): Uint8Array {\n return bip39.mnemonicToSeedSync(mnemonic)\n}\n\n/**\n * Derives the Aleo account key at the given index from a mnemonic in one\n * step: seed, master node, derivation path, account child. Pure and local.\n * This is the usual entry point for turning a stored phrase into key\n * material.\n *\n * @param mnemonic Space-separated BIP-39 phrase.\n * @param options.index Zero-based account index, below 2^31. Defaults to 0.\n * @param options.derivation Path convention. Defaults to `'standard'`\n * (`m/44'/683'`); pass `'legacy'` to recover accounts from wallets that\n * predate the SLIP-0044 registration.\n * @returns The account node; its `key` bytes seed the Aleo private key.\n * @throws If the index is out of range.\n *\n * @example\n * import { mnemonicToHDKey } from '@provablehq/veil-aleo-sdk'\n *\n * const hdKey = mnemonicToHDKey(mnemonic, { index: 1 })\n */\nexport function mnemonicToHDKey(\n mnemonic: string,\n options: { index?: number; derivation?: AleoDerivationId } = {},\n): BLS12377HDKey {\n const { index = 0, derivation = 'standard' } = options\n const seed = mnemonicToSeed(mnemonic)\n return BLS12377HDKey.fromMasterSeed(seed)\n .derivePath(DERIVATION_PATHS[derivation])\n .deriveChild(index)\n}\n"],"mappings":";AAsBA,SAAS,eAAe,eAAe;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,EACpB,WAAW;AAAA,EACX;AAAA,OACK;AACP,SAAS,qBAAqB,oBAAoB;AAMlD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACjDP,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,YAAY,WAAW;AACvB,SAAS,gBAAgB;AAEzB,IAAM,kBAAkB;AAIxB,IAAM,kBAAkB;AAExB,IAAM,aAAa;AAYZ,IAAM,gBAAgB;AAGtB,IAAM,cAAc;AAGpB,IAAM,mBAAqD;AAAA,EAChE,UAAU;AAAA,EACV,QAAQ;AACV;AAOA,SAAS,SAAS,GAAuB;AACvC,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,IAAI,YAAY;AACnD,UAAM,IAAI,MAAM,qCAAqC,CAAC,GAAG;AAAA,EAC3D;AACA,QAAM,MAAM,IAAI,WAAW,CAAC;AAC5B,MAAI,SAAS,IAAI,MAAM,EAAE,UAAU,GAAG,GAAG,KAAK;AAC9C,SAAO;AACT;AAEA,SAAS,eAAe,OAAiC;AACvD,QAAM,QAAQ,MAAM,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,QAAQ,CAAC;AACxD,QAAM,MAAM,IAAI,WAAW,KAAK;AAChC,MAAI,SAAS;AACb,aAAW,KAAK,OAAO;AACrB,QAAI,IAAI,GAAG,MAAM;AACjB,cAAU,EAAE;AAAA,EACd;AACA,SAAO;AACT;AAEA,SAAS,QAAQ,EAAE,KAAK,UAAU,GAAU,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AC1B,QAAQ,YAAY;AAAA,QACpB,YAAY,YAAY;AAAA,QACxB,SAAS,YAAY;AAAA,MACvB,CAAC;AAGD,YAAM,OAAQ,MAAM,aAAa,QAAQ;AAAA,QACvC,QAAQ;AAAA,QACR,QAAQ,EAAE,aAAa,GAAG,SAAS,EAAE;AAAA,MACvC,CAAC;AAID,YAAM,cAAc,MAAM,oBAAoB,cAAc,IAAI;AAOhE,YAAM,iBAAiB,cAAc,YAAY,QAAQ,OAAO;AAChE,YAAM,YAAuB,CAAC,eAAuB;AACnD,cAAM,KAAK,uBAAuB,WAAW,UAAU;AACvD,eAAO,GAAG,QAAQ,cAAc,IAAI,GAAG,QAAQ,cAAc,EAAE,SAAS,IAAI;AAAA,MAC9E;AACA,YAAM,EAAE,aAAa,QAAQ,IAAI,mBAAmB,aAAa,SAAS;AAC1E,aAAO,EAAE,eAAe,MAAM,aAAa,QAAQ;AAAA,IACrD;AAAA,EACF;AAEA,QAAM,eAAe,mBAAmB,EAAE,SAAS,WAAW,QAAQ,CAAC;AAEvE,SAAO,EAAE,cAAc,cAAc,QAAQ;AAC/C;","names":["generateMnemonic","validateMnemonic","Account","generateMnemonic","generateAccount"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/mnemonic.ts"],"sourcesContent":["/**\n * @provablehq/veil-aleo-sdk\n *\n * Loads `@provablehq/sdk` for a specific Aleo network and exposes the SDK's\n * functionality bound to that network's setup parameters.\n *\n * Usage:\n * import { loadNetwork } from '@provablehq/veil-aleo-sdk'\n * import { http } from '@provablehq/veil-core'\n *\n * const aleo = await loadNetwork('mainnet')\n *\n * const account = aleo.privateKeyToAccount('APrivateKey1...')\n * const { publicClient, walletClient } = aleo.createAleoClient({\n * privateKey: 'APrivateKey1...',\n * networkUrl: 'https://api.provable.com/v2',\n * })\n *\n * Switching networks: load a new handle. Existing accounts remain valid —\n * Aleo private keys, view keys, and addresses are network-agnostic.\n */\n\nimport { loadNetwork as loadSdk } from '@provablehq/sdk/dynamic.js'\nimport {\n Account,\n AleoKeyProvider,\n Program,\n ProgramManager,\n RecordCiphertext as StaticRecordCiphertext,\n ViewKey as StaticViewKey,\n getOrInitConsensusVersionTestHeights,\n} from '@provablehq/sdk'\nimport { DEVNODE_PRIVATE_KEY, DEVNODE_ADDR } from '@provablehq/veil-aleo-devnode'\nexport { DEVNODE_PRIVATE_KEY, DEVNODE_ADDR }\nimport type { LocalAccount } from '@provablehq/veil-core'\nimport type { ProvingConfig, BuildTransactionOptions, BuildDeploymentOptions, SimulateOptions, ExecuteOptions, RawSimulateResult, RawExecuteResult } from '@provablehq/veil-core'\nimport type { OwnedRecord, RecordProvider, StandaloneRecordScanner, RequestRecordsParameters } from '@provablehq/veil-core'\nimport type { Network, PublicClient, WalletClient } from '@provablehq/veil-core'\nimport {\n createPublicClient,\n createWalletClient,\n http,\n BaseError,\n ProvingError,\n ConfigurationError,\n classifyBroadcastError,\n classifyProvingError,\n waitForConfirmation,\n extractTransitions,\n} from '@provablehq/veil-core'\nimport type { Decryptor } from '@provablehq/veil-core'\nimport { generateMnemonic, mnemonicToHDKey, type AleoDerivationId } from './mnemonic.js'\n\nexport {\n BLS12377HDKey,\n generateMnemonic,\n validateMnemonic,\n validateWord,\n mnemonicToSeed,\n mnemonicToHDKey,\n STANDARD_PATH,\n LEGACY_PATH,\n type AleoDerivationId,\n} from './mnemonic.js'\n\n/** Networks supported by `@provablehq/sdk/dynamic.js`. */\nexport type SupportedNetwork = 'mainnet' | 'testnet'\n\n// `loadSdk('testnet')` and `loadSdk('mainnet')` return modules whose runtime\n// classes have the same shape. The narrowed-to-testnet type is used as the\n// canonical handle to avoid TS's union-of-modules confusion.\ntype SdkModule = Awaited<ReturnType<typeof loadSdk<'testnet'>>>\n\n/**\n * A network-bound SDK handle. All functions on this handle use the binary\n * set loaded for the named network.\n *\n * Most key/account operations (`privateKeyToAccount`, `mnemonicToAccount`,\n * `generateAccount`, `decryptRecord`, `verifySignature`) are mathematically\n * network-agnostic — the same private key (or mnemonic) derives the same\n * address and view key regardless of which network's binary was loaded.\n * Proving and program operations (`createProvingConfig`, `createAleoClient`,\n * scanners) are network-bound.\n */\nexport interface AleoSdk {\n /** The network this handle is bound to. */\n readonly network: SupportedNetwork\n\n /** Creates a `LocalAccount` from an Aleo private key. */\n privateKeyToAccount(privateKey: string): LocalAccount<'privateKey'>\n\n /**\n * Creates a `LocalAccount` from a BIP39 mnemonic phrase using Aleo's\n * BLS12-377 HD derivation (matches Shield wallet derivation).\n *\n * Defaults to the SLIP-0044 Aleo coin type path `m/44'/683'`, account\n * index 0. Pass `derivation: 'legacy'` to use the pre-registration path\n * `m/44'/0'` for compatibility with older wallets.\n */\n mnemonicToAccount(\n mnemonic: string,\n options?: { index?: number; derivation?: AleoDerivationId },\n ): LocalAccount<'mnemonic'>\n\n /**\n * Generates a fresh BIP39 mnemonic and derives its Aleo account in one call.\n * Pure and local — no network access. The caller MUST persist the returned\n * mnemonic; it is the only way to re-derive the account.\n *\n * @param options.strength Entropy bits: 128 (12 words, default) or 256 (24 words).\n * @param options.index Account index on the derivation path. Defaults to 0.\n * @param options.derivation Derivation path id. Defaults to `'standard'`\n * (`m/44'/683'`); pass `'legacy'` for pre-registration `m/44'/0'` wallets.\n * @returns The generated mnemonic and the account derived from it.\n *\n * @example\n * const { mnemonic, account } = aleo.generateMnemonicAccount()\n * // store `mnemonic` safely; `account.address` is ready to use\n */\n generateMnemonicAccount(options?: {\n strength?: 128 | 256\n index?: number\n derivation?: AleoDerivationId\n }): { mnemonic: string; account: LocalAccount<'mnemonic'> }\n\n /** Creates a new random Aleo account. */\n generateAccount(): LocalAccount<'privateKey'>\n\n /** Decrypts a record ciphertext using a view key. */\n decryptRecord(viewKey: string, ciphertext: string): string\n\n /** Verifies a signature against a message and address. */\n verifySignature(address: string, message: Uint8Array, signature: string): boolean\n\n /** Creates an `AleoNetworkClient` for direct SDK access. */\n createNetworkClient(url: string): InstanceType<SdkModule['AleoNetworkClient']>\n\n /** Creates a `ProvingConfig` for `createWalletClient({ proving })`. */\n createProvingConfig(options: {\n mode: 'delegated' | 'local'\n networkUrl: string\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n account?: LocalAccount<'privateKey'>\n confirmationTimeout?: number\n useFeeMaster?: boolean\n }): ProvingConfig\n\n /**\n * Creates a record scanner backed by Provable's Record Scanner Service.\n *\n * The first `requestRecords` call registers the account's view key with the\n * service (a network round-trip) to obtain the UUID scanning requires;\n * subsequent calls reuse it. `setAccount` resets the registration.\n *\n * The provider implements `switchNetwork`, so a wallet client carrying it\n * re-targets record scanning when `switchChain` runs — the scanner rebuilds\n * against the new network and re-registers lazily on the next scan.\n *\n * @param options.url Base URL of the service (the SDK appends the network\n * segment — do not include it).\n * @param options.consumerId Consumer id used for JWT refresh.\n * @param options.apiKey Optional API key for the authenticated service\n * (e.g. the hosted Provable RSS). Omit for an open/unauthenticated service.\n * @param options.startBlock Optional block height to begin scanning from at\n * registration. Defaults to 0 (full history).\n */\n createRemoteScanner(options: {\n url: string\n consumerId: string\n apiKey?: string\n startBlock?: number\n }): RecordProvider\n\n /**\n * Creates a standalone record scanner with an explicit view key.\n *\n * Like {@link createRemoteScanner}, the first `requestRecords` registers the\n * view key with the service (a network round-trip) to obtain the scanning UUID.\n *\n * @param options.url Base URL of the service (the SDK appends the network segment).\n * @param options.consumerId Consumer id used for JWT refresh.\n * @param options.viewKey The view key (`AViewKey1…`) to scan and decrypt with.\n * @param options.apiKey Optional API key for the authenticated service. Omit\n * for an open/unauthenticated service.\n * @param options.startBlock Optional block height to begin scanning from at\n * registration. Defaults to 0 (full history).\n */\n createStandaloneScanner(options: {\n url: string\n consumerId: string\n viewKey: string\n apiKey?: string\n startBlock?: number\n }): StandaloneRecordScanner\n\n /** Creates a fully-wired Aleo client from a private key and network URL. */\n createAleoClient(options: {\n privateKey: string\n networkUrl: string\n provingMode?: 'delegated' | 'local'\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n useFeeMaster?: boolean\n /**\n * Record provider for `requestRecords`. Not wired by default — pass\n * `aleo.createRemoteScanner(...)` or any\n * custom `RecordProvider`. `requestRecords` throws with a setup hint\n * when no provider is configured.\n */\n records?: RecordProvider\n }): { publicClient: PublicClient; walletClient: WalletClient; account: LocalAccount<'privateKey'> }\n}\n\n/**\n * Loads `@provablehq/sdk` for the named network and returns a network-bound\n * handle. The SDK module cache memoizes the load — calling twice for the\n * same network returns the same binary set without re-instantiating.\n */\nexport async function loadNetwork(name: SupportedNetwork): Promise<AleoSdk> {\n const sdk = (await loadSdk(name)) as SdkModule\n return buildSdk(name, sdk)\n}\n\nfunction buildSdk(initialNetwork: SupportedNetwork, initialSdk: SdkModule): AleoSdk {\n // Mutable handle so `createProvingConfig().switchNetwork()` can swap the\n // underlying binary set without rebuilding the wallet client.\n let currentSdk: SdkModule = initialSdk\n const network = initialNetwork\n const {\n Account,\n PrivateKey,\n Signature,\n Address,\n ViewKey,\n AleoNetworkClient,\n RecordScanner,\n RecordCiphertext,\n } = initialSdk\n\n\n\n function mnemonicToAccount(\n mnemonic: string,\n options?: { index?: number; derivation?: AleoDerivationId },\n ): LocalAccount<'mnemonic'> {\n const hd = mnemonicToHDKey(mnemonic, options)\n // wasm-bindgen exports the snake_case name; it is not a typo.\n const privateKey = (PrivateKey as unknown as {\n from_seed_unchecked: (seed: Uint8Array) => InstanceType<SdkModule['PrivateKey']>\n }).from_seed_unchecked(hd.key).to_string()\n return { ...privateKeyToAccount(privateKey), source: 'mnemonic' }\n }\n\n function generateMnemonicAccount(options?: {\n strength?: 128 | 256\n index?: number\n derivation?: AleoDerivationId\n }): { mnemonic: string; account: LocalAccount<'mnemonic'> } {\n const mnemonic = generateMnemonic(options?.strength ?? 128)\n const { strength: _strength, ...derivationOptions } = options ?? {}\n return { mnemonic, account: mnemonicToAccount(mnemonic, derivationOptions) }\n }\n\n function generateAccount(): LocalAccount<'privateKey'> {\n const sdkAccount = new Account()\n return privateKeyToAccount(sdkAccount.privateKey().to_string())\n }\n\n function decryptRecord(viewKeyString: string, ciphertext: string): string {\n return ViewKey.from_string(viewKeyString).decrypt(ciphertext)\n }\n\n function verifySignature(\n addressString: string,\n message: Uint8Array,\n signatureString: string,\n ): boolean {\n const sig = Signature.from_string(signatureString)\n const addr = Address.from_string(addressString)\n return sig.verify(addr, message)\n }\n\n function createNetworkClient(url: string): InstanceType<SdkModule['AleoNetworkClient']> {\n return new AleoNetworkClient(url)\n }\n\n function createProvingConfig(options: {\n mode: 'delegated' | 'local'\n networkUrl: string\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n account?: LocalAccount<'privateKey'>\n /** Timeout in ms for waiting for transaction confirmation (default: 300_000 = 5 min) */\n confirmationTimeout?: number\n /**\n * The delegated prover pays the transaction fee from its FeeMaster\n * account instead of the caller's public credits. Only meaningful with\n * `mode: 'delegated'`; requires the prover service to allow it for the\n * consumer. Defaults to true — accounts need no public credits to\n * transact. Set false when the account funds its own fees.\n */\n useFeeMaster?: boolean\n }): ProvingConfig {\n // Each call reads from currentSdk so switchNetwork can swap the binary set\n // without rebuilding the wallet client.\n let networkUrl = options.networkUrl\n let keyProvider = new currentSdk.AleoKeyProvider()\n keyProvider.useCache(true)\n\n return {\n mode: options.mode,\n url: options.proverUrl,\n\n buildTransaction: async (txOptions: BuildTransactionOptions) => {\n const programManager = new currentSdk.ProgramManager(\n networkUrl,\n keyProvider,\n undefined,\n )\n\n if (options.account) {\n const sdkAccount = new currentSdk.Account({ privateKey: options.account.privateKey })\n programManager.setAccount(sdkAccount)\n }\n\n // The user-facing API takes dynamic-dispatch import names (`string[]`);\n // the SDK needs a name → source map covering BOTH the program's static\n // imports (declared in the `import` block) and the user's dynamic ones.\n // Auto-discover static imports first, then add the user-provided\n // dynamic ones on top. The SDK's ProgramImports values can be string\n // or Program; its return type is mirrored instead of reconstructed.\n type SdkProgramImports = Awaited<\n ReturnType<InstanceType<SdkModule['AleoNetworkClient']>['getProgramImports']>\n >\n let resolvedImports: SdkProgramImports | undefined\n if (txOptions.imports && txOptions.imports.length > 0) {\n const programSource = await programManager.networkClient.getProgram(txOptions.programName)\n const staticImports = await programManager.networkClient.getProgramImports(programSource)\n const merged: SdkProgramImports = { ...staticImports }\n for (const name of txOptions.imports) {\n merged[name] = await programManager.networkClient.getProgram(name)\n }\n resolvedImports = merged\n }\n\n const tx = await programManager.buildExecutionTransaction({\n programName: txOptions.programName,\n functionName: txOptions.functionName,\n priorityFee: 0,\n privateFee: txOptions.privateFee ?? false,\n inputs: txOptions.inputs,\n ...(resolvedImports ? { imports: resolvedImports } : {}),\n })\n\n return JSON.parse(tx.toString())\n },\n\n buildDeployment: async (deployOptions: BuildDeploymentOptions) => {\n const programManager = new currentSdk.ProgramManager(\n networkUrl,\n keyProvider,\n undefined,\n )\n\n if (options.account) {\n const sdkAccount = new currentSdk.Account({ privateKey: options.account.privateKey })\n programManager.setAccount(sdkAccount)\n }\n\n const tx = await programManager.buildDeploymentTransaction(\n deployOptions.program,\n 0,\n deployOptions.privateFee ?? false,\n )\n\n return JSON.parse(tx.toString())\n },\n\n simulate: async (simOptions: SimulateOptions): Promise<RawSimulateResult> => {\n const programManager = new currentSdk.ProgramManager(networkUrl, keyProvider, undefined)\n if (options.account) {\n programManager.setAccount(new currentSdk.Account({ privateKey: options.account.privateKey }))\n }\n\n // Self-custody decryptor: same view-key-based decryptor as the execute path.\n const accountViewKey = options.account ? ViewKey.from_string(options.account.viewKey) : undefined\n const decryptor: Decryptor | undefined = accountViewKey\n ? (ciphertext: string) => {\n const ct = RecordCiphertext.fromString(ciphertext)\n return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : null\n }\n : undefined\n\n // `buildAuthorization` runs the function (with cross-program calls) and produces an\n // Authorization whose transitions carry program/function metadata and the actual\n // outputs — same structure a confirmed Transaction has, minus the proof.\n const authorization = await programManager.buildAuthorization({\n programName: simOptions.programName,\n functionName: simOptions.functionName,\n inputs: simOptions.inputs,\n programSource: simOptions.programSource,\n programImports: simOptions.programImports,\n })\n\n // Convert the wasm Transition objects into the wire-shaped tx that extractTransitions\n // consumes. Private outputs come back from an Authorization as TVK-encrypted ciphertexts\n // (Aleo's on-chain privacy model); decrypt with the caller's TVK first so plaintext\n // values are visible. `transition.toString()` emits the same wire-format JSON the chain\n // returns from `/transaction/confirmed/{id}` — Aleo-typed string values like '10u32',\n // 'aleo1...', or 'record1...' under each output's `value`.\n const tx = {\n execution: {\n transitions: authorization.transitions().map((t: any) => {\n let source = t\n if (accountViewKey) {\n try {\n source = t.decryptTransition(t.tvk(accountViewKey))\n } catch {\n // Foreign transition signed by another caller — leave outputs encrypted.\n }\n }\n return JSON.parse(source.toString())\n }),\n },\n }\n\n const { transitions, outputs } = extractTransitions(tx, decryptor)\n return { transitions, outputs }\n },\n\n execute: async (execOptions: ExecuteOptions): Promise<RawExecuteResult> => {\n const programManager = new currentSdk.ProgramManager(networkUrl, keyProvider, undefined)\n if (options.account) {\n programManager.setAccount(new currentSdk.Account({ privateKey: options.account.privateKey }))\n }\n\n /** Convert microcredits (Veil API) to credits (SDK API) for priority fee */\n const priorityFee = Number(execOptions.fee) / 1_000_000\n\n /** Self-custody decryptor: use the local account's view key to decrypt owned record ciphertexts. */\n const accountViewKey = options.account ? ViewKey.from_string(options.account.viewKey) : undefined\n const decryptor: Decryptor | undefined = accountViewKey\n ? (ciphertext: string) => {\n const ct = RecordCiphertext.fromString(ciphertext)\n return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : null\n }\n : undefined\n\n /** Build a Veil publicClient bound to the current networkUrl for chain polling. */\n const buildPollingClient = () =>\n createPublicClient({ transport: http(networkUrl, { network: network as Network }) })\n\n if (options.mode === 'delegated') {\n if (!options.proverUrl) throw new ConfigurationError('Delegated execution requires proverUrl. Pass proverUrl to createProvingConfig or createAleoClient.')\n\n let response: any\n try {\n const provingRequest = await programManager.provingRequest({\n programName: execOptions.programName,\n programSource: execOptions.programSource,\n programImports: execOptions.programImports,\n functionName: execOptions.functionName,\n inputs: execOptions.inputs,\n priorityFee,\n privateFee: execOptions.privateFee ?? false,\n broadcast: true,\n useFeeMaster: options.useFeeMaster ?? true,\n })\n\n const dpsClient = new AleoNetworkClient(options.proverUrl)\n response = await dpsClient.submitProvingRequest({\n provingRequest,\n url: options.proverUrl,\n apiKey: options.apiKey,\n consumerId: options.consumerId,\n })\n } catch (e) {\n if (e instanceof BaseError) throw e\n throw classifyProvingError(e)\n }\n\n const txId = response.transaction?.id\n if (!txId) throw new ConfigurationError('DPS response did not contain a transaction ID — check prover service configuration.')\n\n const confirmedTx = await waitForConfirmation(buildPollingClient(), txId, options.confirmationTimeout)\n const { transitions, outputs } = extractTransitions(confirmedTx, decryptor)\n return { transactionId: txId, transitions, outputs }\n\n } else {\n let tx: any\n try {\n tx = await programManager.buildExecutionTransaction({\n programName: execOptions.programName,\n functionName: execOptions.functionName,\n inputs: execOptions.inputs,\n priorityFee,\n privateFee: execOptions.privateFee ?? false,\n program: execOptions.programSource,\n imports: execOptions.programImports,\n })\n } catch (e) {\n if (e instanceof BaseError) throw e\n throw new ProvingError({ message: e instanceof Error ? e.message : String(e), cause: e as Error })\n }\n\n let txId: string\n try {\n const submitClient = new AleoNetworkClient(networkUrl)\n submitClient.setVerboseErrors(false)\n txId = await submitClient.submitTransaction(tx)\n } catch (e) {\n if (e instanceof BaseError) throw e\n throw classifyBroadcastError(e)\n }\n\n const confirmedTx = await waitForConfirmation(buildPollingClient(), txId, options.confirmationTimeout)\n const { transitions, outputs } = extractTransitions(confirmedTx, decryptor)\n return { transactionId: txId, transitions, outputs }\n }\n },\n\n decrypt: async (cipherText) => {\n if (!options.account?.viewKey) {\n throw new Error(\n 'decrypt requires an account with a viewKey on the proving config.',\n )\n }\n return currentSdk.ViewKey.from_string(options.account.viewKey).decrypt(cipherText)\n },\n\n switchNetwork: async (newNetwork) => {\n if (newNetwork !== 'mainnet' && newNetwork !== 'testnet') {\n throw new Error(\n `loadNetwork supports 'mainnet' or 'testnet' (received '${newNetwork}').`,\n )\n }\n currentSdk = (await loadSdk(newNetwork as SupportedNetwork)) as SdkModule\n keyProvider = new currentSdk.AleoKeyProvider()\n keyProvider.useCache(true)\n },\n }\n }\n\n // The RSS returns record fields in snake_case (record_plaintext,\n // program_name, …); the veil OwnedRecord contract is camelCase. Map them —\n // a bare cast silently leaves recordPlaintext undefined, which reads as an\n // unspendable wallet. Fields whose two casings coincide are read directly;\n // the rest accept either case so a future camelCase SDK build keeps working.\n // `uid` and `recordView` are privacy-wallet-adapter concepts the RSS does\n // not supply, so they are intentionally omitted.\n function toOwnedRecord(raw: Record<string, unknown>): OwnedRecord {\n const pick = (snake: string, camel: string): unknown => raw[snake] ?? raw[camel]\n return {\n blockHeight: pick('block_height', 'blockHeight') as number | undefined,\n blockTimestamp: pick('block_timestamp', 'blockTimestamp') as number | undefined,\n commitment: raw.commitment as string | undefined,\n functionName: pick('function_name', 'functionName') as string | undefined,\n outputIndex: pick('output_index', 'outputIndex') as number | undefined,\n owner: raw.owner as string | undefined,\n programName: pick('program_name', 'programName') as string,\n recordCiphertext: pick('record_ciphertext', 'recordCiphertext') as string | undefined,\n recordName: pick('record_name', 'recordName') as string | undefined,\n sender: raw.sender as string | undefined,\n spent: raw.spent as boolean | undefined,\n tag: raw.tag as string,\n transactionId: pick('transaction_id', 'transactionId') as string | undefined,\n transitionId: pick('transition_id', 'transitionId') as string | undefined,\n transactionIndex: pick('transaction_index', 'transactionIndex') as number | undefined,\n transitionIndex: pick('transition_index', 'transitionIndex') as number | undefined,\n recordPlaintext: (pick('record_plaintext', 'recordPlaintext') as string | undefined) ?? '',\n }\n }\n\n // A scanner's UUID is issued at registration; owned() rejects locally\n // without one. Register once, lazily, and memoize the in-flight promise so\n // concurrent scans share a single round-trip. Account or network changes\n // replace the whole object (one registration per scanner build).\n function makeRegisterOnce(startBlock: number) {\n let registration: Promise<void> | undefined\n return {\n ensure(\n scanner: InstanceType<SdkModule['RecordScanner']>,\n viewKey: ReturnType<SdkModule['ViewKey']['from_string']>,\n ): Promise<void> {\n if (!registration) {\n registration = (async () => {\n const result = await scanner.registerEncrypted(viewKey, startBlock)\n if (!result.ok) {\n registration = undefined // allow a later retry after a transient failure\n throw new Error(\n `Record scanner registration failed (HTTP ${result.status}): ${result.error?.message ?? 'unknown error'}`,\n )\n }\n })()\n }\n return registration\n },\n }\n }\n\n // Scans owned records with bounded retry. owned() returns a discriminated\n // result on HTTP error but *throws* on a network failure or an invalidated\n // UUID — both paths are retried here. A freshly-minted JWT can momentarily\n // hit an RSS backend that has not yet synced the credential (HTTP 401), and\n // the SDK caches that JWT for the scanner's lifetime — so between attempts it\n // is dropped (setJwtData(undefined) forces a re-mint), backed off, and retried,\n // giving the backend time to catch up. A non-transient status surfaces at once.\n //\n // 429/5xx are always transient; a 401/403 is only worth retrying when a JWT\n // can actually be re-minted (apiKey configured) — on an unauthenticated\n // scanner those are permanent, so retrying just burns backoff.\n async function scanOwned(\n scanner: InstanceType<SdkModule['RecordScanner']>,\n program: string,\n statusFilter: string | undefined,\n canReMint: boolean,\n ): Promise<OwnedRecord[]> {\n const ALWAYS_RETRY = new Set([429, 500, 502, 503, 504])\n const AUTH_RETRY = new Set([401, 403])\n const retryable = (status: number) => ALWAYS_RETRY.has(status) || (canReMint && AUTH_RETRY.has(status))\n const MAX_ATTEMPTS = 4\n let last = ''\n for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {\n try {\n const result = await scanner.owned({\n unspent: statusFilter !== 'spent',\n filter: { programs: [program] },\n })\n if (result.ok) return (result.data ?? []).map((r) => toOwnedRecord(r as Record<string, unknown>))\n last = `HTTP ${result.status}: ${result.error?.message ?? 'unknown error'}`\n if (!retryable(result.status)) break\n } catch (err) {\n // owned() throws (rather than returning a result) on a network failure\n // or an invalidated UUID — treat as transient and retry.\n last = err instanceof Error ? err.message : String(err)\n }\n if (attempt === MAX_ATTEMPTS - 1) break\n scanner.setJwtData(undefined) // drop the cached (rejected) JWT so the next call re-mints\n await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt))\n }\n throw new Error(`Record scan failed (${last})`)\n }\n\n function createRemoteScanner(options: {\n url: string\n consumerId: string\n apiKey?: string\n startBlock?: number\n }): RecordProvider {\n // The RecordScanner class is network-bound: a scanner built from a given\n // SDK module scans that module's network. Network switching rebuilds the\n // scanner (and the wasm view key) from the target network's module.\n let scannerSdk: Pick<SdkModule, 'RecordScanner' | 'ViewKey'> = { RecordScanner, ViewKey }\n let scanner: InstanceType<SdkModule['RecordScanner']> | undefined\n let viewKey: ReturnType<SdkModule['ViewKey']['from_string']> | undefined\n let viewKeyString: string | undefined\n let registration = makeRegisterOnce(options.startBlock ?? 0)\n\n function buildScanner() {\n if (!viewKeyString) return // no active account yet — nothing to rebuild\n viewKey = scannerSdk.ViewKey.from_string(viewKeyString)\n scanner = new scannerSdk.RecordScanner({\n url: options.url,\n consumerId: options.consumerId,\n ...(options.apiKey ? { apiKey: options.apiKey } : {}),\n viewKeys: [viewKey],\n decryptEnabled: true,\n autoReRegister: true,\n })\n // Each build gets its own registration: view keys register per account\n // AND per network, and the old promise stays bound to the scanner a\n // concurrent scan may still hold.\n registration = makeRegisterOnce(options.startBlock ?? 0)\n }\n\n return {\n setAccount: (account: { viewKey: string }) => {\n viewKeyString = account.viewKey\n buildScanner()\n },\n\n requestRecords: async (params: RequestRecordsParameters): Promise<OwnedRecord[]> => {\n if (!scanner) {\n throw new Error('No active account set on record scanner. Call setAccount() first.')\n }\n\n // Pin this scan to the current build: a concurrent setAccount or\n // switchNetwork swaps the closures, and mixing builds mid-scan would\n // register one scanner and scan another.\n const activeScanner = scanner\n const activeViewKey = viewKey!\n const activeRegistration = registration\n await activeRegistration.ensure(activeScanner, activeViewKey)\n return scanOwned(activeScanner, params.program, params.statusFilter, !!options.apiKey)\n },\n\n switchNetwork: async (newNetwork: string) => {\n if (newNetwork !== 'mainnet' && newNetwork !== 'testnet') {\n throw new Error(\n `Record scanning supports 'mainnet' or 'testnet' (received '${newNetwork}').`,\n )\n }\n scannerSdk = (await loadSdk(newNetwork as SupportedNetwork)) as SdkModule\n buildScanner()\n },\n }\n }\n\n function createStandaloneScanner(options: {\n url: string\n consumerId: string\n viewKey: string\n apiKey?: string\n startBlock?: number\n }): StandaloneRecordScanner {\n const viewKey = ViewKey.from_string(options.viewKey)\n const scanner = new RecordScanner({\n url: options.url,\n consumerId: options.consumerId,\n ...(options.apiKey ? { apiKey: options.apiKey } : {}),\n viewKeys: [viewKey],\n decryptEnabled: true,\n autoReRegister: true,\n })\n const registration = makeRegisterOnce(options.startBlock ?? 0)\n\n return {\n requestRecords: async (params: RequestRecordsParameters): Promise<OwnedRecord[]> => {\n await registration.ensure(scanner, viewKey)\n return scanOwned(scanner, params.program, params.statusFilter, !!options.apiKey)\n },\n }\n }\n\n function createAleoClient(options: {\n privateKey: string\n networkUrl: string\n provingMode?: 'delegated' | 'local'\n proverUrl?: string\n apiKey?: string\n consumerId?: string\n /** Forwarded to `createProvingConfig` — the delegated prover pays fees. Defaults to true. */\n useFeeMaster?: boolean\n records?: RecordProvider\n }): { publicClient: PublicClient; walletClient: WalletClient; account: LocalAccount<'privateKey'> } {\n const account = privateKeyToAccount(options.privateKey)\n const transport = http(options.networkUrl, { network: network as Network })\n\n const proving = createProvingConfig({\n mode: options.provingMode ?? 'delegated',\n networkUrl: options.networkUrl,\n proverUrl: options.proverUrl,\n apiKey: options.apiKey,\n consumerId: options.consumerId,\n account,\n ...(options.useFeeMaster !== undefined ? { useFeeMaster: options.useFeeMaster } : {}),\n })\n\n const publicClient = createPublicClient({ transport })\n\n if (options.records) {\n options.records.setAccount({ viewKey: account.viewKey })\n }\n\n const walletClient = createWalletClient({\n account,\n transport,\n proving,\n ...(options.records ? { recordProvider: options.records } : {}),\n })\n\n return { publicClient, walletClient, account }\n }\n\n return {\n network,\n privateKeyToAccount,\n mnemonicToAccount,\n generateMnemonicAccount,\n generateAccount,\n decryptRecord,\n verifySignature,\n createNetworkClient,\n createProvingConfig,\n createRemoteScanner,\n createStandaloneScanner,\n createAleoClient,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Standalone exports — synchronous helpers and devnode client factory.\n// These use the statically-imported SDK (testnet binaries) so they work\n// without an awaited loadNetwork() call.\n// ---------------------------------------------------------------------------\n\n// Consensus version activation heights the WASM layer assumes when building\n// devnode transactions. MUST mirror the CONSENSUS_VERSION_HEIGHTS default that\n// @provablehq/veil-aleo-devnode passes to the aleo-devnode process, so the transaction builder\n// and the node agree on which consensus version is active at each height. The\n// entry count must also equal the WASM SDK's consensus-version count exactly —\n// a shorter list panics with an opaque `unreachable` inside the WASM.\nconst DEVNODE_CONSENSUS_HEIGHTS = '0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16'\n\nfunction privateKeyToAccount(privateKey: string): LocalAccount<'privateKey'> {\n const sdkAccount = new Account({ privateKey })\n const address = sdkAccount.address().to_string()\n const viewKey = sdkAccount.viewKey().to_string()\n\n const signFn = async (message: Uint8Array): Promise<Uint8Array> => {\n const sig = sdkAccount.sign(message)\n return new TextEncoder().encode(sig.to_string())\n }\n\n return {\n type: 'local',\n source: 'privateKey',\n address,\n privateKey,\n viewKey,\n sign: signFn,\n signMessage: signFn,\n }\n}\n\n/** Creates a new random Aleo account (uses static SDK binaries). */\nexport function generateAccount(): LocalAccount<'privateKey'> {\n const sdkAccount = new Account()\n return privateKeyToAccount(sdkAccount.privateKey().to_string())\n}\n\n/**\n * Creates a fully-wired client pair pointing at a local Aleo Devnode instance.\n *\n * Devnode is a lightweight local Aleo node (similar to Foundry's Anvil) that\n * bypasses consensus and skips ZK proof generation, enabling rapid program iteration.\n * The seeded account is pre-funded; both key and socket address can be overridden.\n *\n * The returned wallet client supports `executeContract`. Its confirmation wait\n * resolves once the devnode includes the transaction in a block — automatic\n * after broadcast by default; under `manualBlockCreation` the caller must\n * advance blocks (e.g. a test client's `advanceBlock`) while the call is\n * pending. Record outputs owned by the client's account are decrypted to\n * plaintext in the result; foreign records are dropped.\n *\n * @example\n * ```ts\n * // Zero-config — uses seeded key and localhost:3030\n * const { publicClient, walletClient, account } = createDevnodeClient()\n *\n * // Custom key or socket address\n * const { publicClient, walletClient, account } = createDevnodeClient({\n * privateKey: 'APrivateKey1...',\n * socketAddr: '127.0.0.1:4040',\n * })\n * ```\n */\nexport function createDevnodeClient(options?: {\n privateKey?: string\n /** Socket address of the devnode, e.g. \"127.0.0.1:3030\" */\n socketAddr?: string\n}): { publicClient: PublicClient; walletClient: WalletClient; account: LocalAccount<'privateKey'> } {\n const url = `http://${options?.socketAddr ?? DEVNODE_ADDR}`\n const account = privateKeyToAccount(options?.privateKey ?? DEVNODE_PRIVATE_KEY)\n const sdkAccount = new Account({ privateKey: account.privateKey })\n const transport = http(url, { network: 'testnet' })\n\n const keyProvider = new AleoKeyProvider()\n keyProvider.useCache(true)\n\n // Initialize the wasm consensus heights before any wasm build or parse call\n // this client makes. Idempotent get-or-init: safe to call per client.\n getOrInitConsensusVersionTestHeights(DEVNODE_CONSENSUS_HEIGHTS)\n\n // Created before the proving config so `execute` can broadcast and poll\n // through the same transport-backed client the caller receives.\n const publicClient = createPublicClient({ transport })\n\n /**\n * Builds an unproven devnode execution transaction. `imports` must already\n * map program id → source; resolution of dynamic-dispatch import names\n * happens in `buildTransaction`, not here. Priority fees are always 0 on\n * the devnode path — a caller-supplied fee is ignored.\n */\n const buildExecutionTx = async (opts: {\n programName: string\n functionName: string\n inputs: string[]\n privateFee?: boolean | undefined\n imports?: Record<string, string> | undefined\n }) => {\n const programManager = new ProgramManager(url, keyProvider, undefined)\n programManager.setAccount(sdkAccount)\n return programManager.buildDevnodeExecutionTransaction({\n programName: opts.programName,\n functionName: opts.functionName,\n priorityFee: 0,\n privateFee: opts.privateFee ?? false,\n inputs: opts.inputs,\n ...(opts.imports ? { imports: opts.imports } : {}),\n })\n }\n\n const proving: ProvingConfig = {\n mode: 'devnode',\n buildDeployment: async (deployOptions: BuildDeploymentOptions) => {\n const programManager = new ProgramManager(url, keyProvider, undefined)\n programManager.setAccount(sdkAccount)\n const tx = await programManager.buildDevnodeDeploymentTransaction({\n program: deployOptions.program,\n priorityFee: 0,\n privateFee: deployOptions.privateFee ?? false,\n })\n return JSON.parse(tx.toString())\n },\n buildTransaction: async (txOptions: BuildTransactionOptions) => {\n // Fetch program sources for any call.dynamic targets the caller declared,\n // and recursively include their static imports as well.\n // Use direct REST calls instead of the SDK network client to avoid the\n // /latest_edition endpoint which returns 500 on the devnode.\n let imports: Record<string, string> | undefined\n if (txOptions.imports && txOptions.imports.length > 0) {\n const networkClient = new ProgramManager(url, keyProvider, undefined).networkClient\n imports = {}\n const queue = [...txOptions.imports]\n const seen = new Set<string>()\n while (queue.length > 0) {\n const name = queue.shift()!\n if (seen.has(name)) continue\n seen.add(name)\n const source = await networkClient.getProgram(name); // automatically throws.\n imports[name] = source;\n const importNames = Program.fromString(source).getImports(); // Invoke `wasm` to avoid regex.\n for (const dep of importNames) {\n if (dep && !seen.has(dep)) queue.push(dep)\n }\n }\n }\n\n const tx = await buildExecutionTx({\n programName: txOptions.programName,\n functionName: txOptions.functionName,\n inputs: txOptions.inputs,\n privateFee: txOptions.privateFee,\n imports,\n })\n return JSON.parse(tx.toString())\n },\n execute: async (execOptions: ExecuteOptions): Promise<RawExecuteResult> => {\n const tx = await buildExecutionTx({\n programName: execOptions.programName,\n functionName: execOptions.functionName,\n inputs: execOptions.inputs,\n privateFee: execOptions.privateFee,\n imports: execOptions.programImports,\n })\n\n // Broadcast through the same transport-backed request writeContract uses.\n const txId = (await publicClient.request({\n method: 'sendTransaction',\n params: { transaction: tx.toString() },\n })) as string\n\n // The devnode auto-produces a block after broadcast by default; under\n // manualBlockCreation the caller must advance blocks for this to resolve.\n const confirmedTx = await waitForConfirmation(publicClient, txId)\n\n // Self-custody decryptor: records owned by the devnode account surface\n // as plaintext; records owned by someone else (e.g. a compliance record\n // minted to an authority) pass through as ciphertext rather than being\n // dropped, so the outputs keep their transition positions — positional\n // consumers like the generated contract bindings depend on that.\n const accountViewKey = StaticViewKey.from_string(account.viewKey)\n const decryptor: Decryptor = (ciphertext: string) => {\n const ct = StaticRecordCiphertext.fromString(ciphertext)\n return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : ciphertext\n }\n const { transitions, outputs } = extractTransitions(confirmedTx, decryptor)\n return { transactionId: txId, transitions, outputs }\n },\n }\n\n const walletClient = createWalletClient({ account, transport, proving })\n\n return { publicClient, walletClient, account }\n}\n","import { hmac } from '@noble/hashes/hmac'\nimport { sha512 } from '@noble/hashes/sha512'\nimport * as bip39 from '@scure/bip39'\nimport { wordlist } from '@scure/bip39/wordlists/english'\n\nconst HARDENED_OFFSET = 0x80000000\n\n// Aleo-specific HMAC key for HD master derivation (parallel to BIP32's\n// \"Bitcoin seed\", but for BLS12-377). Matches shield-core.\nconst BLS12_377_CURVE = 'bls12_377 seed'\n\nconst PATH_REGEX = /^m(\\/[0-9]+')+$/\n\n/**\n * Names the derivation-path convention used to turn a seed into Aleo keys.\n *\n * `'standard'` uses the SLIP-0044-registered Aleo coin type (`m/44'/683'`);\n * `'legacy'` uses the pre-registration path (`m/44'/0'`) some older wallets\n * chose. Pick `'legacy'` only to recover accounts created by such a wallet.\n */\nexport type AleoDerivationId = 'standard' | 'legacy'\n\n/** SLIP-0044 registered Aleo coin type. */\nexport const STANDARD_PATH = \"m/44'/683'\"\n\n/** Pre-SLIP-0044-registration derivation path. Some older wallets used this. */\nexport const LEGACY_PATH = \"m/44'/0'\"\n\n/** Maps each {@link AleoDerivationId} to its account-level derivation path. */\nexport const DERIVATION_PATHS: Record<AleoDerivationId, string> = {\n standard: STANDARD_PATH,\n legacy: LEGACY_PATH,\n}\n\ninterface IKeys {\n key: Uint8Array\n chainCode: Uint8Array\n}\n\nfunction uint32BE(n: number): Uint8Array {\n if (!Number.isInteger(n) || n < 0 || n > 0xffffffff) {\n throw new Error(`uint32BE: value out of range (got ${n})`)\n }\n const out = new Uint8Array(4)\n new DataView(out.buffer).setUint32(0, n, false)\n return out\n}\n\nfunction concatBytes(...parts: Uint8Array[]): Uint8Array {\n const total = parts.reduce((sum, p) => sum + p.length, 0)\n const out = new Uint8Array(total)\n let offset = 0\n for (const p of parts) {\n out.set(p, offset)\n offset += p.length\n }\n return out\n}\n\nfunction ckdPriv({ key, chainCode }: IKeys, index: number): IKeys {\n const data = concatBytes(new Uint8Array([0]), key, uint32BE(index))\n const I = hmac(sha512, chainCode, data)\n return { key: I.slice(0, 32), chainCode: I.slice(32) }\n}\n\nfunction getMasterKeyFromSeed(seed: Uint8Array): IKeys {\n const I = hmac(sha512, BLS12_377_CURVE, seed)\n return { key: I.slice(0, 32), chainCode: I.slice(32) }\n}\n\nfunction isValidPath(path: string): boolean {\n if (!PATH_REGEX.test(path)) return false\n return path\n .split('/')\n .slice(1)\n .map((s) => s.replace(\"'\", ''))\n .every((s) => Number.isFinite(Number(s)))\n}\n\n/**\n * Hierarchical-deterministic key node for the BLS12-377 curve Aleo uses.\n *\n * Follows the SLIP-0010 construction (HMAC-SHA512 chains, hardened-only\n * derivation) with an Aleo-specific master key tag, matching shield-core.\n * All operations are pure and local — nothing touches the network. Start\n * from {@link BLS12377HDKey.fromMasterSeed} (or {@link mnemonicToHDKey})\n * rather than the constructor; the 32-byte `key` of a derived node is the\n * seed for an Aleo private key.\n */\nexport class BLS12377HDKey {\n /**\n * Wraps raw node material. Callers normally use\n * {@link BLS12377HDKey.fromMasterSeed} instead of constructing directly.\n *\n * @param key 32-byte private key material of this node.\n * @param chainCode 32-byte chain code used to derive children.\n */\n constructor(\n public readonly key: Uint8Array,\n public readonly chainCode: Uint8Array,\n ) {}\n\n /**\n * Derives the master node from a BIP-39 seed. Pure and local.\n *\n * @param seed Seed bytes, typically the 64-byte output of\n * {@link mnemonicToSeed}.\n * @returns The root node from which paths are derived.\n */\n static fromMasterSeed(seed: Uint8Array): BLS12377HDKey {\n const master = getMasterKeyFromSeed(seed)\n return new BLS12377HDKey(master.key, master.chainCode)\n }\n\n /**\n * Derives the descendant node at a hardened path. Pure and local.\n *\n * @param path Path of the form `m/44'/683'` — every segment MUST be\n * hardened (trailing `'`) and below 2^31.\n * @returns A new node; this node is unchanged.\n * @throws If the path is malformed, contains a non-hardened segment, or a\n * segment is out of range.\n */\n derive(path: string): BLS12377HDKey {\n if (!isValidPath(path)) {\n throw new Error(\n `Invalid derivation path: ${path} (must match m/N'/N'/... — hardened only)`,\n )\n }\n const segments = path\n .split('/')\n .slice(1)\n .map((s) => parseInt(s.replace(\"'\", ''), 10))\n\n for (const seg of segments) {\n if (seg >= HARDENED_OFFSET) {\n throw new Error(\n `Derivation path segment out of range: ${seg} (must be < 2³¹)`,\n )\n }\n }\n\n const result = segments.reduce(\n (acc, segment) => ckdPriv(acc, segment + HARDENED_OFFSET),\n { key: this.key, chainCode: this.chainCode } as IKeys,\n )\n return new BLS12377HDKey(result.key, result.chainCode)\n }\n\n /** Alias for {@link BLS12377HDKey.derive}, kept for HD-key API parity. */\n derivePath(path: string): BLS12377HDKey {\n return this.derive(path)\n }\n\n /**\n * Derives the account node at `m/{index}'/0'` relative to this node. Pure\n * and local. Applied to a {@link DERIVATION_PATHS} node, this yields the\n * account at that index.\n *\n * @param index Zero-based account index, below 2^31; hardening is applied\n * internally.\n * @returns The account-level node.\n * @throws If the index is negative, fractional, or 2^31 or greater.\n */\n deriveChild(index: number): BLS12377HDKey {\n if (!Number.isInteger(index) || index < 0 || index >= HARDENED_OFFSET) {\n throw new Error(\n `Invalid child index: ${index} (must be integer in [0, 2³¹))`,\n )\n }\n return this.derive(`m/${index}'/0'`)\n }\n}\n\n/**\n * Generates a fresh BIP-39 mnemonic from the English wordlist.\n *\n * Draws entropy from the platform CSPRNG; no network access. The phrase is\n * the root secret for every account derived from it — the caller MUST store\n * it securely and never log it.\n *\n * @param strength Entropy in bits: 128 yields 12 words, 256 yields 24.\n * Defaults to 128.\n * @returns A space-separated mnemonic phrase.\n *\n * @example\n * import { generateMnemonic, mnemonicToHDKey } from '@provablehq/veil-aleo-sdk'\n *\n * const mnemonic = generateMnemonic()\n * const account0 = mnemonicToHDKey(mnemonic)\n */\nexport function generateMnemonic(strength: 128 | 256 = 128): string {\n return bip39.generateMnemonic(wordlist, strength)\n}\n\n/**\n * Checks a full mnemonic phrase against BIP-39: English wordlist membership,\n * word count, and checksum. Pure and local.\n *\n * @param mnemonic Space-separated candidate phrase.\n * @returns True only if the phrase can be used for key derivation; a single\n * wrong or reordered word fails the checksum.\n */\nexport function validateMnemonic(mnemonic: string): boolean {\n return bip39.validateMnemonic(mnemonic, wordlist)\n}\n\n/**\n * Checks whether a single word belongs to the English BIP-39 wordlist. Pure\n * and local. Use for per-word feedback while a phrase is being typed;\n * validating the complete phrase still requires {@link validateMnemonic}.\n *\n * @param word Candidate word, lowercase.\n * @returns True if the word is one of the 2048 list entries.\n */\nexport function validateWord(word: string): boolean {\n return wordlist.includes(word)\n}\n\n/**\n * Converts a mnemonic to its 64-byte BIP-39 seed via PBKDF2-HMAC-SHA512 with\n * an empty passphrase. Pure, local, and deterministic.\n *\n * The mnemonic is not validated here — call {@link validateMnemonic} first;\n * an invalid phrase still produces a seed, only for the wrong accounts.\n *\n * @param mnemonic Space-separated BIP-39 phrase.\n * @returns Seed bytes for {@link BLS12377HDKey.fromMasterSeed}.\n */\nexport function mnemonicToSeed(mnemonic: string): Uint8Array {\n return bip39.mnemonicToSeedSync(mnemonic)\n}\n\n/**\n * Derives the Aleo account key at the given index from a mnemonic in one\n * step: seed, master node, derivation path, account child. Pure and local.\n * This is the usual entry point for turning a stored phrase into key\n * material.\n *\n * @param mnemonic Space-separated BIP-39 phrase.\n * @param options.index Zero-based account index, below 2^31. Defaults to 0.\n * @param options.derivation Path convention. Defaults to `'standard'`\n * (`m/44'/683'`); pass `'legacy'` to recover accounts from wallets that\n * predate the SLIP-0044 registration.\n * @returns The account node; its `key` bytes seed the Aleo private key.\n * @throws If the index is out of range.\n *\n * @example\n * import { mnemonicToHDKey } from '@provablehq/veil-aleo-sdk'\n *\n * const hdKey = mnemonicToHDKey(mnemonic, { index: 1 })\n */\nexport function mnemonicToHDKey(\n mnemonic: string,\n options: { index?: number; derivation?: AleoDerivationId } = {},\n): BLS12377HDKey {\n const { index = 0, derivation = 'standard' } = options\n const seed = mnemonicToSeed(mnemonic)\n return BLS12377HDKey.fromMasterSeed(seed)\n .derivePath(DERIVATION_PATHS[derivation])\n .deriveChild(index)\n}\n"],"mappings":";AAsBA,SAAS,eAAe,eAAe;AACvC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA,oBAAoB;AAAA,EACpB,WAAW;AAAA,EACX;AAAA,OACK;AACP,SAAS,qBAAqB,oBAAoB;AAMlD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACjDP,SAAS,YAAY;AACrB,SAAS,cAAc;AACvB,YAAY,WAAW;AACvB,SAAS,gBAAgB;AAEzB,IAAM,kBAAkB;AAIxB,IAAM,kBAAkB;AAExB,IAAM,aAAa;AAYZ,IAAM,gBAAgB;AAGtB,IAAM,cAAc;AAGpB,IAAM,mBAAqD;AAAA,EAChE,UAAU;AAAA,EACV,QAAQ;AACV;AAOA,SAAS,SAAS,GAAuB;AACvC,MAAI,CAAC,OAAO,UAAU,CAAC,KAAK,IAAI,KAAK,IAAI,YAAY;AACnD,UAAM,IAAI,MAAM,qCAAqC,CAAC,GAAG;AAAA,EAC3D;AACA,QAAM,MAAM,IAAI,WAAW,CAAC;AAC5B,MAAI,SAAS,IAAI,MAAM,EAAE,UAAU,GAAG,GAAG,KAAK;AAC9C,SAAO;AACT;AAEA,SAAS,eAAe,OAAiC;AACvD,QAAM,QAAQ,MAAM,OAAO,CAAC,KAAK,MAAM,MAAM,EAAE,QAAQ,CAAC;AACxD,QAAM,MAAM,IAAI,WAAW,KAAK;AAChC,MAAI,SAAS;AACb,aAAW,KAAK,OAAO;AACrB,QAAI,IAAI,GAAG,MAAM;AACjB,cAAU,EAAE;AAAA,EACd;AACA,SAAO;AACT;AAE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M,GAAG,SAAS,CAAC;AAAA,IACjC;AAAA,IACA,SAAS,OAAO,gBAA2D;AACzE,YAAM,KAAK,MAAM,iBAAiB;AAAA,QAChC,aAAa,YAAY;AAAA,QACzB,cAAc,YAAY;AAAA,QAC1B,QAAQ,YAAY;AAAA,QACpB,YAAY,YAAY;AAAA,QACxB,SAAS,YAAY;AAAA,MACvB,CAAC;AAGD,YAAM,OAAQ,MAAM,aAAa,QAAQ;AAAA,QACvC,QAAQ;AAAA,QACR,QAAQ,EAAE,aAAa,GAAG,SAAS,EAAE;AAAA,MACvC,CAAC;AAID,YAAM,cAAc,MAAM,oBAAoB,cAAc,IAAI;AAOhE,YAAM,iBAAiB,cAAc,YAAY,QAAQ,OAAO;AAChE,YAAM,YAAuB,CAAC,eAAuB;AACnD,cAAM,KAAK,uBAAuB,WAAW,UAAU;AACvD,eAAO,GAAG,QAAQ,cAAc,IAAI,GAAG,QAAQ,cAAc,EAAE,SAAS,IAAI;AAAA,MAC9E;AACA,YAAM,EAAE,aAAa,QAAQ,IAAI,mBAAmB,aAAa,SAAS;AAC1E,aAAO,EAAE,eAAe,MAAM,aAAa,QAAQ;AAAA,IACrD;AAAA,EACF;AAEA,QAAM,eAAe,mBAAmB,EAAE,SAAS,WAAW,QAAQ,CAAC;AAEvE,SAAO,EAAE,cAAc,cAAc,QAAQ;AAC/C;","names":["generateMnemonic","validateMnemonic","Account","generateMnemonic","generateAccount"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@provablehq/veil-aleo-sdk",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "description": "Local signing and proving for the Veil Aleo SDK, backed by the Provable SDK.",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -29,8 +29,8 @@
29
29
  "access": "public"
30
30
  },
31
31
  "peerDependencies": {
32
- "@provablehq/veil-core": "0.4.0",
33
- "@provablehq/veil-aleo-devnode": "0.4.0"
32
+ "@provablehq/veil-core": "^0.5.0",
33
+ "@provablehq/veil-aleo-devnode": "^0.5.0"
34
34
  },
35
35
  "dependencies": {
36
36
  "@noble/hashes": "^1.7.2",
@@ -38,7 +38,7 @@
38
38
  "@scure/bip39": "^1.4.0"
39
39
  },
40
40
  "devDependencies": {
41
- "@provablehq/veil-leo": "0.4.0"
41
+ "@provablehq/veil-leo": "0.5.0"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "tsup",