@provablehq/veil-aleo-sdk 0.4.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Provable Inc.
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,89 @@
1
+ # @provablehq/veil-aleo-sdk
2
+
3
+ Local signing and proving for the Veil Aleo SDK, backed by the Provable WASM SDK
4
+ (`@provablehq/sdk`).
5
+
6
+ Reach for this package when the caller holds an Aleo private key directly — bots,
7
+ scripts, tests, and CI — rather than connecting a wallet. It turns a private key
8
+ into an account, wires a wallet client with proving configured (delegated or
9
+ local), builds record scanners, and derives the same account keys (address, view
10
+ key) and blinded claim identity that private flows depend on. Because it loads
11
+ WASM, an app that connects a wallet instead — the wallet holds the keys and
12
+ proves for you — generally does not need this package at all.
13
+
14
+ ## Installation
15
+
16
+ ```sh
17
+ pnpm add @provablehq/veil-aleo-sdk @provablehq/veil-core
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ Load the SDK for a network, then build the account, scanner, and clients from
23
+ the returned handle. `loadNetwork` is async because it fetches the network's WASM
24
+ binaries; the handle it returns is synchronous from there on.
25
+
26
+ ```ts
27
+ import { loadNetwork } from '@provablehq/veil-aleo-sdk'
28
+
29
+ const aleo = await loadNetwork('testnet')
30
+
31
+ // A record scanner so the wallet client can find the private records that
32
+ // program calls spend. The first requestRecords registers the view key with the
33
+ // service (one network round-trip); later calls reuse it.
34
+ const scanner = aleo.createRemoteScanner({
35
+ url: 'https://api.provable.com/scanner',
36
+ consumerId: CONSUMER_ID,
37
+ apiKey: DPS_API_KEY, // authenticates + registers the view key for scanning
38
+ })
39
+
40
+ // A fully-wired client pair: an account from the private key, a public client
41
+ // for reads, and a wallet client with proving + the scanner attached.
42
+ const { publicClient, walletClient, account } = aleo.createAleoClient({
43
+ privateKey: PRIVATE_KEY,
44
+ networkUrl: 'https://api.provable.com/v2',
45
+ provingMode: 'delegated',
46
+ proverUrl: 'https://api.provable.com/prove/testnet',
47
+ apiKey: DPS_API_KEY,
48
+ consumerId: CONSUMER_ID,
49
+ records: scanner,
50
+ })
51
+
52
+ account.address // 'aleo1...'
53
+ ```
54
+
55
+ Pass `provingMode: 'local'` to prove in-process instead of delegating to a prover
56
+ service (drop `proverUrl`/`apiKey`/`consumerId`). The `walletClient` composes with
57
+ action packages the same way a wallet-backed client does:
58
+
59
+ ```ts
60
+ import { shieldSwapActions } from '@provablehq/shield-swap-sdk'
61
+
62
+ const client = walletClient.extend(
63
+ shieldSwapActions({ api: { baseUrl: 'https://amm-api.dev.provable.com' } }),
64
+ )
65
+ ```
66
+
67
+ The handle also exposes the pieces individually when the caller does not want the
68
+ full pair:
69
+
70
+ - `aleo.privateKeyToAccount(privateKey)` / `aleo.mnemonicToAccount(mnemonic)` /
71
+ `aleo.generateAccount()` — build a `LocalAccount`.
72
+ - `aleo.createProvingConfig({ ... })` — the `proving` config for
73
+ `createWalletClient({ proving })`.
74
+ - `aleo.createStandaloneScanner({ ... })` — a scanner keyed by an explicit view
75
+ key, with no account attached.
76
+ - `aleo.decryptRecord(viewKey, ciphertext)` / `aleo.verifySignature(...)` —
77
+ network-agnostic key operations.
78
+
79
+ For local iteration without a live chain, `createDevnodeClient()` returns the
80
+ same client pair pointed at an Aleo Devnode instance with a pre-funded seeded
81
+ account.
82
+
83
+ ## WASM dependency
84
+
85
+ `@provablehq/sdk` ships the Aleo cryptography as WebAssembly, and this package
86
+ loads it. That is the cost of holding keys and proving locally. An app that
87
+ connects a wallet — Shield, Leo — should build its client from the wallet adapter
88
+ instead (see `@provablehq/veil-aleo-wallet-adapter`) and skip `@provablehq/veil-aleo-sdk`, keeping the
89
+ WASM out of the bundle.
@@ -0,0 +1,346 @@
1
+ import { loadNetwork as loadNetwork$1 } from '@provablehq/sdk/dynamic.js';
2
+ export { DEVNODE_ADDR, DEVNODE_PRIVATE_KEY } from '@provablehq/veil-aleo-devnode';
3
+ import { LocalAccount, ProvingConfig, RecordProvider, StandaloneRecordScanner, PublicClient, WalletClient } from '@provablehq/veil-core';
4
+
5
+ /**
6
+ * Names the derivation-path convention used to turn a seed into Aleo keys.
7
+ *
8
+ * `'standard'` uses the SLIP-0044-registered Aleo coin type (`m/44'/683'`);
9
+ * `'legacy'` uses the pre-registration path (`m/44'/0'`) some older wallets
10
+ * chose. Pick `'legacy'` only to recover accounts created by such a wallet.
11
+ */
12
+ type AleoDerivationId = 'standard' | 'legacy';
13
+ /** SLIP-0044 registered Aleo coin type. */
14
+ declare const STANDARD_PATH = "m/44'/683'";
15
+ /** Pre-SLIP-0044-registration derivation path. Some older wallets used this. */
16
+ declare const LEGACY_PATH = "m/44'/0'";
17
+ /**
18
+ * Hierarchical-deterministic key node for the BLS12-377 curve Aleo uses.
19
+ *
20
+ * Follows the SLIP-0010 construction (HMAC-SHA512 chains, hardened-only
21
+ * derivation) with an Aleo-specific master key tag, matching shield-core.
22
+ * All operations are pure and local — nothing touches the network. Start
23
+ * from {@link BLS12377HDKey.fromMasterSeed} (or {@link mnemonicToHDKey})
24
+ * rather than the constructor; the 32-byte `key` of a derived node is the
25
+ * seed for an Aleo private key.
26
+ */
27
+ declare class BLS12377HDKey {
28
+ readonly key: Uint8Array;
29
+ readonly chainCode: Uint8Array;
30
+ /**
31
+ * Wraps raw node material. Callers normally use
32
+ * {@link BLS12377HDKey.fromMasterSeed} instead of constructing directly.
33
+ *
34
+ * @param key 32-byte private key material of this node.
35
+ * @param chainCode 32-byte chain code used to derive children.
36
+ */
37
+ constructor(key: Uint8Array, chainCode: Uint8Array);
38
+ /**
39
+ * Derives the master node from a BIP-39 seed. Pure and local.
40
+ *
41
+ * @param seed Seed bytes, typically the 64-byte output of
42
+ * {@link mnemonicToSeed}.
43
+ * @returns The root node from which paths are derived.
44
+ */
45
+ static fromMasterSeed(seed: Uint8Array): BLS12377HDKey;
46
+ /**
47
+ * Derives the descendant node at a hardened path. Pure and local.
48
+ *
49
+ * @param path Path of the form `m/44'/683'` — every segment MUST be
50
+ * hardened (trailing `'`) and below 2^31.
51
+ * @returns A new node; this node is unchanged.
52
+ * @throws If the path is malformed, contains a non-hardened segment, or a
53
+ * segment is out of range.
54
+ */
55
+ derive(path: string): BLS12377HDKey;
56
+ /** Alias for {@link BLS12377HDKey.derive}, kept for HD-key API parity. */
57
+ derivePath(path: string): BLS12377HDKey;
58
+ /**
59
+ * Derives the account node at `m/{index}'/0'` relative to this node. Pure
60
+ * and local. Applied to a {@link DERIVATION_PATHS} node, this yields the
61
+ * account at that index.
62
+ *
63
+ * @param index Zero-based account index, below 2^31; hardening is applied
64
+ * internally.
65
+ * @returns The account-level node.
66
+ * @throws If the index is negative, fractional, or 2^31 or greater.
67
+ */
68
+ deriveChild(index: number): BLS12377HDKey;
69
+ }
70
+ /**
71
+ * Generates a fresh BIP-39 mnemonic from the English wordlist.
72
+ *
73
+ * Draws entropy from the platform CSPRNG; no network access. The phrase is
74
+ * the root secret for every account derived from it — the caller MUST store
75
+ * it securely and never log it.
76
+ *
77
+ * @param strength Entropy in bits: 128 yields 12 words, 256 yields 24.
78
+ * Defaults to 128.
79
+ * @returns A space-separated mnemonic phrase.
80
+ *
81
+ * @example
82
+ * import { generateMnemonic, mnemonicToHDKey } from '@provablehq/veil-aleo-sdk'
83
+ *
84
+ * const mnemonic = generateMnemonic()
85
+ * const account0 = mnemonicToHDKey(mnemonic)
86
+ */
87
+ declare function generateMnemonic(strength?: 128 | 256): string;
88
+ /**
89
+ * Checks a full mnemonic phrase against BIP-39: English wordlist membership,
90
+ * word count, and checksum. Pure and local.
91
+ *
92
+ * @param mnemonic Space-separated candidate phrase.
93
+ * @returns True only if the phrase can be used for key derivation; a single
94
+ * wrong or reordered word fails the checksum.
95
+ */
96
+ declare function validateMnemonic(mnemonic: string): boolean;
97
+ /**
98
+ * Checks whether a single word belongs to the English BIP-39 wordlist. Pure
99
+ * and local. Use for per-word feedback while a phrase is being typed;
100
+ * validating the complete phrase still requires {@link validateMnemonic}.
101
+ *
102
+ * @param word Candidate word, lowercase.
103
+ * @returns True if the word is one of the 2048 list entries.
104
+ */
105
+ declare function validateWord(word: string): boolean;
106
+ /**
107
+ * Converts a mnemonic to its 64-byte BIP-39 seed via PBKDF2-HMAC-SHA512 with
108
+ * an empty passphrase. Pure, local, and deterministic.
109
+ *
110
+ * The mnemonic is not validated here — call {@link validateMnemonic} first;
111
+ * an invalid phrase still produces a seed, only for the wrong accounts.
112
+ *
113
+ * @param mnemonic Space-separated BIP-39 phrase.
114
+ * @returns Seed bytes for {@link BLS12377HDKey.fromMasterSeed}.
115
+ */
116
+ declare function mnemonicToSeed(mnemonic: string): Uint8Array;
117
+ /**
118
+ * Derives the Aleo account key at the given index from a mnemonic in one
119
+ * step: seed, master node, derivation path, account child. Pure and local.
120
+ * This is the usual entry point for turning a stored phrase into key
121
+ * material.
122
+ *
123
+ * @param mnemonic Space-separated BIP-39 phrase.
124
+ * @param options.index Zero-based account index, below 2^31. Defaults to 0.
125
+ * @param options.derivation Path convention. Defaults to `'standard'`
126
+ * (`m/44'/683'`); pass `'legacy'` to recover accounts from wallets that
127
+ * predate the SLIP-0044 registration.
128
+ * @returns The account node; its `key` bytes seed the Aleo private key.
129
+ * @throws If the index is out of range.
130
+ *
131
+ * @example
132
+ * import { mnemonicToHDKey } from '@provablehq/veil-aleo-sdk'
133
+ *
134
+ * const hdKey = mnemonicToHDKey(mnemonic, { index: 1 })
135
+ */
136
+ declare function mnemonicToHDKey(mnemonic: string, options?: {
137
+ index?: number;
138
+ derivation?: AleoDerivationId;
139
+ }): BLS12377HDKey;
140
+
141
+ /**
142
+ * @provablehq/veil-aleo-sdk
143
+ *
144
+ * Loads `@provablehq/sdk` for a specific Aleo network and exposes the SDK's
145
+ * functionality bound to that network's setup parameters.
146
+ *
147
+ * Usage:
148
+ * import { loadNetwork } from '@provablehq/veil-aleo-sdk'
149
+ * import { http } from '@provablehq/veil-core'
150
+ *
151
+ * const aleo = await loadNetwork('mainnet')
152
+ *
153
+ * const account = aleo.privateKeyToAccount('APrivateKey1...')
154
+ * const { publicClient, walletClient } = aleo.createAleoClient({
155
+ * privateKey: 'APrivateKey1...',
156
+ * networkUrl: 'https://api.provable.com/v2',
157
+ * })
158
+ *
159
+ * Switching networks: load a new handle. Existing accounts remain valid —
160
+ * Aleo private keys, view keys, and addresses are network-agnostic.
161
+ */
162
+
163
+ /** Networks supported by `@provablehq/sdk/dynamic.js`. */
164
+ type SupportedNetwork = 'mainnet' | 'testnet';
165
+ type SdkModule = Awaited<ReturnType<typeof loadNetwork$1<'testnet'>>>;
166
+ /**
167
+ * A network-bound SDK handle. All functions on this handle use the binary
168
+ * set loaded for the named network.
169
+ *
170
+ * Most key/account operations (`privateKeyToAccount`, `mnemonicToAccount`,
171
+ * `generateAccount`, `decryptRecord`, `verifySignature`) are mathematically
172
+ * network-agnostic — the same private key (or mnemonic) derives the same
173
+ * address and view key regardless of which network's binary was loaded.
174
+ * Proving and program operations (`createProvingConfig`, `createAleoClient`,
175
+ * scanners) are network-bound.
176
+ */
177
+ interface AleoSdk {
178
+ /** The network this handle is bound to. */
179
+ readonly network: SupportedNetwork;
180
+ /** Creates a `LocalAccount` from an Aleo private key. */
181
+ privateKeyToAccount(privateKey: string): LocalAccount<'privateKey'>;
182
+ /**
183
+ * Creates a `LocalAccount` from a BIP39 mnemonic phrase using Aleo's
184
+ * BLS12-377 HD derivation (matches Shield wallet derivation).
185
+ *
186
+ * Defaults to the SLIP-0044 Aleo coin type path `m/44'/683'`, account
187
+ * index 0. Pass `derivation: 'legacy'` to use the pre-registration path
188
+ * `m/44'/0'` for compatibility with older wallets.
189
+ */
190
+ mnemonicToAccount(mnemonic: string, options?: {
191
+ index?: number;
192
+ derivation?: AleoDerivationId;
193
+ }): LocalAccount<'mnemonic'>;
194
+ /**
195
+ * Generates a fresh BIP39 mnemonic and derives its Aleo account in one call.
196
+ * Pure and local — no network access. The caller MUST persist the returned
197
+ * mnemonic; it is the only way to re-derive the account.
198
+ *
199
+ * @param options.strength Entropy bits: 128 (12 words, default) or 256 (24 words).
200
+ * @param options.index Account index on the derivation path. Defaults to 0.
201
+ * @param options.derivation Derivation path id. Defaults to `'standard'`
202
+ * (`m/44'/683'`); pass `'legacy'` for pre-registration `m/44'/0'` wallets.
203
+ * @returns The generated mnemonic and the account derived from it.
204
+ *
205
+ * @example
206
+ * const { mnemonic, account } = aleo.generateMnemonicAccount()
207
+ * // store `mnemonic` safely; `account.address` is ready to use
208
+ */
209
+ generateMnemonicAccount(options?: {
210
+ strength?: 128 | 256;
211
+ index?: number;
212
+ derivation?: AleoDerivationId;
213
+ }): {
214
+ mnemonic: string;
215
+ account: LocalAccount<'mnemonic'>;
216
+ };
217
+ /** Creates a new random Aleo account. */
218
+ generateAccount(): LocalAccount<'privateKey'>;
219
+ /** Decrypts a record ciphertext using a view key. */
220
+ decryptRecord(viewKey: string, ciphertext: string): string;
221
+ /** Verifies a signature against a message and address. */
222
+ verifySignature(address: string, message: Uint8Array, signature: string): boolean;
223
+ /** Creates an `AleoNetworkClient` for direct SDK access. */
224
+ createNetworkClient(url: string): InstanceType<SdkModule['AleoNetworkClient']>;
225
+ /** Creates a `ProvingConfig` for `createWalletClient({ proving })`. */
226
+ createProvingConfig(options: {
227
+ mode: 'delegated' | 'local';
228
+ networkUrl: string;
229
+ proverUrl?: string;
230
+ apiKey?: string;
231
+ consumerId?: string;
232
+ account?: LocalAccount<'privateKey'>;
233
+ confirmationTimeout?: number;
234
+ }): ProvingConfig;
235
+ /**
236
+ * Creates a record scanner backed by Provable's Record Scanner Service.
237
+ *
238
+ * The first `requestRecords` call registers the account's view key with the
239
+ * service (a network round-trip) to obtain the UUID scanning requires;
240
+ * subsequent calls reuse it. `setAccount` resets the registration.
241
+ *
242
+ * The provider implements `switchNetwork`, so a wallet client carrying it
243
+ * re-targets record scanning when `switchChain` runs — the scanner rebuilds
244
+ * against the new network and re-registers lazily on the next scan.
245
+ *
246
+ * @param options.url Base URL of the service (the SDK appends the network
247
+ * segment — do not include it).
248
+ * @param options.consumerId Consumer id used for JWT refresh.
249
+ * @param options.apiKey Optional API key for the authenticated service
250
+ * (e.g. the hosted Provable RSS). Omit for an open/unauthenticated service.
251
+ * @param options.startBlock Optional block height to begin scanning from at
252
+ * registration. Defaults to 0 (full history).
253
+ */
254
+ createRemoteScanner(options: {
255
+ url: string;
256
+ consumerId: string;
257
+ apiKey?: string;
258
+ startBlock?: number;
259
+ }): RecordProvider;
260
+ /**
261
+ * Creates a standalone record scanner with an explicit view key.
262
+ *
263
+ * Like {@link createRemoteScanner}, the first `requestRecords` registers the
264
+ * view key with the service (a network round-trip) to obtain the scanning UUID.
265
+ *
266
+ * @param options.url Base URL of the service (the SDK appends the network segment).
267
+ * @param options.consumerId Consumer id used for JWT refresh.
268
+ * @param options.viewKey The view key (`AViewKey1…`) to scan and decrypt with.
269
+ * @param options.apiKey Optional API key for the authenticated service. Omit
270
+ * for an open/unauthenticated service.
271
+ * @param options.startBlock Optional block height to begin scanning from at
272
+ * registration. Defaults to 0 (full history).
273
+ */
274
+ createStandaloneScanner(options: {
275
+ url: string;
276
+ consumerId: string;
277
+ viewKey: string;
278
+ apiKey?: string;
279
+ startBlock?: number;
280
+ }): StandaloneRecordScanner;
281
+ /** Creates a fully-wired Aleo client from a private key and network URL. */
282
+ createAleoClient(options: {
283
+ privateKey: string;
284
+ networkUrl: string;
285
+ provingMode?: 'delegated' | 'local';
286
+ proverUrl?: string;
287
+ apiKey?: string;
288
+ consumerId?: string;
289
+ /**
290
+ * Record provider for `requestRecords`. Not wired by default — pass
291
+ * `aleo.createRemoteScanner(...)` or any
292
+ * custom `RecordProvider`. `requestRecords` throws with a setup hint
293
+ * when no provider is configured.
294
+ */
295
+ records?: RecordProvider;
296
+ }): {
297
+ publicClient: PublicClient;
298
+ walletClient: WalletClient;
299
+ account: LocalAccount<'privateKey'>;
300
+ };
301
+ }
302
+ /**
303
+ * Loads `@provablehq/sdk` for the named network and returns a network-bound
304
+ * handle. The SDK module cache memoizes the load — calling twice for the
305
+ * same network returns the same binary set without re-instantiating.
306
+ */
307
+ declare function loadNetwork(name: SupportedNetwork): Promise<AleoSdk>;
308
+ /** Creates a new random Aleo account (uses static SDK binaries). */
309
+ declare function generateAccount(): LocalAccount<'privateKey'>;
310
+ /**
311
+ * Creates a fully-wired client pair pointing at a local Aleo Devnode instance.
312
+ *
313
+ * Devnode is a lightweight local Aleo node (similar to Foundry's Anvil) that
314
+ * bypasses consensus and skips ZK proof generation, enabling rapid program iteration.
315
+ * The seeded account is pre-funded; both key and socket address can be overridden.
316
+ *
317
+ * The returned wallet client supports `executeContract`. Its confirmation wait
318
+ * resolves once the devnode includes the transaction in a block — automatic
319
+ * after broadcast by default; under `manualBlockCreation` the caller must
320
+ * advance blocks (e.g. a test client's `advanceBlock`) while the call is
321
+ * pending. Record outputs owned by the client's account are decrypted to
322
+ * plaintext in the result; foreign records are dropped.
323
+ *
324
+ * @example
325
+ * ```ts
326
+ * // Zero-config — uses seeded key and localhost:3030
327
+ * const { publicClient, walletClient, account } = createDevnodeClient()
328
+ *
329
+ * // Custom key or socket address
330
+ * const { publicClient, walletClient, account } = createDevnodeClient({
331
+ * privateKey: 'APrivateKey1...',
332
+ * socketAddr: '127.0.0.1:4040',
333
+ * })
334
+ * ```
335
+ */
336
+ declare function createDevnodeClient(options?: {
337
+ privateKey?: string;
338
+ /** Socket address of the devnode, e.g. "127.0.0.1:3030" */
339
+ socketAddr?: string;
340
+ }): {
341
+ publicClient: PublicClient;
342
+ walletClient: WalletClient;
343
+ account: LocalAccount<'privateKey'>;
344
+ };
345
+
346
+ export { type AleoDerivationId, type AleoSdk, BLS12377HDKey, LEGACY_PATH, STANDARD_PATH, type SupportedNetwork, createDevnodeClient, generateAccount, generateMnemonic, loadNetwork, mnemonicToHDKey, mnemonicToSeed, validateMnemonic, validateWord };
package/dist/index.js ADDED
@@ -0,0 +1,679 @@
1
+ // src/index.ts
2
+ import { loadNetwork as loadSdk } from "@provablehq/sdk/dynamic.js";
3
+ import {
4
+ Account,
5
+ AleoKeyProvider,
6
+ Program,
7
+ ProgramManager,
8
+ RecordCiphertext as StaticRecordCiphertext,
9
+ ViewKey as StaticViewKey,
10
+ getOrInitConsensusVersionTestHeights
11
+ } from "@provablehq/sdk";
12
+ import { DEVNODE_PRIVATE_KEY, DEVNODE_ADDR } from "@provablehq/veil-aleo-devnode";
13
+ import {
14
+ createPublicClient,
15
+ createWalletClient,
16
+ http,
17
+ BaseError,
18
+ ProvingError,
19
+ ConfigurationError,
20
+ classifyBroadcastError,
21
+ classifyProvingError,
22
+ waitForConfirmation,
23
+ extractTransitions
24
+ } from "@provablehq/veil-core";
25
+
26
+ // src/mnemonic.ts
27
+ import { hmac } from "@noble/hashes/hmac";
28
+ import { sha512 } from "@noble/hashes/sha512";
29
+ import * as bip39 from "@scure/bip39";
30
+ import { wordlist } from "@scure/bip39/wordlists/english";
31
+ var HARDENED_OFFSET = 2147483648;
32
+ var BLS12_377_CURVE = "bls12_377 seed";
33
+ var PATH_REGEX = /^m(\/[0-9]+')+$/;
34
+ var STANDARD_PATH = "m/44'/683'";
35
+ var LEGACY_PATH = "m/44'/0'";
36
+ var DERIVATION_PATHS = {
37
+ standard: STANDARD_PATH,
38
+ legacy: LEGACY_PATH
39
+ };
40
+ function uint32BE(n) {
41
+ if (!Number.isInteger(n) || n < 0 || n > 4294967295) {
42
+ throw new Error(`uint32BE: value out of range (got ${n})`);
43
+ }
44
+ const out = new Uint8Array(4);
45
+ new DataView(out.buffer).setUint32(0, n, false);
46
+ return out;
47
+ }
48
+ function concatBytes(...parts) {
49
+ const total = parts.reduce((sum, p) => sum + p.length, 0);
50
+ const out = new Uint8Array(total);
51
+ let offset = 0;
52
+ for (const p of parts) {
53
+ out.set(p, offset);
54
+ offset += p.length;
55
+ }
56
+ return out;
57
+ }
58
+ function ckdPriv({ key, chainCode }, index) {
59
+ const data = concatBytes(new Uint8Array([0]), key, uint32BE(index));
60
+ const I = hmac(sha512, chainCode, data);
61
+ return { key: I.slice(0, 32), chainCode: I.slice(32) };
62
+ }
63
+ function getMasterKeyFromSeed(seed) {
64
+ const I = hmac(sha512, BLS12_377_CURVE, seed);
65
+ return { key: I.slice(0, 32), chainCode: I.slice(32) };
66
+ }
67
+ function isValidPath(path) {
68
+ if (!PATH_REGEX.test(path)) return false;
69
+ return path.split("/").slice(1).map((s) => s.replace("'", "")).every((s) => Number.isFinite(Number(s)));
70
+ }
71
+ var BLS12377HDKey = class _BLS12377HDKey {
72
+ /**
73
+ * Wraps raw node material. Callers normally use
74
+ * {@link BLS12377HDKey.fromMasterSeed} instead of constructing directly.
75
+ *
76
+ * @param key 32-byte private key material of this node.
77
+ * @param chainCode 32-byte chain code used to derive children.
78
+ */
79
+ constructor(key, chainCode) {
80
+ this.key = key;
81
+ this.chainCode = chainCode;
82
+ }
83
+ key;
84
+ chainCode;
85
+ /**
86
+ * Derives the master node from a BIP-39 seed. Pure and local.
87
+ *
88
+ * @param seed Seed bytes, typically the 64-byte output of
89
+ * {@link mnemonicToSeed}.
90
+ * @returns The root node from which paths are derived.
91
+ */
92
+ static fromMasterSeed(seed) {
93
+ const master = getMasterKeyFromSeed(seed);
94
+ return new _BLS12377HDKey(master.key, master.chainCode);
95
+ }
96
+ /**
97
+ * Derives the descendant node at a hardened path. Pure and local.
98
+ *
99
+ * @param path Path of the form `m/44'/683'` — every segment MUST be
100
+ * hardened (trailing `'`) and below 2^31.
101
+ * @returns A new node; this node is unchanged.
102
+ * @throws If the path is malformed, contains a non-hardened segment, or a
103
+ * segment is out of range.
104
+ */
105
+ derive(path) {
106
+ if (!isValidPath(path)) {
107
+ throw new Error(
108
+ `Invalid derivation path: ${path} (must match m/N'/N'/... \u2014 hardened only)`
109
+ );
110
+ }
111
+ const segments = path.split("/").slice(1).map((s) => parseInt(s.replace("'", ""), 10));
112
+ for (const seg of segments) {
113
+ if (seg >= HARDENED_OFFSET) {
114
+ throw new Error(
115
+ `Derivation path segment out of range: ${seg} (must be < 2\xB3\xB9)`
116
+ );
117
+ }
118
+ }
119
+ const result = segments.reduce(
120
+ (acc, segment) => ckdPriv(acc, segment + HARDENED_OFFSET),
121
+ { key: this.key, chainCode: this.chainCode }
122
+ );
123
+ return new _BLS12377HDKey(result.key, result.chainCode);
124
+ }
125
+ /** Alias for {@link BLS12377HDKey.derive}, kept for HD-key API parity. */
126
+ derivePath(path) {
127
+ return this.derive(path);
128
+ }
129
+ /**
130
+ * Derives the account node at `m/{index}'/0'` relative to this node. Pure
131
+ * and local. Applied to a {@link DERIVATION_PATHS} node, this yields the
132
+ * account at that index.
133
+ *
134
+ * @param index Zero-based account index, below 2^31; hardening is applied
135
+ * internally.
136
+ * @returns The account-level node.
137
+ * @throws If the index is negative, fractional, or 2^31 or greater.
138
+ */
139
+ deriveChild(index) {
140
+ if (!Number.isInteger(index) || index < 0 || index >= HARDENED_OFFSET) {
141
+ throw new Error(
142
+ `Invalid child index: ${index} (must be integer in [0, 2\xB3\xB9))`
143
+ );
144
+ }
145
+ return this.derive(`m/${index}'/0'`);
146
+ }
147
+ };
148
+ function generateMnemonic2(strength = 128) {
149
+ return bip39.generateMnemonic(wordlist, strength);
150
+ }
151
+ function validateMnemonic2(mnemonic) {
152
+ return bip39.validateMnemonic(mnemonic, wordlist);
153
+ }
154
+ function validateWord(word) {
155
+ return wordlist.includes(word);
156
+ }
157
+ function mnemonicToSeed(mnemonic) {
158
+ return bip39.mnemonicToSeedSync(mnemonic);
159
+ }
160
+ function mnemonicToHDKey(mnemonic, options = {}) {
161
+ const { index = 0, derivation = "standard" } = options;
162
+ const seed = mnemonicToSeed(mnemonic);
163
+ return BLS12377HDKey.fromMasterSeed(seed).derivePath(DERIVATION_PATHS[derivation]).deriveChild(index);
164
+ }
165
+
166
+ // src/index.ts
167
+ async function loadNetwork(name) {
168
+ const sdk = await loadSdk(name);
169
+ return buildSdk(name, sdk);
170
+ }
171
+ function buildSdk(initialNetwork, initialSdk) {
172
+ let currentSdk = initialSdk;
173
+ const network = initialNetwork;
174
+ const {
175
+ Account: Account2,
176
+ PrivateKey,
177
+ Signature,
178
+ Address,
179
+ ViewKey,
180
+ AleoNetworkClient,
181
+ RecordScanner,
182
+ RecordCiphertext
183
+ } = initialSdk;
184
+ function mnemonicToAccount(mnemonic, options) {
185
+ const hd = mnemonicToHDKey(mnemonic, options);
186
+ const privateKey = PrivateKey.from_seed_unchecked(hd.key).to_string();
187
+ return { ...privateKeyToAccount(privateKey), source: "mnemonic" };
188
+ }
189
+ function generateMnemonicAccount(options) {
190
+ const mnemonic = generateMnemonic2(options?.strength ?? 128);
191
+ const { strength: _strength, ...derivationOptions } = options ?? {};
192
+ return { mnemonic, account: mnemonicToAccount(mnemonic, derivationOptions) };
193
+ }
194
+ function generateAccount2() {
195
+ const sdkAccount = new Account2();
196
+ return privateKeyToAccount(sdkAccount.privateKey().to_string());
197
+ }
198
+ function decryptRecord(viewKeyString, ciphertext) {
199
+ return ViewKey.from_string(viewKeyString).decrypt(ciphertext);
200
+ }
201
+ function verifySignature(addressString, message, signatureString) {
202
+ const sig = Signature.from_string(signatureString);
203
+ const addr = Address.from_string(addressString);
204
+ return sig.verify(addr, message);
205
+ }
206
+ function createNetworkClient(url) {
207
+ return new AleoNetworkClient(url);
208
+ }
209
+ function createProvingConfig(options) {
210
+ let networkUrl = options.networkUrl;
211
+ let keyProvider = new currentSdk.AleoKeyProvider();
212
+ keyProvider.useCache(true);
213
+ return {
214
+ mode: options.mode,
215
+ url: options.proverUrl,
216
+ buildTransaction: async (txOptions) => {
217
+ const programManager = new currentSdk.ProgramManager(
218
+ networkUrl,
219
+ keyProvider,
220
+ void 0
221
+ );
222
+ if (options.account) {
223
+ const sdkAccount = new currentSdk.Account({ privateKey: options.account.privateKey });
224
+ programManager.setAccount(sdkAccount);
225
+ }
226
+ let resolvedImports;
227
+ if (txOptions.imports && txOptions.imports.length > 0) {
228
+ const programSource = await programManager.networkClient.getProgram(txOptions.programName);
229
+ const staticImports = await programManager.networkClient.getProgramImports(programSource);
230
+ const merged = { ...staticImports };
231
+ for (const name of txOptions.imports) {
232
+ merged[name] = await programManager.networkClient.getProgram(name);
233
+ }
234
+ resolvedImports = merged;
235
+ }
236
+ const tx = await programManager.buildExecutionTransaction({
237
+ programName: txOptions.programName,
238
+ functionName: txOptions.functionName,
239
+ priorityFee: 0,
240
+ privateFee: txOptions.privateFee ?? false,
241
+ inputs: txOptions.inputs,
242
+ ...resolvedImports ? { imports: resolvedImports } : {}
243
+ });
244
+ return JSON.parse(tx.toString());
245
+ },
246
+ buildDeployment: async (deployOptions) => {
247
+ const programManager = new currentSdk.ProgramManager(
248
+ networkUrl,
249
+ keyProvider,
250
+ void 0
251
+ );
252
+ if (options.account) {
253
+ const sdkAccount = new currentSdk.Account({ privateKey: options.account.privateKey });
254
+ programManager.setAccount(sdkAccount);
255
+ }
256
+ const tx = await programManager.buildDeploymentTransaction(
257
+ deployOptions.program,
258
+ 0,
259
+ deployOptions.privateFee ?? false
260
+ );
261
+ return JSON.parse(tx.toString());
262
+ },
263
+ simulate: async (simOptions) => {
264
+ const programManager = new currentSdk.ProgramManager(networkUrl, keyProvider, void 0);
265
+ if (options.account) {
266
+ programManager.setAccount(new currentSdk.Account({ privateKey: options.account.privateKey }));
267
+ }
268
+ const accountViewKey = options.account ? ViewKey.from_string(options.account.viewKey) : void 0;
269
+ const decryptor = accountViewKey ? (ciphertext) => {
270
+ const ct = RecordCiphertext.fromString(ciphertext);
271
+ return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : null;
272
+ } : void 0;
273
+ const authorization = await programManager.buildAuthorization({
274
+ programName: simOptions.programName,
275
+ functionName: simOptions.functionName,
276
+ inputs: simOptions.inputs,
277
+ programSource: simOptions.programSource,
278
+ programImports: simOptions.programImports
279
+ });
280
+ const tx = {
281
+ execution: {
282
+ transitions: authorization.transitions().map((t) => {
283
+ let source = t;
284
+ if (accountViewKey) {
285
+ try {
286
+ source = t.decryptTransition(t.tvk(accountViewKey));
287
+ } catch {
288
+ }
289
+ }
290
+ return JSON.parse(source.toString());
291
+ })
292
+ }
293
+ };
294
+ const { transitions, outputs } = extractTransitions(tx, decryptor);
295
+ return { transitions, outputs };
296
+ },
297
+ execute: async (execOptions) => {
298
+ const programManager = new currentSdk.ProgramManager(networkUrl, keyProvider, void 0);
299
+ if (options.account) {
300
+ programManager.setAccount(new currentSdk.Account({ privateKey: options.account.privateKey }));
301
+ }
302
+ const priorityFee = Number(execOptions.fee) / 1e6;
303
+ const accountViewKey = options.account ? ViewKey.from_string(options.account.viewKey) : void 0;
304
+ const decryptor = accountViewKey ? (ciphertext) => {
305
+ const ct = RecordCiphertext.fromString(ciphertext);
306
+ return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : null;
307
+ } : void 0;
308
+ const buildPollingClient = () => createPublicClient({ transport: http(networkUrl, { network }) });
309
+ if (options.mode === "delegated") {
310
+ if (!options.proverUrl) throw new ConfigurationError("Delegated execution requires proverUrl. Pass proverUrl to createProvingConfig or createAleoClient.");
311
+ let response;
312
+ try {
313
+ const provingRequest = await programManager.provingRequest({
314
+ programName: execOptions.programName,
315
+ programSource: execOptions.programSource,
316
+ programImports: execOptions.programImports,
317
+ functionName: execOptions.functionName,
318
+ inputs: execOptions.inputs,
319
+ priorityFee,
320
+ privateFee: execOptions.privateFee ?? false,
321
+ broadcast: true
322
+ });
323
+ const dpsClient = new AleoNetworkClient(options.proverUrl);
324
+ response = await dpsClient.submitProvingRequest({
325
+ provingRequest,
326
+ url: options.proverUrl,
327
+ apiKey: options.apiKey,
328
+ consumerId: options.consumerId
329
+ });
330
+ } catch (e) {
331
+ if (e instanceof BaseError) throw e;
332
+ throw classifyProvingError(e);
333
+ }
334
+ const txId = response.transaction?.id;
335
+ if (!txId) throw new ConfigurationError("DPS response did not contain a transaction ID \u2014 check prover service configuration.");
336
+ const confirmedTx = await waitForConfirmation(buildPollingClient(), txId, options.confirmationTimeout);
337
+ const { transitions, outputs } = extractTransitions(confirmedTx, decryptor);
338
+ return { transactionId: txId, transitions, outputs };
339
+ } else {
340
+ let tx;
341
+ try {
342
+ tx = await programManager.buildExecutionTransaction({
343
+ programName: execOptions.programName,
344
+ functionName: execOptions.functionName,
345
+ inputs: execOptions.inputs,
346
+ priorityFee,
347
+ privateFee: execOptions.privateFee ?? false,
348
+ program: execOptions.programSource,
349
+ imports: execOptions.programImports
350
+ });
351
+ } catch (e) {
352
+ if (e instanceof BaseError) throw e;
353
+ throw new ProvingError({ message: e instanceof Error ? e.message : String(e), cause: e });
354
+ }
355
+ let txId;
356
+ try {
357
+ const submitClient = new AleoNetworkClient(networkUrl);
358
+ submitClient.setVerboseErrors(false);
359
+ txId = await submitClient.submitTransaction(tx);
360
+ } catch (e) {
361
+ if (e instanceof BaseError) throw e;
362
+ throw classifyBroadcastError(e);
363
+ }
364
+ const confirmedTx = await waitForConfirmation(buildPollingClient(), txId, options.confirmationTimeout);
365
+ const { transitions, outputs } = extractTransitions(confirmedTx, decryptor);
366
+ return { transactionId: txId, transitions, outputs };
367
+ }
368
+ },
369
+ decrypt: async (cipherText) => {
370
+ if (!options.account?.viewKey) {
371
+ throw new Error(
372
+ "decrypt requires an account with a viewKey on the proving config."
373
+ );
374
+ }
375
+ return currentSdk.ViewKey.from_string(options.account.viewKey).decrypt(cipherText);
376
+ },
377
+ switchNetwork: async (newNetwork) => {
378
+ if (newNetwork !== "mainnet" && newNetwork !== "testnet") {
379
+ throw new Error(
380
+ `loadNetwork supports 'mainnet' or 'testnet' (received '${newNetwork}').`
381
+ );
382
+ }
383
+ currentSdk = await loadSdk(newNetwork);
384
+ keyProvider = new currentSdk.AleoKeyProvider();
385
+ keyProvider.useCache(true);
386
+ }
387
+ };
388
+ }
389
+ function toOwnedRecord(raw) {
390
+ const pick = (snake, camel) => raw[snake] ?? raw[camel];
391
+ return {
392
+ blockHeight: pick("block_height", "blockHeight"),
393
+ blockTimestamp: pick("block_timestamp", "blockTimestamp"),
394
+ commitment: raw.commitment,
395
+ functionName: pick("function_name", "functionName"),
396
+ outputIndex: pick("output_index", "outputIndex"),
397
+ owner: raw.owner,
398
+ programName: pick("program_name", "programName"),
399
+ recordCiphertext: pick("record_ciphertext", "recordCiphertext"),
400
+ recordName: pick("record_name", "recordName"),
401
+ sender: raw.sender,
402
+ spent: raw.spent,
403
+ tag: raw.tag,
404
+ transactionId: pick("transaction_id", "transactionId"),
405
+ transitionId: pick("transition_id", "transitionId"),
406
+ transactionIndex: pick("transaction_index", "transactionIndex"),
407
+ transitionIndex: pick("transition_index", "transitionIndex"),
408
+ recordPlaintext: pick("record_plaintext", "recordPlaintext") ?? ""
409
+ };
410
+ }
411
+ function makeRegisterOnce(startBlock) {
412
+ let registration;
413
+ return {
414
+ ensure(scanner, viewKey) {
415
+ if (!registration) {
416
+ registration = (async () => {
417
+ const result = await scanner.registerEncrypted(viewKey, startBlock);
418
+ if (!result.ok) {
419
+ registration = void 0;
420
+ throw new Error(
421
+ `Record scanner registration failed (HTTP ${result.status}): ${result.error?.message ?? "unknown error"}`
422
+ );
423
+ }
424
+ })();
425
+ }
426
+ return registration;
427
+ }
428
+ };
429
+ }
430
+ async function scanOwned(scanner, program, statusFilter, canReMint) {
431
+ const ALWAYS_RETRY = /* @__PURE__ */ new Set([429, 500, 502, 503, 504]);
432
+ const AUTH_RETRY = /* @__PURE__ */ new Set([401, 403]);
433
+ const retryable = (status) => ALWAYS_RETRY.has(status) || canReMint && AUTH_RETRY.has(status);
434
+ const MAX_ATTEMPTS = 4;
435
+ let last = "";
436
+ for (let attempt = 0; attempt < MAX_ATTEMPTS; attempt++) {
437
+ try {
438
+ const result = await scanner.owned({
439
+ unspent: statusFilter !== "spent",
440
+ filter: { programs: [program] }
441
+ });
442
+ if (result.ok) return (result.data ?? []).map((r) => toOwnedRecord(r));
443
+ last = `HTTP ${result.status}: ${result.error?.message ?? "unknown error"}`;
444
+ if (!retryable(result.status)) break;
445
+ } catch (err) {
446
+ last = err instanceof Error ? err.message : String(err);
447
+ }
448
+ if (attempt === MAX_ATTEMPTS - 1) break;
449
+ scanner.setJwtData(void 0);
450
+ await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
451
+ }
452
+ throw new Error(`Record scan failed (${last})`);
453
+ }
454
+ function createRemoteScanner(options) {
455
+ let scannerSdk = { RecordScanner, ViewKey };
456
+ let scanner;
457
+ let viewKey;
458
+ let viewKeyString;
459
+ let registration = makeRegisterOnce(options.startBlock ?? 0);
460
+ function buildScanner() {
461
+ if (!viewKeyString) return;
462
+ viewKey = scannerSdk.ViewKey.from_string(viewKeyString);
463
+ scanner = new scannerSdk.RecordScanner({
464
+ url: options.url,
465
+ consumerId: options.consumerId,
466
+ ...options.apiKey ? { apiKey: options.apiKey } : {},
467
+ viewKeys: [viewKey],
468
+ decryptEnabled: true,
469
+ autoReRegister: true
470
+ });
471
+ registration = makeRegisterOnce(options.startBlock ?? 0);
472
+ }
473
+ return {
474
+ setAccount: (account) => {
475
+ viewKeyString = account.viewKey;
476
+ buildScanner();
477
+ },
478
+ requestRecords: async (params) => {
479
+ if (!scanner) {
480
+ throw new Error("No active account set on record scanner. Call setAccount() first.");
481
+ }
482
+ const activeScanner = scanner;
483
+ const activeViewKey = viewKey;
484
+ const activeRegistration = registration;
485
+ await activeRegistration.ensure(activeScanner, activeViewKey);
486
+ return scanOwned(activeScanner, params.program, params.statusFilter, !!options.apiKey);
487
+ },
488
+ switchNetwork: async (newNetwork) => {
489
+ if (newNetwork !== "mainnet" && newNetwork !== "testnet") {
490
+ throw new Error(
491
+ `Record scanning supports 'mainnet' or 'testnet' (received '${newNetwork}').`
492
+ );
493
+ }
494
+ scannerSdk = await loadSdk(newNetwork);
495
+ buildScanner();
496
+ }
497
+ };
498
+ }
499
+ function createStandaloneScanner(options) {
500
+ const viewKey = ViewKey.from_string(options.viewKey);
501
+ const scanner = new RecordScanner({
502
+ url: options.url,
503
+ consumerId: options.consumerId,
504
+ ...options.apiKey ? { apiKey: options.apiKey } : {},
505
+ viewKeys: [viewKey],
506
+ decryptEnabled: true,
507
+ autoReRegister: true
508
+ });
509
+ const registration = makeRegisterOnce(options.startBlock ?? 0);
510
+ return {
511
+ requestRecords: async (params) => {
512
+ await registration.ensure(scanner, viewKey);
513
+ return scanOwned(scanner, params.program, params.statusFilter, !!options.apiKey);
514
+ }
515
+ };
516
+ }
517
+ function createAleoClient(options) {
518
+ const account = privateKeyToAccount(options.privateKey);
519
+ const transport = http(options.networkUrl, { network });
520
+ const proving = createProvingConfig({
521
+ mode: options.provingMode ?? "delegated",
522
+ networkUrl: options.networkUrl,
523
+ proverUrl: options.proverUrl,
524
+ apiKey: options.apiKey,
525
+ consumerId: options.consumerId,
526
+ account
527
+ });
528
+ const publicClient = createPublicClient({ transport });
529
+ if (options.records) {
530
+ options.records.setAccount({ viewKey: account.viewKey });
531
+ }
532
+ const walletClient = createWalletClient({
533
+ account,
534
+ transport,
535
+ proving,
536
+ ...options.records ? { recordProvider: options.records } : {}
537
+ });
538
+ return { publicClient, walletClient, account };
539
+ }
540
+ return {
541
+ network,
542
+ privateKeyToAccount,
543
+ mnemonicToAccount,
544
+ generateMnemonicAccount,
545
+ generateAccount: generateAccount2,
546
+ decryptRecord,
547
+ verifySignature,
548
+ createNetworkClient,
549
+ createProvingConfig,
550
+ createRemoteScanner,
551
+ createStandaloneScanner,
552
+ createAleoClient
553
+ };
554
+ }
555
+ var DEVNODE_CONSENSUS_HEIGHTS = "0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16";
556
+ function privateKeyToAccount(privateKey) {
557
+ const sdkAccount = new Account({ privateKey });
558
+ const address = sdkAccount.address().to_string();
559
+ const viewKey = sdkAccount.viewKey().to_string();
560
+ const signFn = async (message) => {
561
+ const sig = sdkAccount.sign(message);
562
+ return new TextEncoder().encode(sig.to_string());
563
+ };
564
+ return {
565
+ type: "local",
566
+ source: "privateKey",
567
+ address,
568
+ privateKey,
569
+ viewKey,
570
+ sign: signFn,
571
+ signMessage: signFn
572
+ };
573
+ }
574
+ function generateAccount() {
575
+ const sdkAccount = new Account();
576
+ return privateKeyToAccount(sdkAccount.privateKey().to_string());
577
+ }
578
+ function createDevnodeClient(options) {
579
+ const url = `http://${options?.socketAddr ?? DEVNODE_ADDR}`;
580
+ const account = privateKeyToAccount(options?.privateKey ?? DEVNODE_PRIVATE_KEY);
581
+ const sdkAccount = new Account({ privateKey: account.privateKey });
582
+ const transport = http(url, { network: "testnet" });
583
+ const keyProvider = new AleoKeyProvider();
584
+ keyProvider.useCache(true);
585
+ getOrInitConsensusVersionTestHeights(DEVNODE_CONSENSUS_HEIGHTS);
586
+ const publicClient = createPublicClient({ transport });
587
+ const buildExecutionTx = async (opts) => {
588
+ const programManager = new ProgramManager(url, keyProvider, void 0);
589
+ programManager.setAccount(sdkAccount);
590
+ return programManager.buildDevnodeExecutionTransaction({
591
+ programName: opts.programName,
592
+ functionName: opts.functionName,
593
+ priorityFee: 0,
594
+ privateFee: opts.privateFee ?? false,
595
+ inputs: opts.inputs,
596
+ ...opts.imports ? { imports: opts.imports } : {}
597
+ });
598
+ };
599
+ const proving = {
600
+ mode: "devnode",
601
+ buildDeployment: async (deployOptions) => {
602
+ const programManager = new ProgramManager(url, keyProvider, void 0);
603
+ programManager.setAccount(sdkAccount);
604
+ const tx = await programManager.buildDevnodeDeploymentTransaction({
605
+ program: deployOptions.program,
606
+ priorityFee: 0,
607
+ privateFee: deployOptions.privateFee ?? false
608
+ });
609
+ return JSON.parse(tx.toString());
610
+ },
611
+ buildTransaction: async (txOptions) => {
612
+ let imports;
613
+ if (txOptions.imports && txOptions.imports.length > 0) {
614
+ const networkClient = new ProgramManager(url, keyProvider, void 0).networkClient;
615
+ imports = {};
616
+ const queue = [...txOptions.imports];
617
+ const seen = /* @__PURE__ */ new Set();
618
+ while (queue.length > 0) {
619
+ const name = queue.shift();
620
+ if (seen.has(name)) continue;
621
+ seen.add(name);
622
+ const source = await networkClient.getProgram(name);
623
+ imports[name] = source;
624
+ const importNames = Program.fromString(source).getImports();
625
+ for (const dep of importNames) {
626
+ if (dep && !seen.has(dep)) queue.push(dep);
627
+ }
628
+ }
629
+ }
630
+ const tx = await buildExecutionTx({
631
+ programName: txOptions.programName,
632
+ functionName: txOptions.functionName,
633
+ inputs: txOptions.inputs,
634
+ privateFee: txOptions.privateFee,
635
+ imports
636
+ });
637
+ return JSON.parse(tx.toString());
638
+ },
639
+ execute: async (execOptions) => {
640
+ const tx = await buildExecutionTx({
641
+ programName: execOptions.programName,
642
+ functionName: execOptions.functionName,
643
+ inputs: execOptions.inputs,
644
+ privateFee: execOptions.privateFee,
645
+ imports: execOptions.programImports
646
+ });
647
+ const txId = await publicClient.request({
648
+ method: "sendTransaction",
649
+ params: { transaction: tx.toString() }
650
+ });
651
+ const confirmedTx = await waitForConfirmation(publicClient, txId);
652
+ const accountViewKey = StaticViewKey.from_string(account.viewKey);
653
+ const decryptor = (ciphertext) => {
654
+ const ct = StaticRecordCiphertext.fromString(ciphertext);
655
+ return ct.isOwner(accountViewKey) ? ct.decrypt(accountViewKey).toString() : ciphertext;
656
+ };
657
+ const { transitions, outputs } = extractTransitions(confirmedTx, decryptor);
658
+ return { transactionId: txId, transitions, outputs };
659
+ }
660
+ };
661
+ const walletClient = createWalletClient({ account, transport, proving });
662
+ return { publicClient, walletClient, account };
663
+ }
664
+ export {
665
+ BLS12377HDKey,
666
+ DEVNODE_ADDR,
667
+ DEVNODE_PRIVATE_KEY,
668
+ LEGACY_PATH,
669
+ STANDARD_PATH,
670
+ createDevnodeClient,
671
+ generateAccount,
672
+ generateMnemonic2 as generateMnemonic,
673
+ loadNetwork,
674
+ mnemonicToHDKey,
675
+ mnemonicToSeed,
676
+ validateMnemonic2 as validateMnemonic,
677
+ validateWord
678
+ };
679
+ //# sourceMappingURL=index.js.map
@@ -0,0 +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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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 ADDED
@@ -0,0 +1,47 @@
1
+ {
2
+ "name": "@provablehq/veil-aleo-sdk",
3
+ "version": "0.4.0",
4
+ "description": "Local signing and proving for the Veil Aleo SDK, backed by the Provable SDK.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/ProvableHQ/veil.git",
9
+ "directory": "packages/provable-sdk"
10
+ },
11
+ "homepage": "https://github.com/ProvableHQ/veil#readme",
12
+ "type": "module",
13
+ "main": "dist/index.js",
14
+ "types": "dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ }
20
+ },
21
+ "sideEffects": false,
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "engines": {
26
+ "node": ">=18"
27
+ },
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
31
+ "peerDependencies": {
32
+ "@provablehq/veil-core": "0.4.0",
33
+ "@provablehq/veil-aleo-devnode": "0.4.0"
34
+ },
35
+ "dependencies": {
36
+ "@noble/hashes": "^1.7.2",
37
+ "@provablehq/sdk": "^0.11.3",
38
+ "@scure/bip39": "^1.4.0"
39
+ },
40
+ "devDependencies": {
41
+ "@provablehq/veil-leo": "0.4.0"
42
+ },
43
+ "scripts": {
44
+ "build": "tsup",
45
+ "typecheck": "tsc --noEmit"
46
+ }
47
+ }