darkfid/
error.rs

1/* This file is part of DarkFi (https://dark.fi)
2 *
3 * Copyright (C) 2020-2025 Dyne.org foundation
4 *
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU Affero General Public License as
7 * published by the Free Software Foundation, either version 3 of the
8 * License, or (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 * GNU Affero General Public License for more details.
14 *
15 * You should have received a copy of the GNU Affero General Public License
16 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
17 */
18
19use darkfi::rpc::jsonrpc::{ErrorCode::ServerError, JsonError, JsonResult};
20
21/// Custom RPC errors available for darkfid.
22/// Please sort them sensefully.
23pub enum RpcError {
24    // Transaction-related errors
25    TxSimulationFail = -32110,
26    TxGasCalculationFail = -32111,
27
28    // State-related errors,
29    NotSynced = -32120,
30    UnknownBlockHeight = -32121,
31
32    // Parsing errors
33    ParseError = -32190,
34
35    // Contract-related errors
36    ContractZkasDbNotFound = -32200,
37    ContractStateNotFound = -32201,
38    ContractStateKeyNotFound = -32202,
39
40    // Misc errors
41    PingFailed = -32300,
42}
43
44fn to_tuple(e: RpcError) -> (i32, String) {
45    let msg = match e {
46        // Transaction-related errors
47        RpcError::TxSimulationFail => "Failed simulating transaction state change",
48        RpcError::TxGasCalculationFail => "Failed to calculate transaction's gas",
49        // State-related errors
50        RpcError::NotSynced => "Blockchain is not synced",
51        RpcError::UnknownBlockHeight => "Did not find block height",
52        // Parsing errors
53        RpcError::ParseError => "Parse error",
54        // Contract-related errors
55        RpcError::ContractZkasDbNotFound => "zkas database not found for given contract",
56        RpcError::ContractStateNotFound => "Records not found for given contract state",
57        RpcError::ContractStateKeyNotFound => "Value not found for given contract state key",
58        // Misc errors
59        RpcError::PingFailed => "Miner daemon ping error",
60    };
61
62    (e as i32, msg.to_string())
63}
64
65pub fn server_error(e: RpcError, id: u16, msg: Option<&str>) -> JsonResult {
66    let (code, default_msg) = to_tuple(e);
67
68    if let Some(message) = msg {
69        return JsonError::new(ServerError(code), Some(message.to_string()), id).into()
70    }
71
72    JsonError::new(ServerError(code), Some(default_msg), id).into()
73}