miden-client 0.17.0-rc.2

Client library that facilitates interaction with the Miden network
Documentation
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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
use alloc::boxed::Box;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;

use miden_protocol::account::AccountId;
use miden_protocol::crypto::merkle::MerkleError;
pub use miden_protocol::errors::{
    AccountError,
    AccountIdError,
    AccountPatchError,
    AssetError,
    NetworkIdError,
};
use miden_protocol::errors::{
    NoteError,
    PartialBlockchainError,
    ProposedBatchError,
    ProvenBatchError,
    TransactionInputError,
};
use miden_protocol::note::NoteId;
use miden_protocol::transaction::{ProvenTransaction, TransactionId, TransactionInputs};
use miden_protocol::{MastForestScriptError, Word};
// RE-EXPORTS
// ================================================================================================
pub use miden_standards::errors::CodeBuilderError;
use miden_standards::tx_script::SendNotesTransactionScriptError;
use miden_tx::utils::HexParseError;
use miden_tx::utils::serde::DeserializationError;
pub use miden_tx::{AuthenticationError, NoteCheckerError, TransactionExecutorError};
use miden_tx::{DataStoreError, TransactionProverError};
use thiserror::Error;

use crate::note::NoteScreenerError;
use crate::note_transport::NoteTransportError;
use crate::rpc::{EndpointError, RegisterAccountError, RpcError};
use crate::store::{NoteRecordError, StoreError};
use crate::transaction::{
    BatchBuilderError,
    ChainAnchorError,
    ProvenBatchSubmission,
    TransactionRequestError,
    TransactionStoreUpdateError,
};

// ACTIONABLE HINTS
// ================================================================================================

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ErrorHint {
    message: String,
    docs_url: Option<&'static str>,
}

impl ErrorHint {
    pub fn into_help_message(self) -> String {
        self.to_string()
    }
}

impl fmt::Display for ErrorHint {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.docs_url {
            Some(url) => write!(f, "{} See docs: {}", self.message, url),
            None => f.write_str(self.message.as_str()),
        }
    }
}

// TODO: This is mostly illustrative but we could add a URL with fragemtn identifiers for each error
const TROUBLESHOOTING_DOC: &str =
    "https://docs.miden.xyz/builder/tools/clients/rust-client/cli/cli-troubleshooting";

// CLIENT ERROR
// ================================================================================================

