rialo-cdk 0.2.0-alpha.0

Rialo CDK - A comprehensive toolkit for building with the Rialo blockchain
Documentation
// Copyright (c) Subzero Labs, Inc.
// SPDX-License-Identifier: Apache-2.0

use async_trait::async_trait;
#[cfg(feature = "rpc-client")]
use rialo_api_types::messages::get_accounts_by_owner::GetAccountsByOwnerResponse;
use rialo_api_types::messages::submit_epoch_change::{
    SubmitEpochChangeRequest, SubmitEpochChangeResponse,
};
use serde::de::DeserializeOwned;

pub use crate::rpc::no_wasm::*;
use crate::{error::Result, rpc::types::*};

/// A generic trait for making RPC calls with type safety.
///
/// This trait provides a foundation for implementing various RPC clients
/// with the ability to serialize request parameters and deserialize responses.
///
/// # Type Parameters
///
/// * `T` - The type of parameters to send in the RPC request.
/// * `R` - The expected return type from the RPC call.
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait GenericRpcCaller: NoWasmSend + NoWasmSync {
    /// Makes a generic RPC call with the specified method and parameters.
    ///
    /// # Parameters
    ///
    /// * `method` - The RPC method name to call.
    /// * `params` - The parameters to pass to the RPC method.
    ///
    /// # Returns
    ///
    /// The deserialized response from the RPC call.
    ///
    /// # Errors
    ///
    /// Returns an error if the RPC call fails, or if there are serialization/deserialization issues.
    async fn call<T, R>(&self, method: &str, params: T) -> Result<R>
    where
        T: serde::Serialize + NoWasmSend,
        R: DeserializeOwned + NoWasmSend;
}

/// A trait that defines the specific RPC methods available in the Rialo blockchain.
///
/// This trait provides a comprehensive interface for interacting with Rialo nodes,
/// allowing clients to query account information, submit transactions, and more.
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
pub trait RpcClient: NoWasmSend + NoWasmSync {
    /// Makes an RPC call with raw JSON parameters and returns a raw JSON response.
    ///
    /// This method is useful for calls not covered by the specific methods in this trait.
    ///
    /// # Parameters
    ///
    /// * `method` - The RPC method name to call.
    /// * `params` - The JSON parameters to pass to the RPC method.
    ///
    /// # Returns
    ///
    /// The raw JSON response from the RPC call.
    async fn call_with_json(
        &self,
        method: &str,
        params: serde_json::Value,
    ) -> Result<serde_json::Value>;

    /// Gets the balance of an account.
    ///
    /// # Parameters
    ///
    /// * `pubkey` - The public key (address) of the account as a string.
    ///
    /// # Returns
    ///
    /// The account balance in the smallest denomination of the native token.
    async fn get_balance(&self, pubkey: &Pubkey) -> Result<u64>;

    /// Submits a signed transaction to the blockchain.
    ///
    /// # Parameters
    ///
    /// * `transaction` - The serialized, signed transaction as a byte array.
    /// * `options` - The options for the transaction.
    ///   If None, the default options are used.
    ///
    /// # Returns
    ///
    /// The transaction signature as a string, which can be used to check its status.
    async fn send_transaction(
        &self,
        transaction: &[u8],
        options: Option<SendTransactionOptions>,
    ) -> Result<Signature>;

    /// Send `submitEpochChange` admin transaction.
    async fn send_admin_transaction(
        &self,
        params: SubmitEpochChangeRequest,
    ) -> Result<SubmitEpochChangeResponse>;

    /// Gets detailed information about an account.
    ///
    /// # Parameters
    ///
    /// * `pubkey` - The public key (address) of the account as a string.
    ///
    /// # Returns
    ///
    /// Detailed account information including balance, owner, and data.
    async fn get_account_info(&self, pubkey: &Pubkey) -> Result<AccountInfo>;

    /// Gets the current finalized block height from the blockchain.
    ///
    /// The block height is a measure of blockchain progress, representing the number
    /// of blocks that have been produced since genesis. This method always returns
    /// the finalized block height for consistency and simplicity.
    ///
    /// # Returns
    ///
    /// The current finalized block height.
    async fn get_block_height(&self) -> Result<u64>;

