miden-client-web 0.7.2

Web Client library that facilitates interaction with the Miden rollup
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# @demox-labs/miden-sdk
The @demox-labs/miden-sdk is a toolkit designed for interacting with the Miden virtual machine. It offers essential tools and functionalities for developers aiming to integrate or utilize Miden VM capabilities in their applications.

## Installation
To install the package via npm, run the following command:

```javascript
npm i @demox-labs/miden-sdk
```

For yarn:
```javascript
yarn add @demox-labs/miden-sdk
```

## Usage

```typescript
import { WebClient } from "@demox-labs/miden-sdk";

const webClient = new WebClient();
await webClient.create_client();

// Use WebClient to create accounts, notes, transactions, etc.
// This will create a mutable, private account and store it in IndexedDB
const accountId = await webClient.new_wallet("Private", true);
```

## Examples
### The WebClient
The WebClient is your gateway to creating and interacting with anything miden vm related.
Example:
```typescript
// Creates a new WebClient instance which can then be configured after
const webClient = new WebClient();

// Creates the internal client of a previously instantiated WebClient.
// Can provide `node_url` as an optional parameter. Defaults to the tesnet RPC URL.
await webClient.create_client();
```
Example specifying a specific node URL:
```typescript
const webClient = new WebClient();

let remote_node_url = "http://18.203.155.106:57291"
await webClient.create_client(remote_node_url);
```

### Accounts
You can use the WebClient to create and retrieve account information.
```typescript
const webClient = new WebClient();
await webClient.create_client();

/**
 * Creates a new wallet account.
 * 
 * @param storage_mode String. Either "Private" or "Public".
 * @param mutable Boolean. Whether the wallet code is mutable or not
 * 
 * Returns: Wallet Id
 */
const walletId = await webClient.new_wallet("Private", true);

/**
 * Creates a new faucet account.
 * 
 * @param storage_mode String. Either "Private" or "Public".
 * @param non_fungible Boolean. Whether the faucet is non_fungible or not. NOTE: Non-fungible faucets are not supported yet
 * @param token_symbol String. Token symbol of the token the faucet creates
 * @param decimals String. Decimal precision of token.
 * @param max_supply String. Maximum token supply
 */ 
const faucetId = await webClient.new_faucet("Private", true, "TOK", 6, 1_000_000)

/**
 * Returns all accounts. Both wallets and faucets. Returns the following object per account
 * {
 *   id: string
 *   nonce: string
 *   vault_root: string
 *   storage_root: string
 *   code_root: string
 * }/
const accounts = await webClient.get_accounts()
console.log(accounts[0].id) // Prints account id of first account retrieved as hex value

// Gets a single account by id
const account = await webClient.get_account("0x9258fec00ad6d9bc");

// Imports an account. This example adds a simple button to an HTML page, creates a listener for an account file selection, serializes that file into bytes, then calls the client to import it. 
<label for="accountFileInput" class="custom-file-upload">
    Choose Account File
</label>
<input type="file" id="accountFileInput" style="display: none;">
document.getElementById('accountFileInput').addEventListener('change', function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();

        reader.onload = async function(e) {
            let webClient = await createMidenWebClient();
            const arrayBuffer = e.target.result;
            const byteArray = new Uint8Array(arrayBuffer);

            await webClient.importAccount(accountAsBytes);
        };

        reader.readAsArrayBuffer(file);
    }
});
```

### Transactions
You can use the WebClient to facilitate transactions between accounts.

Let's mint some tokens for our wallet from our faucet:
```typescript
const webClient = new WebClient();
await webClient.create_client();
const walletId = await webClient.new_wallet("Private", true);
const faucetId = await webClient.new_faucet("Private", true, "TOK", 6, 1_000_000);

// Syncs web client with node state.
await webClient.sync_state();
// Caches faucet account auth. A workaround to allow for synchronicity in the transaction flow.
await webClient.fetch_and_cache_account_auth_by_pub_key(faucetId);

/**
 * Mints 10_000 tokens for the previously created wallet via a Private Note and returns a transaction the following result object:
 * {
 *   transaction_id: string
 *   created_note_ids: string[]
 * }
 */
const newTxnResult = await webClient.new_mint_transaction(walletId, faucetId, "Private", 10_000);
console.log(newTxnResult.created_note_ids); // Prints the list of note ids created from this transaction

// Sync state again
await webClient.sync_state();

/**
 * Gets all of your existing transactions
 * Returns string[] of transaction ids
 */
const transactions = await webClient.get_transactions()
```

