Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: improved credit transfer strategies #97

Open
wants to merge 12 commits into
base: master
Choose a base branch
from
193 changes: 102 additions & 91 deletions Cargo.lock

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,24 +12,24 @@ tui-realm-stdlib = "1.3.1"
tuirealm = "1.9.1"
bs58 = "0.5.0"
copypasta = "0.10.1"
dpp = { git = "https://github.com/dashpay/platform", tag = "v1.4.1", features = [
dpp = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb", features = [
"client",
] }
dash-sdk = { git = "https://github.com/dashpay/platform", tag = "v1.4.1" }
drive = { git = "https://github.com/dashpay/platform", tag = "v1.4.1" }
drive-proof-verifier = { git = "https://github.com/dashpay/platform", tag = "v1.4.1" }
dash-sdk = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb" }
drive = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb" }
drive-proof-verifier = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb" }
thiserror = "1.0.64"
serde = "1.0.197"
serde_json = "1.0.120"
toml = { version = "0.8.10", features = ["display"] }
dapi-grpc = { git = "https://github.com/dashpay/platform", tag = "v1.4.1", features = [
dapi-grpc = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb", features = [
"client",
] }
rs-dapi-client = { git = "https://github.com/dashpay/platform", tag = "v1.4.1" }
rs-dapi-client = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb" }
tokio = { version = "1.36.0", features = ["full"] }
bincode = { version = "2.0.0-rc.3", features = ["serde"] }
strategy-tests = { git = "https://github.com/dashpay/platform", tag = "v1.4.1" }
simple-signer = { git = "https://github.com/dashpay/platform", tag = "v1.4.1" }
strategy-tests = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb" }
simple-signer = { git = "https://github.com/dashpay/platform.git", commit = "cafda11af1ee767a8cf803c23697f57401fc30fb" }
reqwest = { version = "0.12.3", features = ["json"] }
hex = { version = "0.4.3" }
itertools = "0.12.1"
Expand Down
6 changes: 3 additions & 3 deletions src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ use std::{
};