    /// Gets the current finalized block height from the blockchain with advanced configuration.
    ///
    /// This method provides access to advanced parameters for block height retrieval,
    /// specifically minimum context slot requirements.
    ///
    /// * `min_context_slot` - The minimum context slot that the server must have reached
    ///   before responding to this request.
    ///
    /// # Returns
    ///
    /// The current finalized block height.
    async fn get_block_height_with_config(&self, min_context_slot: Option<u64>) -> Result<u64>;

    /// Gets detailed information about a transaction.
    ///
    /// # Parameters
    ///
    /// * `signature` - The transaction signature as a string.
    ///
    /// # Returns
    ///
    /// Detailed transaction information.
    async fn get_transaction(&self, signature: &Signature) -> Result<TransactionResponse>;

    /// Gets the total number of transactions processed since genesis.
    ///
    /// # Returns
    ///
    /// The total transaction count.
    async fn get_transaction_count(&self) -> Result<u64>;

    /// Calculates the minimum balance required for rent exemption.
    ///
    /// Accounts with at least this balance are exempt from paying rent.
    ///
    /// # Parameters
    ///
    /// * `size` - The size of the account data in bytes.
    ///
    /// # Returns
    ///
    /// The minimum balance required for rent exemption.
    async fn get_minimum_balance_for_rent_exemption(&self, size: u64) -> Result<u64>;

    /// Gets the status of multiple transaction signatures.
    ///
    /// # Parameters
    ///
    /// * `signatures` - A slice of transaction signatures as strings.
    ///
    /// # Returns
    ///
    /// A vector of signature statuses corresponding to the input signatures.
    async fn get_signature_statuses(
        &self,
        signatures: &[Signature],
    ) -> Result<Vec<SignatureStatus>>;

    /// Gets subscriptions for a given subscriber.
    ///
    /// Returns a list of subscriptions associated with the specified subscriber.
    /// Optionally filters by a specific subscription nonce and limits the results.
    ///
    /// # Parameters
    ///
    /// * `subscriber` - The public key of the subscriber to query.
    /// * `nonce` - The nonce identifying the specific subscription.
    ///
    /// # Returns
    ///
    /// The subscription for the specified subscriber and nonce.
    async fn get_subscription(
        &self,
        subscriber: &Pubkey,
        nonce: &str,
    ) -> Result<GetSubscriptionResponse>;

    /// Gets triggered transactions for a subscription account.
    ///
    /// Returns a list of transactions that were automatically triggered in response
    /// to subscription matches or other programmatic conditions.
    ///
    /// # Parameters
    ///
    /// * `subscription_account` - The public key of the subscription account.
    /// * `limit` - Optional limit on the number of transactions to return.
    ///
    /// # Returns
    ///
    /// A response containing triggered transactions for the subscription.
    async fn get_triggered_transactions(
        &self,
        subscription_account: &Pubkey,
        limit: Option<u32>,
    ) -> Result<GetTriggeredTransactionsResponse>;

    /// Requests an airdrop of tokens to the specified account.
    ///
    /// This method is typically only available on test networks.
    ///
    /// # Parameters
    ///
    /// * `pubkey` - The public key (address) of the recipient account.
    /// * `amount` - The amount of tokens to airdrop in the smallest denomination.
    ///
    /// # Returns
    ///
    /// The transaction signature of the airdrop as a string.
    async fn request_airdrop(&self, pubkey: &Pubkey, amount: u64) -> Result<Signature>;

    /// Gets epoch information.
    ///
    /// # Returns
    ///
    /// Epoch information including slot indices and transaction count.
    async fn get_epoch_info(&self) -> Result<EpochInfoResponse>;

    /// Gets the fee for a given message.
    ///
    /// # Parameters
    ///
    /// * `message` - The message to calculate fees for.
    ///
    /// # Returns
    ///
    /// The fee required for the message.
    async fn get_fee_for_message(&self, message: &str) -> Result<GetFeeForMessageResponse>;