/// Errors generated by the client.
#[derive(Debug, Error)]
pub enum ClientError {
    #[error("address {0} is already being tracked")]
    AddressAlreadyTracked(String),
    #[error("account with id {0} is already being tracked")]
    AccountAlreadyTracked(AccountId),
    #[error("account error")]
    AccountError(#[from] AccountError),
    #[error("account patch error")]
    AccountPatchError(#[from] AccountPatchError),
    #[error("account {0} is locked because the local state may be out of date with the network")]
    AccountLocked(AccountId),
    #[error(
        "account import failed: the on-chain account commitment ({0}) does not match the commitment of the account being imported"
    )]
    AccountCommitmentMismatch(Word),
    #[error("account {0} is private and its details cannot be retrieved from the network")]
    AccountIsPrivate(AccountId),
    #[error("account {0} is watched and cannot be used to execute transactions")]
    AccountIsWatched(AccountId),
    #[error("account {0} is a network account and does not need an invitation code")]
    AccountIsNetworkAccount(AccountId),
    #[error("account {0} is already allowed on the network and does not need an invitation code")]
    AccountAlreadyAllowed(AccountId),
    #[error("account {0} is already deployed and does not need an invitation code")]
    AccountIsNotNew(AccountId),
    #[error(
        "account {0} is already tracked with a different ClientAccountType; switching between Native and Watched is not supported"
    )]
    AccountWatchedMismatch(AccountId),
    #[error("account with id {0} not found on the network")]
    AccountNotFoundOnChain(AccountId),
    #[error("account {0} is not registered on the network allowlist")]
    AccountNotAllowlisted(AccountId),
    #[error(
        "cannot import account: the local account nonce is higher than the imported one, meaning the local state is newer"
    )]
    AccountNonceTooLow,
    #[error("asset error")]
    AssetError(#[from] AssetError),
    #[error("account data wasn't found for account id {0}")]
    AccountDataNotFound(AccountId),
    #[error(transparent)]
    BatchBuilder(#[from] BatchBuilderError),
    #[error("chain anchor error")]
    ChainAnchorError(#[from] ChainAnchorError),
    #[error("data store error")]
    DataStoreError(#[from] DataStoreError),
    #[error("failed to construct the partial blockchain")]
    PartialBlockchainError(#[from] PartialBlockchainError),
    #[error("failed to build proposed batch")]
    ProposedBatchError(#[from] ProposedBatchError),
    #[error("failed to prove batch")]
    ProvenBatchError(#[from] ProvenBatchError),
    #[error("failed to deserialize data")]
    DataDeserializationError(#[from] DeserializationError),
    #[error(
        "cannot recover consumed note {0}: its nullifier has no position in the sync's transaction execution order"
    )]
    MissingConsumedNoteOrder(NoteId),
    #[error(
        "cannot continue iterating consumed notes: the store returned the note with details commitment {0}, which carries no consumption position"
    )]
    MissingNoteConsumptionPosition(Word),
    #[error("note with id {0} not found on chain")]
    NoteNotFoundOnChain(NoteId),
    #[error("failed to parse hex string")]
    HexParseError(#[from] HexParseError),
    #[error(
        "the chain Merkle Mountain Range (MMR) forest value exceeds the supported range (must fit in a u32)"
    )]
    InvalidPartialMmrForest,
    #[error("chain validation error: {0}")]
    ChainValidationError(String),
    #[error(
        "cannot track a new account without its seed; the seed is required to validate the account ID's correctness"
    )]
    AddNewAccountWithoutSeed,
    #[error("merkle proof error")]
    MerkleError(#[from] MerkleError),
    #[error(
        "transaction output mismatch: expected output notes with recipient digests {0:?} were not produced by the transaction"
    )]
    MissingOutputRecipients(Vec<Word>),
    #[error("note error")]
    NoteError(#[from] NoteError),
    #[error("note consumption check failed")]
    NoteCheckerError(#[from] NoteCheckerError),
    #[error("note import error: {0}")]
    NoteImportError(String),
    #[error("failed to convert note record")]
    NoteRecordConversionError(#[from] NoteRecordError),
    #[error("note transport error")]
    NoteTransportError(#[from] NoteTransportError),
    #[error(
        "account {0} has no notes available to consume; sync the client or check that notes targeting this account exist"
    )]
    NoConsumableNoteForAccount(AccountId),
    #[error("RPC error")]
    RpcError(#[from] RpcError),
    #[error(
        "no transaction encryption key is available; the validator set's key must be cached in the store before transaction inputs can be sealed for submission"
    )]
    MissingTransactionEncryptionKey,
    #[error(
        "transaction failed a recency check: {0} — the reference block may be too old; try syncing and resubmitting"
    )]
    RecencyConditionError(&'static str),
    #[error("note relevance check failed")]
    NoteScreenerError(#[from] NoteScreenerError),
    #[error("storage error")]
    StoreError(#[from] StoreError),
    #[error("transaction execution failed")]
    TransactionExecutorError(#[from] TransactionExecutorError),
    #[error("invalid transaction input")]
    TransactionInputError(#[source] TransactionInputError),
    #[error("transaction proving failed")]
    TransactionProvingError(#[from] TransactionProverError),
    #[error("prover returned a proof of transaction {returned}, but {requested} was requested")]
    MismatchedProvenTransaction {
        requested: TransactionId,
        returned: TransactionId,
    },
    #[error("invalid transaction request")]
    TransactionRequestError(#[from] TransactionRequestError),
    #[error("failed to build the send-notes transaction script")]
    SendNotesTransactionScriptError(#[from] SendNotesTransactionScriptError),
    #[error("mast forest script error")]
    MastForestScriptError(#[source] MastForestScriptError),
    #[error("client initialization error: {0}")]
    ClientInitializationError(String),
    #[error("expected full account data for account {0}, but only partial data is available")]
    AccountRecordNotFull(AccountId),
    #[error("expected partial account data for account {0}, but full data was found")]
    AccountRecordNotPartial(AccountId),
    #[error("failed to register NTX note script with root {script_root:?}")]
    NtxScriptRegistrationFailed {
        script_root: Word,
        #[source]
        source: RpcError,
    },
    #[error(
        "transaction {} was accepted into the node's mempool at block {} but the local store \
         update failed. The pending store update is attached and can be re-applied later via \
         `apply_transaction_update`. Resubmitting the same transaction will be rejected if the \
         original is still in the mempool or has been finalized in a block, because the \
         account (and network) state has already been mutated by the accepted copy.",
        pending_update.executed_transaction().id(),
        pending_update.submission_height()
    )]
    ApplyTransactionAfterSubmitFailed {
        pending_update: Box<crate::transaction::TransactionStoreUpdate>,
        #[source]
        source: Box<ClientError>,
    },
    #[error(
        "submission of transaction {} came back without a definite outcome, so the node may or \
         may not have accepted it; nothing was recorded locally",
        transaction.id()
    )]
    SubmissionOutcomeUnknown {
        /// The transaction as submitted. Pass it back to
        /// [`Client::submit_proven_transaction`](crate::Client::submit_proven_transaction)
        /// alongside `transaction_inputs` to retry, or track `transaction.id()` instead.
        transaction: Box<ProvenTransaction>,
        /// The inputs the submission sealed. Required to retry: they cannot be recovered from the
        /// proven transaction, which only commits to them.
        transaction_inputs: Box<TransactionInputs>,
        #[source]
        source: RpcError,
    },
    /// Generic carrier for feature-specific errors raised by an observer or domain module. Keeps
    /// `ClientError` free of per-feature variants; each feature provides its own
    /// `From<MyFeatureError> for ClientError` returning `Observer(Box::new(err))`.
    #[error(transparent)]
    Observer(Box<dyn core::error::Error + Send + Sync + 'static>),
    #[error("expected note blocks to be screened before state sync update is built")]
    UnscreenedNoteBlocks,
}

// OBSERVER FAN-OUT
// ================================================================================================

/// Logs a non-fatal observer failure without propagating it, so one observer can't abort the others
/// or the surrounding sync/transaction step. Shared by the `NoteObserver` and `TransactionObserver`
/// fan-out loops.
pub(crate) fn log_observer_failure(
    observer: &'static str,
    op: &str,
    result: Result<(), ClientError>,
) {
    if let Err(err) = result {
        tracing::warn!(observer, error = ?err, "{} failed; continuing with remaining observers", op);
    }
}

// CONVERSIONS
// ================================================================================================

impl From<ClientError> for String {
    fn from(err: ClientError) -> String {
        err.to_string()
    }
}

impl From<TransactionStoreUpdateError> for ClientError {
    fn from(err: TransactionStoreUpdateError) -> Self {
        match err {
            TransactionStoreUpdateError::Store(e) => ClientError::StoreError(e),
            TransactionStoreUpdateError::NoteScreener(e) => ClientError::NoteScreenerError(e),
            TransactionStoreUpdateError::NoteRecord(e) => ClientError::NoteRecordConversionError(e),
        }
    }
}

impl From<&ClientError> for Option<ErrorHint> {
    fn from(err: &ClientError) -> Self {
        match err {
            ClientError::MissingOutputRecipients(recipients) => {
                Some(missing_recipient_hint(recipients))
            },
            ClientError::TransactionRequestError(inner) => inner.into(),
            ClientError::TransactionExecutorError(inner) => transaction_executor_hint(inner),
            ClientError::NoteNotFoundOnChain(note_id) => Some(ErrorHint {
                message: format!(
                    "Note {note_id} has not been found on chain. Double-check the note ID, ensure it has been committed, and run `miden-client sync` before retrying."
                ),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            ClientError::AccountLocked(account_id) => Some(ErrorHint {
                message: format!(
                    "Account {account_id} is locked because the client may be missing its latest \
                     state. This can happen when the account is shared and another client executed \
                     a transaction. Run `sync` to fetch the latest state from the network."
                ),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            ClientError::AccountNotAllowlisted(account_id) => {
                Some(account_not_allowlisted_hint(*account_id))
            },
            ClientError::AccountNonceTooLow => Some(ErrorHint {
                message: "The account you are trying to import has an older nonce than the version \
                          already tracked locally. Run `sync` to ensure your local state is current, \
                          or re-export the account from a more up-to-date source.".to_string(),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            ClientError::NoConsumableNoteForAccount(account_id) => Some(ErrorHint {
                message: format!(
                    "No notes were found that account {account_id} can consume. \
                     Run `sync` to fetch the latest notes from the network, \
                     and verify that notes targeting this account have been committed on chain."
                ),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            ClientError::AccountIsNetworkAccount(account_id)
            | ClientError::AccountAlreadyAllowed(account_id)
            | ClientError::AccountIsNotNew(account_id) => {
                Some(unneeded_invitation_code_hint(err, *account_id))
            },
            ClientError::RpcError(inner) => rpc_hint(inner),
            ClientError::AddNewAccountWithoutSeed => Some(ErrorHint {
                message: "New accounts require a seed to derive their initial state. \
                          Use `Client::new_account()` which generates the seed automatically, \
                          or provide the seed when importing.".to_string(),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            ClientError::ApplyTransactionAfterSubmitFailed { pending_update, .. } => {
                let tx_id = pending_update.executed_transaction().id();
                let submission_height = pending_update.submission_height();
                Some(ErrorHint {
                    message: format!(
                        "Transaction {tx_id} was accepted into the node's mempool at block \
                         {submission_height} but the local store update failed. The pending \
                         update is attached to this error as `pending_update`; you can re-apply \
                         it later via `Client::apply_transaction_update`. Do NOT resubmit the \
                         same transaction: if the original is still in the mempool or has been \
                         finalized in a block, the account (and network) state has already been \
                         mutated by the accepted copy, so the node will reject the retry."
                    ),
                    docs_url: Some(TROUBLESHOOTING_DOC),
                })
            },
            ClientError::SubmissionOutcomeUnknown { transaction, .. } => {
                let tx_id = transaction.id();
                Some(ErrorHint {
                    message: format!(
                        "Do not build and submit a replacement for {tx_id}: that would be a \
                         different transaction, and it would be rejected as a conflict if the \
                         original landed. Either retry with the `transaction` and \
                         `transaction_inputs` attached to this error, whose id is fixed so it \
                         cannot double spend, or keep syncing and check `get_transactions` for \
                         {tx_id} until it commits or expires."
                    ),
                    docs_url: Some(TROUBLESHOOTING_DOC),
                })
            },
            ClientError::BatchBuilder(BatchBuilderError::BatchSubmissionOutcomeUnknown {
                submission,
                ..
            }) => Some(batch_submission_outcome_unknown_hint(submission)),
            _ => None,
        }
    }
}

impl ClientError {
    pub fn error_hint(&self) -> Option<ErrorHint> {
        self.into()
    }
}

impl From<&TransactionRequestError> for Option<ErrorHint> {
    fn from(err: &TransactionRequestError) -> Self {
        match err {
            TransactionRequestError::NoInputNotesNorAccountChange => Some(ErrorHint {
                message: "Transactions must consume input notes or mutate tracked account state. Add at least one authenticated/unauthenticated input note or include an explicit account state update in the request.".to_string(),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            TransactionRequestError::StorageSlotNotFound(slot, account_id) => {
                Some(storage_miss_hint(*slot, *account_id))
            },
            TransactionRequestError::InputNoteNotAuthenticated(note_id) => Some(ErrorHint {
                message: format!(
                    "Note {note_id} needs an inclusion proof before it can be consumed as an \
                     authenticated input. Run `sync` to fetch the latest proofs from the network."
                ),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            TransactionRequestError::InputNoteBeingProcessed { transaction_id, .. } => {
                Some(ErrorHint {
                    message: format!(
                        "The note is an input of pending transaction {transaction_id}. Run `sync` \
                         until that transaction is committed or discarded before consuming the \
                         note again."
                    ),
                    docs_url: Some(TROUBLESHOOTING_DOC),
                })
            },
            TransactionRequestError::P2IDNoteWithoutAsset => Some(ErrorHint {
                message: "A pay-to-ID (P2ID) note transfers assets to a target account. \
                          Add at least one fungible or non-fungible asset to the note.".to_string(),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            TransactionRequestError::SwapNoteWithZeroAsset(side) => Some(ErrorHint {
                message: format!(
                    "A swap note exchanges the offered asset for the requested one, and its \
                     payback is a P2ID note carrying the requested asset. A zero {side} asset \
                     leaves one side of that exchange empty. Set a non-zero amount."
                ),
                docs_url: Some(TROUBLESHOOTING_DOC),
            }),
            TransactionRequestError::OutputNoteSenderMismatch { expected, actual } => {
                Some(ErrorHint {
                    message: format!(
                        "A note's sender is the account that emits it: it must be the account \
                         executing the transaction. This transaction runs as account {expected}, \
                         but one of its output notes declares sender {actual}. Rebuild the note \
                         with {expected} as its sender, or execute the transaction from {actual}."
                    ),
                    docs_url: Some(TROUBLESHOOTING_DOC),
                })
            },
            _ => None,
        }
    }
}

impl TransactionRequestError {
    pub fn error_hint(&self) -> Option<ErrorHint> {
        self.into()
    }
}

/// Returns the hint for an account the network allowlist does not accept.
fn account_not_allowlisted_hint(account_id: AccountId) -> ErrorHint {
    ErrorHint {
        message: format!(
            "The network only creates accounts that are on its allowlist, and account \
             {account_id} is not on it. Register it with \
             `account --register {account_id} --invitation-code <CODE>` before you create it."
        ),
        docs_url: Some(TROUBLESHOOTING_DOC),
    }
}

/// Hint for a batch submission that came back without a definite outcome.
fn batch_submission_outcome_unknown_hint(submission: &ProvenBatchSubmission) -> ErrorHint {
    ErrorHint {
        message: format!(
            "Do not rebuild the batch: re-executing produces new transaction ids over the same \
             notes, so if the original did land you would be left with ids that can never \
             commit. Neither option can apply the batch twice, since both consume the same \
             nullifiers. Either retry with the `submission` attached to this error, which \
             carries the proven batch and each transaction's inputs and records the batch if the \
             node accepts it, or sync and see whether the accounts moved: until a retry is \
             accepted the {} ids in `submission.transaction_ids()` have no record to look up.",
            submission.transaction_count()
        ),
        docs_url: Some(TROUBLESHOOTING_DOC),
    }
}

/// Returns the hint for an error the node or the transport returned.
fn rpc_hint(err: &RpcError) -> Option<ErrorHint> {
    match err {
        RpcError::ConnectionError(_) => Some(ErrorHint {
            message: "Could not reach the Miden node. Check that the node endpoint in your \
                      configuration is correct and that the node is running."
                .to_string(),
            docs_url: Some(TROUBLESHOOTING_DOC),
        }),
        RpcError::AcceptHeaderError(_) => Some(ErrorHint {
            message: "The node rejected the request due to a version mismatch. \
                      Ensure your client version is compatible with the node version."
                .to_string(),
            docs_url: Some(TROUBLESHOOTING_DOC),
        }),
        RpcError::RequestError {
            endpoint_error: Some(EndpointError::RegisterAccount(inner)),
            ..
        } => Some(register_account_hint(inner)),
        _ => None,
    }
}

/// Returns the hint for an invitation code that the client refused before it sent the code.
fn unneeded_invitation_code_hint(err: &ClientError, account_id: AccountId) -> ErrorHint {
    let message = match err {
        ClientError::AccountIsNetworkAccount(_) => format!(
            "Account {account_id} is a network account. The node admits network accounts without \
             an invitation code. Add the account without a code."
        ),
        ClientError::AccountAlreadyAllowed(_) => format!(
            "Account {account_id} is already registered, or the node does not enforce an \
             allowlist. The client did not send the invitation code. Keep the code for a \
             different account."
        ),
        _ => format!(
            "Account {account_id} already exists on chain. Only an account that is not deployed \
             needs an invitation code. Keep the code for a new account."
        ),
    };

    ErrorHint {
        message,
        docs_url: Some(TROUBLESHOOTING_DOC),
    }
}

/// Returns the hint for a registration that the node rejected.
fn register_account_hint(err: &RegisterAccountError) -> ErrorHint {
    let message = match err {
        RegisterAccountError::InvitationNotFound => {
            "The node does not know this invitation code. A code is case-sensitive. Send it \
             exactly as you received it, and do not add or remove characters."
        },
        RegisterAccountError::AlreadyRegistered => {
            "This invitation code is registered to a different account, or this account is \
             already registered. A code binds to one account only."
        },
        RegisterAccountError::InvalidRequest(_) => {
            "The node rejected the registration request. Check that the invitation code is not \
             empty and that the account ID is correct."
        },
    };

    ErrorHint {
        message: message.to_string(),
        docs_url: Some(TROUBLESHOOTING_DOC),
    }
}

fn missing_recipient_hint(recipients: &[Word]) -> ErrorHint {
    let message = format!(
        "Recipients {recipients:?} were missing from the transaction outputs. Keep `TransactionRequestBuilder::expected_output_recipients(...)` aligned with the MASM program so the declared recipients appear in the outputs."
    );

    ErrorHint {
        message,
        docs_url: Some(TROUBLESHOOTING_DOC),
    }
}

fn storage_miss_hint(slot: u8, account_id: AccountId) -> ErrorHint {
    ErrorHint {
        message: format!(
            "Storage slot {slot} was not found on account {account_id}. Verify the account ABI and component ordering, then adjust the slot index used in the transaction."
        ),
        docs_url: Some(TROUBLESHOOTING_DOC),
    }
}

fn transaction_executor_hint(err: &TransactionExecutorError) -> Option<ErrorHint> {
    match err {
        TransactionExecutorError::ForeignAccountNotAnchoredInReference(account_id) => {
            Some(ErrorHint {
                message: format!(
                    "The foreign account proof for {account_id} was built against a different block. Re-fetch the account proof anchored at the request's reference block before retrying."
                ),
                docs_url: Some(TROUBLESHOOTING_DOC),
            })
        },
        TransactionExecutorError::TransactionProgramExecutionFailed(_) => Some(ErrorHint {
            message: "Re-run the transaction with debug mode enabled, capture VM diagnostics, and inspect the source manager output to understand why execution failed.".to_string(),
            docs_url: Some(TROUBLESHOOTING_DOC),
        }),
        _ => None,
    }
}

// ID PREFIX FETCH ERROR
// ================================================================================================

/// Error when Looking for a specific ID from a partial ID.
#[derive(Debug, Error)]
pub enum IdPrefixFetchError {
    /// No matches were found for the ID prefix.
    #[error("no stored notes matched the provided prefix '{0}'")]
    NoMatch(String),
    /// Multiple entities matched with the ID prefix.
    #[error(
        "multiple {0} entries match the provided prefix; provide a longer prefix to narrow it down"
    )]
    MultipleMatches(String),
}