use arboard::Clipboard;
use dash_sdk::dashcore_rpc::Client;
use dash_sdk::Sdk;
use dash_sdk::{dashcore_rpc::Client, query_types::IndexMap};
use dpp::{
document::Document,
identity::accessors::IdentityGettersV0,
Expand Down Expand Up @@ -77,13 +77,13 @@ pub enum Task {
/// that case specific variants are used.
#[derive(Debug)]
pub enum CompletedTaskPayload {
Documents(BTreeMap<Identifier, Option<Document>>),
Documents(IndexMap<Identifier, Option<Document>>),
Document(Document),
Identities(BTreeMap<Identifier, Identity>),
String(String),
ContestedResources(ContestedResources),
ContestedResourceContenders(ContestedDocumentResourceVotePoll, Contenders, Option<u64>),
DocumentsAndContestedResources(BTreeMap<Identifier, Option<Document>>, ContestedResources),
DocumentsAndContestedResources(IndexMap<Identifier, Option<Document>>, ContestedResources),
}

impl From<String> for CompletedTaskPayload {
Expand Down
4 changes: 2 additions & 2 deletions src/backend/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ impl From<InsightError> for Error {
}
}

impl From<DapiClientError<Status>> for Error {
fn from(value: DapiClientError<Status>) -> Self {
impl From<DapiClientError> for Error {
fn from(value: DapiClientError) -> Self {
SdkError(value.into())
}
}
4 changes: 3 additions & 1 deletion src/backend/identities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1806,6 +1806,7 @@ impl AppState {
let block_hash = sdk
.execute(GetBlockchainStatusRequest {}, RequestSettings::default())
.await?
.inner
.chain
.map(|chain| chain.best_block_hash)
.ok_or_else(|| dash_sdk::Error::DapiClientError("missing `chain` field".to_owned()))?;
Expand Down Expand Up @@ -1846,7 +1847,8 @@ impl AppState {
},
RequestSettings::default(),
)
.await?;
.await?
.inner;

tracing::debug!(
"restarting the stream from the transaction minded block hash {}",
Expand Down
282 changes: 158 additions & 124 deletions src/backend/strategies.rs

Large diffs are not rendered by default.

50 changes: 15 additions & 35 deletions src/backend/wallet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ use dpp::dashcore::{
Address, OutPoint, PrivateKey, PublicKey, ScriptBuf, Transaction, TxIn, TxOut, Witness,
};
use rand::{prelude::StdRng, Rng, SeedableRng};
use rs_dapi_client::DapiRequestExecutor;
use rs_dapi_client::{DapiRequestExecutor, IntoInner};
use tokio::sync::{Mutex, MutexGuard};

use super::{set_clipboard, AppStateUpdate, BackendEvent, CompletedTaskPayload, Task};
Expand Down Expand Up @@ -636,41 +636,16 @@ impl SingleKeyWallet {
core_client: &Client,
) -> Result<HashMap<OutPoint, TxOut>, String> {
// First, let's try to get UTXOs from the RPC client using `list_unspent`.
match core_client.list_unspent(Some(1), None, Some(&[&self.address]), None, None) {
// If that doesn't work, use the Insight API as a fallback
match insight
.utxos_with_amount_for_addresses(&[&self.address])
.await
{
Ok(utxos) => {
// Test log statement
tracing::info!("{:?} utxos", utxos.len());

// Convert RPC UTXOs to the desired HashMap format
let mut utxo_map = HashMap::new();
for utxo in utxos {
let outpoint = OutPoint::new(utxo.txid, utxo.vout);
let tx_out = TxOut {
value: utxo.amount.to_sat(),
script_pubkey: utxo.script_pub_key,
};
utxo_map.insert(outpoint, tx_out);
}
self.utxos = utxo_map.clone(); // Store the result in `self.utxos`
Ok(utxo_map)
}
Err(first_error) => {
// If that doesn't work, use the Insight API as a fallback
match insight
.utxos_with_amount_for_addresses(&[&self.address])
.await
{
Ok(utxos) => {
self.utxos = utxos.clone();
Ok(utxos)
}
Err(err) => Err(format!(
"First error from Core: {}, Second Error from Insight: {}",
first_error.to_string(),
err.to_string()
)),
}
self.utxos = utxos.clone();
Ok(utxos)
}
Err(err) => Err(format!("Error from Insight: {}", err.to_string())),
}
}

Expand Down Expand Up @@ -815,7 +790,11 @@ impl SingleKeyWallet {
bypass_limits: false,
};
let max_retries = 3;
match sdk.execute(request, RequestSettings::default()).await {
match sdk
.execute(request, RequestSettings::default())
.await
.into_inner()
{
Ok(BroadcastTransactionResponse { transaction_id: id }) => {
tokio::time::sleep(Duration::from_secs(1)).await;

Expand All @@ -829,6 +808,7 @@ impl SingleKeyWallet {
RequestSettings::default(),
)
.await
.into_inner()
{
Ok(GetTransactionResponse { .. }) => {
transaction_found = true;
Expand Down
79 changes: 66 additions & 13 deletions src/bin/query_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ use governor::{Quota, RateLimiter};
use rand::seq::SliceRandom;
use rs_dapi_client::{
Address, AddressList, DapiClient, DapiClientError, DapiRequest, DapiRequestExecutor,
RequestSettings,
ExecutionResponse, ExecutionResult, IntoInner, RequestSettings,
};
use rs_platform_explorer::config::Config;
use tokio::time::{interval, Instant};
Expand Down Expand Up @@ -395,9 +395,15 @@ async fn send_request(
summary: &TestSummary,
) {
// TODO: Record response duration and then report average and histogram?
match request.execute(client.as_ref(), settings).await {
match request
.execute(client.as_ref(), settings)
.await
.into_inner()
{
Ok(_) => summary.add_ok(),
Err(DapiClientError::Transport(e, ..)) => summary.add_error(e),
Err(DapiClientError::Transport(e, ..)) => summary.add_error(match e {
rs_dapi_client::transport::TransportError::Grpc(status) => status,
}),
Err(e) => panic!("unexpected error: {}", e),
}
}
Expand Down Expand Up @@ -503,48 +509,95 @@ impl From<GetDataContractsRequest> for AnyDapiRequest {

impl DapiRequest for AnyDapiRequest {
type Response = ();
type TransportError = dapi_grpc::tonic::Status;

fn execute<'c, D: DapiRequestExecutor>(
self,
dapi_client: &'c D,
settings: RequestSettings,
) -> BoxFuture<'c, Result<Self::Response, DapiClientError<Self::TransportError>>>
) -> BoxFuture<'c, ExecutionResult<Self::Response, DapiClientError>>
where
Self: 'c,
{
match self {
AnyDapiRequest::GetIdentityRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetIdentityNonceRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetIdentityContractNonceRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetIdentityBalanceRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetIdentityBalanceAndRevisionRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetIdentityKeysRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetDataContractRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
AnyDapiRequest::GetDataContractsRequest(request) => request
.execute(dapi_client, settings)
.map(|result| result.map(|_| ()))
.map(|result| {
result.map(|response| ExecutionResponse {
inner: (),
retries: response.retries,
address: response.address,
})
})
.boxed(),
}
}
Expand Down
4 changes: 1 addition & 3 deletions src/bin/strategy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ use rs_platform_explorer::{
},
config::Config,
};
use std::os::fd::IntoRawFd;
use std::{fs::File, panic, time::Duration};
use tracing::level_filters::LevelFilter;
use tracing_subscriber::EnvFilter;
Expand Down Expand Up @@ -251,16 +250,15 @@ async fn main() {
.expect("expected core client");

if let Some(test_name) = args.test {
let block_mode = if args.second { false } else { true };
backend
.state()
.run_strategy_task(
&sdk,
backend::strategies::StrategyTask::RunStrategy(
test_name.to_string(),
args.blocks,
1,
args.prove,
block_mode,
credit_amount,
),
&insight,
Expand Down
8 changes: 3 additions & 5 deletions src/ui/views/documents.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
//! View for fetched documents navigation and inspection.

use std::collections::BTreeMap;

use dash_sdk::query_types::IndexMap;
use dpp::{
data_contract::{document_type::DocumentType, DataContract},
document::{Document, DocumentV0Getters},
Expand Down Expand Up @@ -73,7 +71,7 @@ impl DocumentsQuerysetScreenController {
data_contract: DataContract,
document_type: DocumentType,
identity_id: Option<Identifier>,
current_batch: BTreeMap<Identifier, Option<Document>>,
current_batch: IndexMap<Identifier, Option<Document>>,
) -> Self {
let mut document_select = tui_realm_stdlib::List::default()
.rows(
Expand All @@ -93,7 +91,7 @@ impl DocumentsQuerysetScreenController {

let document_view = Info::new_scrollable(
&current_batch
.first_key_value()
.first()
.map(|(_, v)| as_json_string(v))
.unwrap_or_else(String::new),
);
Expand Down
Loading