    /// Gets information for multiple accounts.
    ///
    /// # Parameters
    ///
    /// * `pubkeys` - A slice of public keys to query.
    ///
    /// # Returns
    ///
    /// Account information for the requested accounts.
    async fn get_multiple_accounts(&self, pubkeys: &[Pubkey]) -> Result<MultipleAccountsResponse>;

    /// Gets workflow lineage information.
    ///
    /// # Parameters
    ///
    /// * `request` - The workflow lineage request parameters.
    ///
    /// # Returns
    ///
    /// Workflow lineage information.
    async fn get_workflow_lineage(
        &self,
        request: &GetWorkflowLineageRequest,
    ) -> Result<GetWorkflowLineageResponse>;

    /// Gets signatures for a given address.
    ///
    /// # Parameters
    ///
    /// * `address` - The address to query signatures for.
    /// * `config` - Optional configuration for the request.
    ///
    /// # Returns
    ///
    /// Signatures for the given address.
    async fn get_signatures_for_address(
        &self,
        address: &Pubkey,
        config: Option<GetSignaturesForAddressConfig>,
    ) -> Result<GetSignaturesForAddressResponse>;

    /// Checks if a blockhash is valid.
    ///
    /// # Parameters
    ///
    /// * `blockhash` - The blockhash to validate.
    ///
    /// # Returns
    ///
    /// Whether the blockhash is valid.
    async fn is_blockhash_valid(&self, blockhash: &Hash) -> Result<IsBlockhashValidResponse>;

    /// Gets the health status of the node.
    ///
    /// # Returns
    ///
    /// The health status of the node, typically "ok" when healthy.
    async fn get_health(&self) -> Result<GetHealthResponse>;

    /// Gets the health status of the validator.
    ///
    /// # Returns
    ///
    /// The validator health status, typically "ok" when healthy.
    async fn get_validator_health(&self) -> Result<GetValidatorHealthResponse>;

    /// Gets the full nodes connected to the validator or full node.
    ///
    /// # Returns
    ///
    /// A list of full nodes identified by a `NetworkPublicKey` and how long
    /// they have been connected in milliseconds.
    async fn get_connected_full_nodes(&self) -> Result<GetConnectedFullNodesResponse>;

    /// Gets transactions from the blockchain with pagination support.
    ///
    /// Returns a list of transactions, optionally filtered and paginated.
    /// This method provides access to blockchain activity and can be used
    /// for transaction monitoring, analytics, and debugging purposes.
    ///
    /// # Parameters
    ///
    /// * `config` - Optional configuration for pagination, commitment levels, and encoding.
    ///   If None, default values will be used (limit: 100, commitment: finalized).
    ///
    /// # Returns
    ///
    /// A response containing transactions with metadata including signatures,
    /// slots, block times, confirmation status, and transaction versions.
    async fn get_transactions(
        &self,
        config: Option<GetTransactionsConfig>,
    ) -> Result<GetTransactionsResponse>;

    /// Retrieves the current Secret Sharing Public Key.
    ///
    /// This method queries the blockchain to get the public key that should be used
    /// for encrypting secrets.
    ///
    /// # Returns
    ///
    /// Returns a [`GetSecretSharingPubkeyResponse`] containing:
    /// - `public_key`: The current secret sharing public key (32 bytes, hex-encoded)
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The RPC call fails
    /// - The TEE Registry state account doesn't exist
    /// - The secret sharing public key has not been registered yet (no TEE has generated the key)
    /// - The state account data cannot be deserialized
    ///
    async fn get_secret_sharing_pubkey(&self) -> Result<GetSecretSharingPubkeyResponse>;

    /// Gets accounts by owner with filter support.
    ///
    /// Returns accounts based on the owner. By default, this uses the
    /// `programAccounts` filter which returns all accounts owned by the specified program.
    ///
    /// # Parameters
    ///
    /// * `owner` - The public key of the owner to query accounts for.
    ///             For programAccounts filter: this is the program ID.
    ///
    /// # Returns
    ///
    /// A response containing accounts matching the filter criteria.
    async fn get_accounts_by_owner(&self, owner: &Pubkey) -> Result<GetAccountsByOwnerResponse>;
}