Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions packages/rs-sdk/src/core/dash_core_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl LowLevelDashCoreClient {
.map_err(Error::CoreClientError)
}

/// Return address to which change of transaction can be sent.
/// Return the wallet balance.
#[allow(dead_code)]
#[deprecated(note = "This function is marked as unused.")]
pub fn get_balance(&self) -> Result<Amount, Error> {
Expand Down Expand Up @@ -164,7 +164,7 @@ impl LowLevelDashCoreClient {
))
}

/// Require list of validators from Core.
/// Request list of Platform validators from Core.
///
/// See also [Dash Core documentation](https://docs.dash.org/projects/core/en/stable/docs/api/remote-procedure-calls-evo.html#protx-list)
#[allow(unused)]
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-sdk/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ pub enum Error {
/// Drive error
#[error("Drive error: {0}")]
Drive(#[from] drive::error::Error),
/// Drive error
/// Drive proof error with associated proof bytes and block info
#[error("Drive error with associated proof: {0}")]
DriveProofError(drive::error::proof::ProofError, Vec<u8>, BlockInfo),
/// DPP error
Expand Down
49 changes: 33 additions & 16 deletions packages/rs-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,66 @@
//!
//! This is the official Rust SDK for the Dash Platform. Dash Platform is a Layer 2 cryptocurrency technology that
//! builds upon the Dash layer 1 network. This SDK provides an abstraction layer to simplify usage of the Dash
//! Platform along with data models based on the Dash Platform Protocol (DPP), a CRUD interface, and bindings
//! for other technologies such as C.
//! Platform along with data models based on the Dash Platform Protocol (DPP), query traits for reading data, and
//! state transition traits for writing data.
//!
//!
//! ## Dash Platform Protocol Data Model
//!
//! SDK data model uses types defined in [Dash Platform Protocol (DPP)](crate::platform::dpp). At this point, the following
//! types are supported:
//! SDK data model uses types defined in [Dash Platform Protocol (DPP)](crate::platform::dpp). The core types are:
//!
//! 1. [`Identity`](crate::platform::Identity)
//! 2. [`Data Contract`](crate::platform::DataContract)
//! 2. [`DataContract`](crate::platform::DataContract)
//! 3. [`Document`](crate::platform::Document)
//!
//! To define document search conditions, you can use [`DriveQuery`](crate::platform::DriveDocumentQuery) and convert it
//! To define document search conditions, you can use [`DriveDocumentQuery`](crate::platform::DriveDocumentQuery) and convert it
//! to [`DocumentQuery`](crate::platform::DocumentQuery) with the [`From`] trait.
//!
//! Basic DPP objects are re-exported in the [`platform`] module.
//!
//! ## CRUD Interface
//! ## Querying (Reading Data)
//!
//! Operations on data model objects can be executing using traits following CRUD (Create, Read, Update, and Delete)
//! approach. The following traits are already implemented:
//! Data can be read from Platform using the following traits:
//!
//! 1. [`Fetch`](crate::platform::Fetch)
//! 2. [`FetchMany`](crate::platform::FetchMany)
//! 1. [`Fetch`](crate::platform::Fetch) - fetch a single object from Platform with proof verification
//! 2. [`FetchMany`](crate::platform::FetchMany) - fetch multiple objects from Platform with proof verification
//! 3. [`FetchUnproved`](crate::platform::FetchUnproved) - fetch a single object without proof verification
//! (e.g., for node status queries)
//! 4. [`FetchCurrent`](crate::platform::fetch_current_no_parameters::FetchCurrent) - fetch current
//! state for parameter-free queries (e.g., current epoch, total credits)
//!
//! Fetch and FetchMany traits return objects based on provided queries. Some example queries include:
//! These traits return objects based on provided queries. Some example queries include:
//!
//! 1. [`Identifier`](crate::platform::Identifier) - fetches an object by its identifier
//! 2. [`DocumentQuery`](crate::platform::DocumentQuery) - fetches documents based on search conditions; see
//! [query syntax documentation](https://docs.dash.org/projects/platform/en/stable/docs/reference/query-syntax.html)
//! for more details.
//! 3. [`DriveQuery`](crate::platform::DriveDocumentQuery) - can be used to build more complex queries
//! 3. [`DriveDocumentQuery`](crate::platform::DriveDocumentQuery) - can be used to build more complex queries
//!
//! ## State Transitions (Writing Data)
//!
//! Data is written to Platform by broadcasting state transitions. The SDK provides traits for common
//! write operations:
//!
//! - [`PutIdentity`](crate::platform::transition::put_identity::PutIdentity) - register a new identity
//! - [`PutContract`](crate::platform::transition::put_contract::PutContract) - publish a data contract
//! - [`PutDocument`](crate::platform::transition::put_document::PutDocument) - create or replace a document
//! - [`TransferToIdentity`](crate::platform::transition::transfer::TransferToIdentity) - transfer credits between identities
//! - [`WithdrawFromIdentity`](crate::platform::transition::withdraw_from_identity::WithdrawFromIdentity) - withdraw credits
//! - [`TopUpIdentity`](crate::platform::transition::top_up_identity::TopUpIdentity) - add credits to an identity
//! - [`PutVote`](crate::platform::transition::vote::PutVote) - cast a masternode vote
//!
//! For document operations, builder-based APIs are also available (see [`platform::documents::transitions`]).
//!
//! ## Testability
//!
//! SDK operations can be mocked using [Sdk::new_mock()].
//!
//! Examples can be found in `tests/mock_*.rs`.
//! Examples can be found in `tests/fetch/mock_fetch.rs` and `tests/fetch/mock_fetch_many.rs`.
//!
//! ## Error handling
//!
//! Errors of type [Error] are returned by the dash-platform-sdk. Note that missing objects ("not found") are not
//! Errors of type [Error] are returned by the SDK. Note that missing objects ("not found") are not
//! treated as errors; `Ok(None)` is returned instead.
//!
//! Mocking functions often panic instead of returning an error.
Expand All @@ -55,7 +72,7 @@
//! flexible framework for adding structured, context-aware logs to your program.
//!
//! To enable logging, you can use the `tracing_subscriber` crate which allows applications to customize how events are processed and recorded.
//! An example can be found in `tests/common.rs:setup_logs()`.
//! An example can be found in `tests/fetch/common.rs:setup_logs()`.
//!
// TODO re-enable when docs are complete
// #![warn(missing_docs)]
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-sdk/src/mock.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
//! sdk.mock().expect_fetch(query, None as Option<dash_sdk::platform::Identity>);
//! ```
//!
//! See tests/mock_*.rs for more detailed examples.
//! See `tests/fetch/mock_fetch.rs` and `tests/fetch/mock_fetch_many.rs` for more detailed examples.

#[cfg(not(feature = "mocks"))]
mod noop;
Expand Down
10 changes: 5 additions & 5 deletions packages/rs-sdk/src/mock/provider.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
//! Example ContextProvider that uses the Core gRPC API to fetch data from Platform.
//! Example ContextProvider that uses the Core RPC API and the Sdk to fetch data.

use crate::core::LowLevelDashCoreClient;
use crate::platform::Fetch;
Expand All @@ -14,7 +14,7 @@ use std::hash::Hash;
use std::num::NonZeroUsize;
use std::sync::Arc;

/// Context provider that uses the Core gRPC API to fetch data from Platform.
/// Context provider that uses the Core RPC API and the Sdk to fetch data.
///
/// Example [ContextProvider] used by the Sdk for testing purposes.
pub struct GrpcContextProvider {
Expand Down Expand Up @@ -137,9 +137,9 @@ impl GrpcContextProvider {

/// Save data contract to disk.
///
/// Files are named: `quorum_pubkey-<int_quorum_type>-<hex_quorum_hash>.json`
/// Files are named: `data_contract-<hex_data_contract_id>.json`
///
/// Note that this will overwrite files with the same quorum type and quorum hash.
/// Note that this will overwrite files with the same data contract ID.
///
/// Any errors are logged on `warn` level and ignored.
#[cfg(feature = "mocks")]
Expand Down Expand Up @@ -251,7 +251,7 @@ impl ContextProvider for GrpcContextProvider {
///
/// This is used to cache objects that are expensive to fetch from Platform, like data contracts.
pub struct Cache<K: Hash + Eq, V> {
// We use a Mutex to allow access to the cache when we don't have mutable &self
// We use a RwLock to allow access to the cache when we don't have mutable &self
// And we use Arc to allow multiple threads to access the cache without having to clone it
inner: std::sync::RwLock<lru::LruCache<K, Arc<V>>>,
Comment thread
lklimek marked this conversation as resolved.
}
Expand Down
15 changes: 8 additions & 7 deletions packages/rs-sdk/src/mock/sdk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ impl MockDashPlatformSdk {
///
/// ## Note
///
/// You have to call [MockDashPlatformSdk::with_sdk()] to set sdk, otherwise Mock SDK will panic.
/// You have to call [MockDashPlatformSdk::set_sdk()] to set sdk, otherwise Mock SDK will panic.
pub(crate) fn new(version: &'static PlatformVersion, dapi: Arc<Mutex<MockDapiClient>>) -> Self {
Self {
from_proof_expectations: Default::default(),
Expand Down Expand Up @@ -275,7 +275,7 @@ impl MockDashPlatformSdk {
/// ## Generic Parameters
///
/// - `O`: Type of the object that will be returned in response to the query. Must implement [Fetch] and [MockResponse].
/// - `Q`: Type of the query that will be sent to Platform. Must implement [Query] and [Mockable].
/// - `Q`: Type of the query that will be sent to Platform. Must implement [Query].
///
/// ## Arguments
///
Expand Down Expand Up @@ -352,13 +352,14 @@ impl MockDashPlatformSdk {
/// ## Generic Parameters
///
/// - `O`: Type of the object that will be returned in response to the query.
/// Must implement [FetchMany]. `Vec<O>` must implement [MockResponse].
/// - `Q`: Type of the query that will be sent to Platform. Must implement [Query] and [Mockable].
/// Must implement [FetchMany].
/// - `Q`: Type of the query that will be sent to Platform. Must implement [Query].
/// - `R`: Collection type for the results. Must implement [MockResponse].
///
/// ## Arguments
///
/// - `query`: Query that will be sent to Platform.
/// - `objects`: Vector of objects that will be returned in response to `query`, or None if no objects are expected.
/// - `objects`: Collection of objects that will be returned in response to `query`, or None if no objects are expected.
///
/// ## Returns
///
Expand Down Expand Up @@ -487,7 +488,7 @@ impl MockDashPlatformSdk {
removed_from_proof || removed_from_dapi
}

/// Wrapper around [FromProof] that uses mock expectations instead of executing [FromProof] trait.
/// Wrapper around [FromProof] that uses mock expectations, falling back to [FromProof] if no expectation is found.
pub(crate) fn parse_proof_with_metadata<I, O: FromProof<I>>(
&self,
request: O::Request,
Expand Down Expand Up @@ -535,7 +536,7 @@ impl MockDashPlatformSdk {

Ok(data)
}
/// Return context provider implementation defined for upstreeam Sdk object.
/// Return context provider implementation defined for upstream Sdk object.
fn context_provider(&self) -> Option<impl ContextProvider> {
if let Some(sdk) = self.sdk.load_full() {
sdk.clone().context_provider()
Expand Down
8 changes: 4 additions & 4 deletions packages/rs-sdk/src/platform/address_sync/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ pub struct AddressSyncConfig {

/// Maximum age in seconds before a full tree rescan is forced.
///
/// When `last_sync_timestamp` is passed to [`sync_address_balances`], the
/// When `last_sync_timestamp` is passed to [`sync_address_balances`](super::sync_address_balances), the
/// function compares `now - last_sync_timestamp` against this threshold.
/// If the elapsed time exceeds this value, a full tree rescan is performed
/// instead of incremental-only catch-up.
Expand Down Expand Up @@ -113,15 +113,15 @@ pub struct AddressSyncResult {
///
/// After each sync the caller should persist two values:
/// 1. This `new_sync_height` — return it from
/// [`AddressProvider::last_sync_height`] on the next call.
/// [`AddressProvider::last_sync_height`](super::provider::AddressProvider::last_sync_height) on the next call.
/// 2. [`new_sync_timestamp`](Self::new_sync_timestamp) — pass it as the
/// `last_sync_timestamp` parameter of [`sync_address_balances`].
/// `last_sync_timestamp` parameter of [`sync_address_balances`](super::sync_address_balances).
pub new_sync_height: u64,

/// Platform block time (Unix seconds) at the point of the latest response.
///
/// Store this value and pass it back as `last_sync_timestamp` on the next
/// call to [`sync_address_balances`]. The function compares it against the
/// call to [`sync_address_balances`](super::sync_address_balances). The function compares it against the
/// current wall-clock time to decide whether a full tree rescan is needed.
pub new_sync_timestamp: u64,
}
Expand Down
10 changes: 5 additions & 5 deletions packages/rs-sdk/src/platform/block_info_from_metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ use drive::error::proof::ProofError;
/// Constructs a `BlockInfo` structure from the provided response metadata. This function
/// translates metadata received from a platform response into a format that is specific to the
/// application's needs, particularly focusing on block-related information. It ensures that
/// the epoch value from the metadata does not exceed the maximum allowed for a 16-bit integer,
/// as this is a constraint for the `BlockInfo` structure.
/// the epoch value from the metadata does not exceed `MAX_EPOCH`,
/// as this is a constraint for the `Epoch` type used in the `BlockInfo` structure.
///
/// # Parameters
/// - `response_metadata`: A reference to `ResponseMetadata` obtained from a platform response.
Expand All @@ -20,18 +20,18 @@ use drive::error::proof::ProofError;
/// - `time_ms`: The timestamp of the block in milliseconds.
/// - `height`: The height of the block.
/// - `core_height`: The core chain locked height, indicating the height of the block in the core blockchain that is considered final and securely linked to this block.
/// - `epoch`: The epoch number, converted to a 16-bit integer.
/// - `epoch`: The epoch number, converted to an `Epoch` struct via a 16-bit number.
///
/// # Errors
/// Returns an error if:
/// - The `epoch` value in the response metadata exceeds the maximum value that can be represented by a 16-bit integer. This is considered a data validity error as it indicates Platform returned an unexpectedly high epoch number.
/// - The `epoch` value in the response metadata exceeds `MAX_EPOCH`. This is considered a data validity error as it indicates Platform returned an unexpectedly high epoch number.
///
/// The function encapsulates errors into the application's own `Error` type, providing a unified interface for error handling across the application.
pub fn block_info_from_metadata(response_metadata: &ResponseMetadata) -> Result<BlockInfo, Error> {
if response_metadata.epoch > MAX_EPOCH as u32 {
return Err(
drive::error::Error::Proof(ProofError::InvalidMetadata(format!(
"platform returned an epoch {} that was higher that maximum of a 16 bit integer",
"platform returned an epoch {} that was higher than the maximum allowed epoch",
response_metadata.epoch
)))
.into(),
Expand Down
12 changes: 6 additions & 6 deletions packages/rs-sdk/src/platform/delegate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
/// Delegate the execution of a transport request to the appropriate variant of an enum wrapper.
///
/// Given two enums, request and response, that wrap multiple requests/responses for one object type, this macro
/// implements [TransportRequest](crate::platform::dapi::transport::TransportRequest) for the request enum and
/// implements [TransportRequest](rs_dapi_client::transport::TransportRequest) for the request enum and
/// delegates the execution of the transport request to the appropriate variant.
///
/// Each variant in request enum must have a corresponding variant in response enum.
/// Variant names in request and response enums must match.
/// Variants must take exactly one argument that implements
/// [TransportRequest](crate::platform::dapi::transport::TransportRequest) (for request) and
/// [TransportResponse](crate::platform::dapi::transport::TransportResponse) (for response), where for a given variant,
/// [TransportRequest](rs_dapi_client::transport::TransportRequest) (for request) and
/// `TransportResponse` (for response), where for a given variant,
/// response must be the response type of the request variant.
///
/// Macro [delegate_enum!](crate::delegate_enum!) can be used to generate these enums and implement required
Expand Down Expand Up @@ -127,15 +127,15 @@ macro_rules! delegate_from_proof_variant {
///
/// In order to support multiple request/response types for one object (like, GetIdentityRequest and
/// GetIdentityByPublicKeyHashRequest for Identity), we need to wrap them in an enum and
/// delegate [TransportRequest](crate::platform::dapi::transport::TransportRequest)
/// delegate [TransportRequest](rs_dapi_client::transport::TransportRequest)
/// and [FromProof](drive_proof_verifier::FromProof) to the appropriate variant.
///
/// This macro creates enums for requests (`$request`) and responses (`$response`) and variants (`$variant`) for
/// each request (`$req`) /response (`$req`) pair. Variant name in request and response enums are the same.
/// each request (`$req`) /response (`$resp`) pair. Variant name in request and response enums are the same.
///
/// It also calls [delegate_transport_request_variant!](crate::delegate_transport_request_variant!) and
/// [delegate_from_proof_variant!](crate::delegate_from_proof_variant!) to delegate
/// [TransportRequest](crate::platform::dapi::transport::TransportRequest)
/// [TransportRequest](rs_dapi_client::transport::TransportRequest)
/// and [FromProof](drive_proof_verifier::FromProof)
/// traits to the appropriate variant.
macro_rules! delegate_enum {
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-sdk/src/platform/documents/document_query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ use crate::platform::Fetch;
#[derive(Debug, Clone, PartialEq, dash_platform_macros::Mockable)]
#[cfg_attr(feature = "mocks", derive(serde::Serialize, serde::Deserialize))]
pub struct DocumentQuery {
/// Data contract ID
/// Data contract
pub data_contract: Arc<DataContract>,
/// Document type for the data contract
pub document_type_name: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ impl DocumentCreateTransitionBuilder {
///
/// # Arguments
///
/// * `settings` - The settings to add
/// * `creation_options` - The creation options to add
///
/// # Returns
///
Expand All @@ -128,7 +128,6 @@ impl DocumentCreateTransitionBuilder {
/// * `identity_public_key` - The public key of the identity
/// * `signer` - The signer instance
/// * `platform_version` - The platform version
/// * `options` - Optional state transition creation options
///
/// # Returns
///
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ pub struct ContestInfo {
pub end_time: TimestampMillis,
}

/// Result of a contested DPNS username
/// A contested DPNS username
#[derive(Debug, Clone)]
pub struct ContestedDpnsUsername {
/// The domain label (e.g., "alice")
Expand Down
2 changes: 1 addition & 1 deletion packages/rs-sdk/src/platform/dpns_usernames/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn convert_to_homograph_safe_chars(input: &str) -> String {
/// - It contains only alphanumeric characters and hyphens
/// - It doesn't have consecutive hyphens (enforced by the pattern)
///
/// Pattern: ^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$
/// Pattern: `^[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]$`
///
/// # Arguments
///
Expand Down
Loading
Loading