### Notes
You can use the WebClient to query for existing notes, export notes, and import notes

Here is an example of how to import a note from a file (generated, say, from the faucet at https://testnet.miden.io/ for a given account). This code exposes a simple button on an HTML page for a user to select a file. A listener is setup to capture this event, serialize the note file, and import it.
```typescript
let webClient = await createMidenWebClient();
let walletAccount = await webClient.new_wallet("Private", true); // The second argument defines that the wallet has mutable code.
console.log(walletAccount); // Prints the id that can be used to plug in to the deployed Miden faucet.

<label for="noteFileInput" class="custom-file-upload">
    Choose Note File
</label>
<input type="file" id="noteFileInput" style="display: none;">
document.getElementById('noteFileInput').addEventListener('change', async function(event) {
    const file = event.target.files[0];
    if (file) {
        const reader = new FileReader();

        reader.onload = async function(e) {
            let webClient = await createMidenWebClient();

            const arrayBuffer = e.target.result;
            const byteArray = new Uint8Array(arrayBuffer);

            await webClient.import_note(byteArray, true); // imports the file generated from the faucet previously
        };

        reader.readAsArrayBuffer(file);
    }
});
```

Example of exporting a note:
```typescript
console.log("testExportNote started");

let webClient = await createMidenWebClient();

// Create a faucet and mint a mint transaction
let faucetId = await createNewFaucet(webClient, "Private", false, "DEN", "10", "1000000");
await syncState(webClient);
await new Promise(r => setTimeout(r, 20000)); // Artificial delays to ensure sync is processed on remote node before continuing 

await webClient.fetch_and_cache_account_auth_by_pub_key(faucetId);

let mintTransactionResult = await createNewMintTransaction(
    webClient,
    "0x9186b96f559e852f", // Insert target account id here
    faucetId,
    "Private",
    "1000"
);
await new Promise(r => setTimeout(r, 20000));
await syncState(webClient);

// Take the note created from the mint transaction, serialize it, and download it via the browser immediately
let result = await exportNote(webClient, mintTransactionResult.created_note_ids[0]);

const blob = new Blob([result], {type: 'application/octet-stream'});

// Create a URL for the Blob
const url = URL.createObjectURL(blob);

// Create a temporary anchor element
const a = document.createElement('a');
a.href = url;
a.download = 'exportNoteTest.mno'; // Specify the file name

// Append the anchor to the document
document.body.appendChild(a);

// Programmatically click the anchor to trigger the download
a.click();

// Remove the anchor from the document
document.body.removeChild(a);

// Revoke the object URL to free up resources
URL.revokeObjectURL(url);
```

Get All Input Notes Example:
```typescript
let webClient = await createMidenWebClient();

/**
 * get_input_notes takes a filter to retrieve notes based on a specific status. The options are the following:
 *  "All",
 *  "Consumed",
 *  "Committed",
 *  "Expected",
 *  "Processing",
 *  "List",
 *  "Unique",
 *  "Nullifiers",
 *  "Unverified",
 */
const notes = await webClient.get_input_notes("All")
```

## API Reference

```typescript
/**
 * @returns {Promise<SerializedAccountHeader>}
 * 
 * Example of returned object:
 * {
 *   id: string,
 *   nonce: string,
 *   vault_root: string,
 *   storage_root: string,
 *   code_root: string
 * }
 */
get_accounts(): Promise<SerializedAccountHeader>;

/**
 * @param {string} account_id
 * @returns {Promise<any>}
 */
get_account(account_id: string): Promise<any>;

/**
 * @param {any} pub_key_bytes
 * @returns {any}
 */
get_account_auth_by_pub_key(pub_key_bytes: any): any;

/**
 * @param {string} account_id
 * @returns {Promise<any>}
 */
fetch_and_cache_account_auth_by_pub_key(account_id: string): Promise<any>;

/**
 * @param {string} note_id
 * @param {string} export_type
 * @returns {Promise<any>}
 * 
 * export_type can be any of the following:
 * 
 * "Full"
 * "Partial"
 * "Id"
 */
export_note(note_id: string, export_type: string): Promise<any>;

/**
 * @param {any} account_bytes
 * @returns created account id as {Promise<string>}
 * 
 */
import_account(account_bytes: any): Promise<string>;

/**
 * @param {string} note_bytes
 * @param {boolean} verify
 * @returns {Promise<any>}
 */
import_note(note_bytes: string, verify: boolean): Promise<any>;

/**
 * @param {string} storage_mode
 * @param {boolean} mutable
 * @returns {Promise<any>}
 */
new_wallet(storage_mode: string, mutable: boolean): Promise<any>;

/**
 * @param {string} storage_mode
 * @param {boolean} non_fungible
 * @param {string} token_symbol
 * @param {string} decimals
 * @param {string} max_supply
 * @returns {Promise<any>}
 */
new_faucet(storage_mode: string, non_fungible: boolean, token_symbol: string, decimals: string, max_supply: string): Promise<any>;

/**
 * @param {string} target_account_id
 * @param {string} faucet_id
 * @param {string} note_type
 * @param {string} amount
 * @returns {Promise<NewTransactionResult>}
 * 
 * Example of a NewTransactionResult object:
 * {
 *   transaction_id: string,
 *   created_note_ids: string[]
 * }
 */
new_mint_transaction(target_account_id: string, faucet_id: string, note_type: string, amount: string): Promise<NewTransactionResult>;

/**
 * @param {string} sender_account_id
 * @param {string} target_account_id
 * @param {string} faucet_id
 * @param {string} note_type
 * @param {string} amount
 * @param {string | undefined} [recall_height]
 * @returns {Promise<NewTransactionResult>}
 * 
 * Example of a NewTransactionResult object:
 * {
 *   transaction_id: string,
 *   created_note_ids: string[]
 * }
 */
new_send_transaction(sender_account_id: string, target_account_id: string, faucet_id: string, note_type: string, amount: string, recall_height?: string): Promise<NewTransactionResult>;

/**
 * @param {string} account_id
 * @param {(string)[]} list_of_notes
 * @returns {Promise<NewTransactionResult>}
 * 
 * Example of a NewTransactionResult object:
 * {
 *   transaction_id: string,
 *   created_note_ids: string[]
 * }
 */
new_consume_transaction(account_id: string, list_of_notes: (string)[]): Promise<NewTransactionResult>;

/**
 * @param {string} sender_account_id
 * @param {string} offered_asset_faucet_id
 * @param {string} offered_asset_amount
 * @param {string} requested_asset_faucet_id
 * @param {string} requested_asset_amount
 * @param {string} note_type
 * @returns {Promise<NewSwapTransactionResult>}
 * 
 * Example of a NewSwapTransactionResult object:
 * {
 *   transaction_id: string,
 *   expected_output_note_ids: string[],
 *.  expected_partial_note_ids: string[],
 *   payback_note_tag: string,
 * }
 */
new_swap_transaction(sender_account_id: string, offered_asset_faucet_id: string, offered_asset_amount: string, requested_asset_faucet_id: string, requested_asset_amount: string, note_type: string): Promise<NewSwapTransactionResult>;

/**
 * @param {any} filter
 * @returns {Promise<any>}
 * 
 * Examples of valid filters:
 *  "All",
 *  "Consumed",
 *  "Committed",
 *  "Expected",
 *  "Processing",
 *  "List",
 *  "Unique",
 *  "Nullifiers",
 *  "Unverified",
 */
get_input_notes(filter: any): Promise<any>;

/**
 * @param {string} note_id
 * @returns note id as {Promise<any>}
 */
get_input_note(note_id: string): Promise<any>;

/**
 * @param {any} filter
 * @returns {Promise<any>}
 * 
 * Examples of valid filters:
 *  "All",
 *  "Consumed",
 *  "Committed",
 *  "Expected",
 *  "Processing",
 *  "List",
 *  "Unique",
 *  "Nullifiers",
 *  "Unverified",
 */
get_output_notes(filter: any): Promise<any>;

/**
 * @param {string} note_id
 * @returns {Promise<any>}
 */
get_output_note(note_id: string): Promise<any>;

/**
 * @returns block number of latest block you synced to {Promise<any>}
 */
sync_state(): Promise<any>;

/**
 * @returns list of existing transaction ids {Promise<string[]>}
 */
get_transactions(): Promise<string[]>;

/**
 * @param {string} tag
 * @returns {Promise<any>}
 */
add_tag(tag: string): Promise<any>;

/**
 */
constructor();

/**
 * @param {string | undefined} [node_url]
 * @returns {Promise<any>}
 */
create_client(node_url?: string): Promise<any>;
```

## License

This project is licensed under the MIT License - see the LICENSE file for details.