alephium-web3 2.0.7

A Rust library to interact with the Alephium platform
Documentation
// Copyright 2018 - 2022 The Alephium Authors
// This file is part of the alephium project.

use thiserror::Error;

/// Result type for the library
pub type Result<T> = std::result::Result<T, Error>;

/// Main error type for the Alephium Web3 library
#[derive(Error, Debug)]
pub enum Error {
    #[error("Invalid address: {0}")]
    InvalidAddress(String),

    #[error("Invalid hex string: {0}")]
    InvalidHex(String),

    #[error("Invalid base58 string: {0}")]
    InvalidBase58(String),

    #[error("Invalid signature: {0}")]
    InvalidSignature(String),

    #[error("Invalid key: {0}")]
    InvalidKey(String),

    #[error("Codec error: {0}")]
    CodecError(String),

    #[error("API error: {0}")]
    ApiError(String),

    #[error("HTTP error: {0}")]
    HttpError(#[from] reqwest::Error),

    #[error("Serialization error: {0}")]
    SerializationError(#[from] serde_json::Error),

    #[error("Invalid transaction: {0}")]
    InvalidTransaction(String),

    #[error("Invalid contract: {0}")]
    InvalidContract(String),

    #[error("Invalid group index: {0}")]
    InvalidGroupIndex(u8),

    #[error("Insufficient balance")]
    InsufficientBalance,

    #[error("Invalid value: {0}")]
    InvalidValue(String),

    #[error("IO error: {0}")]
    IoError(#[from] std::io::Error),

    #[error("Cryptography error: {0}")]
    CryptoError(String),

    #[error("{0}")]
    Other(String),
}

/// Traceable error that preserves the error chain
#[derive(Debug)]
pub struct TraceableError {
    pub message: String,
    pub source: Option<Box<dyn std::error::Error + Send + Sync>>,
}

impl std::fmt::Display for TraceableError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.message)?;
        if let Some(source) = &self.source {
            write!(f, "\nCaused by: {}", source)?;
        }
        Ok(())
    }
}

impl std::error::Error for TraceableError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        self.source.as_ref().map(|e| e.as_ref() as &(dyn std::error::Error + 'static))
    }
}

impl TraceableError {
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            source: None,
        }
    }

    pub fn with_source(message: impl Into<String>, source: impl std::error::Error + Send + Sync + 'static) -> Self {
        Self {
            message: message.into(),
            source: Some(Box::new(source)),
        }
    }
}