From 6e36ed6982d5628896fe6605e65802631a012be6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:09:52 +0000 Subject: [PATCH 1/6] feat(documents): agree to document action fees before broadcasting On protocol 14 a document type can charge an action fee. A fee quote holds the declared owner and moderator parts at the fee multiplier the user saw and the most it can become; its agreement tolerates a 20% multiplier rise for a multiplier-priced fee. The backend never agrees on the user's behalf: an action whose agreement is missing or names another fee is refused before signing. A refusal for a risen multiplier refreshes the multiplier from a proved epoch, so trying again quotes the current fee; if that refresh fails the user is told the fee could not be updated. A protocol 13 guard checks that a fee agreement is refused locally there. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/document.rs | 178 +++++++++++- src/backend_task/platform_info.rs | 4 +- src/backend_task/protocol_13_transitions.rs | 26 ++ src/context/mod.rs | 4 +- src/model/fee_estimation.rs | 303 +++++++++++++++++++- 5 files changed, 510 insertions(+), 5 deletions(-) diff --git a/src/backend_task/document.rs b/src/backend_task/document.rs index fbb493c30..c07e464ca 100644 --- a/src/backend_task/document.rs +++ b/src/backend_task/document.rs @@ -4,15 +4,21 @@ use crate::backend_task::{ await_network_request_with_timeout, }; use crate::context::AppContext; +use crate::model::fee_estimation::checked_action_fee_agreement; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::request_type::RequestType; +use dash_sdk::Error as SdkError; use dash_sdk::Sdk; -use dash_sdk::dpp::data_contract::document_type::DocumentType; use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::DocumentActionFeeAgreement; use dash_sdk::dpp::document::{DocumentV0Getters, DocumentV0Setters}; use dash_sdk::dpp::fee::Credits; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::tokens::token_payment_info::TokenPaymentInfo; +use dash_sdk::dpp::{ + data_contract::document_type::DocumentType, + state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType, +}; use dash_sdk::drive::query::SelectProjection; use dash_sdk::platform::documents::transitions::DocumentCreateResult; use dash_sdk::platform::documents::transitions::DocumentCreateTransitionBuilder; @@ -43,6 +49,10 @@ pub enum DocumentTask { data_contract: Arc, qualified_identity: QualifiedIdentity, identity_key: IdentityPublicKey, + /// The document action fee the user was shown and agreed to (protocol + /// version 14). Required when the document type charges a fee for + /// the action: the backend never agrees on the user's behalf. + action_fee_agreement: Option, }, DeleteDocument { document_id: Identifier, @@ -51,6 +61,10 @@ pub enum DocumentTask { qualified_identity: QualifiedIdentity, identity_key: IdentityPublicKey, token_payment_info: Option, + /// The document action fee the user was shown and agreed to (protocol + /// version 14). Required when the document type charges a fee for + /// the action: the backend never agrees on the user's behalf. + action_fee_agreement: Option, }, ReplaceDocument { document: Document, @@ -59,6 +73,10 @@ pub enum DocumentTask { qualified_identity: QualifiedIdentity, identity_key: IdentityPublicKey, token_payment_info: Option, + /// The document action fee the user was shown and agreed to (protocol + /// version 14). Required when the document type charges a fee for + /// the action: the backend never agrees on the user's behalf. + action_fee_agreement: Option, }, TransferDocument { document_id: Identifier, @@ -68,6 +86,10 @@ pub enum DocumentTask { qualified_identity: QualifiedIdentity, identity_key: IdentityPublicKey, token_payment_info: Option, + /// The document action fee the user was shown and agreed to (protocol + /// version 14). Required when the document type charges a fee for + /// the action: the backend never agrees on the user's behalf. + action_fee_agreement: Option, }, PurchaseDocument { price: Credits, @@ -77,6 +99,10 @@ pub enum DocumentTask { qualified_identity: QualifiedIdentity, identity_key: IdentityPublicKey, token_payment_info: Option, + /// The document action fee the user was shown and agreed to (protocol + /// version 14). Required when the document type charges a fee for + /// the action: the backend never agrees on the user's behalf. + action_fee_agreement: Option, }, SetDocumentPrice { price: Credits, @@ -86,6 +112,10 @@ pub enum DocumentTask { qualified_identity: QualifiedIdentity, identity_key: IdentityPublicKey, token_payment_info: Option, + /// The document action fee the user was shown and agreed to (protocol + /// version 14). Required when the document type charges a fee for + /// the action: the backend never agrees on the user's behalf. + action_fee_agreement: Option, }, FetchDocuments(DocumentQuery), FetchDocumentsPage(DocumentQuery), @@ -133,6 +163,22 @@ impl AppContext { &self, task: DocumentTask, sdk: &Sdk, + ) -> Result { + match self.run_document_task_inner(task, sdk).await { + // The multiplier the refusal names is unproven node data: it only + // triggers a proved epoch refresh, never feeds the cache itself. + Err(refusal @ TaskError::DocumentActionFeeMultiplierRose { .. }) => { + let refreshed = self.refresh_current_epoch(sdk).await.map(|_| ()); + Err(fee_refusal_after_refresh(refusal, refreshed)) + } + result => result, + } + } + + async fn run_document_task_inner( + &self, + task: DocumentTask, + sdk: &Sdk, ) -> Result { match task { DocumentTask::FetchDocuments(document_query) => await_network_request_with_timeout( @@ -192,6 +238,7 @@ impl AppContext { data_contract, qualified_identity, identity_key, + action_fee_agreement, } => { let contest_fund = crate::model::fee_estimation::document_create_contest_fund_cap( document_type.as_ref(), @@ -219,6 +266,15 @@ impl AppContext { if let Some(options) = maybe_options { builder = builder.with_state_transition_creation_options(options); } + // After the options: setting them replaces the struct the + // agreement is kept in. + if let Some(agreement) = checked_action_fee_agreement( + document_type.as_ref(), + DocumentTransitionActionType::Create, + action_fee_agreement, + )? { + builder = builder.with_action_fee_agreement(agreement); + } let result = sdk .document_create(builder, &identity_key, &qualified_identity) @@ -241,6 +297,7 @@ impl AppContext { qualified_identity, identity_key, token_payment_info, + action_fee_agreement, } => { let mut builder = DocumentDeleteTransitionBuilder::new( data_contract, @@ -257,6 +314,15 @@ impl AppContext { if let Some(options) = maybe_options { builder = builder.with_state_transition_creation_options(options); } + // After the options: setting them replaces the struct the + // agreement is kept in. + if let Some(agreement) = checked_action_fee_agreement( + document_type.as_ref(), + DocumentTransitionActionType::Delete, + action_fee_agreement, + )? { + builder = builder.with_action_fee_agreement(agreement); + } let result = sdk .document_delete(builder, &identity_key, &qualified_identity) @@ -281,6 +347,7 @@ impl AppContext { qualified_identity, identity_key, token_payment_info, + action_fee_agreement, } => { let mut builder = DocumentReplaceTransitionBuilder::new( data_contract, @@ -296,6 +363,15 @@ impl AppContext { if let Some(options) = maybe_options { builder = builder.with_state_transition_creation_options(options); } + // After the options: setting them replaces the struct the + // agreement is kept in. + if let Some(agreement) = checked_action_fee_agreement( + document_type.as_ref(), + DocumentTransitionActionType::Replace, + action_fee_agreement, + )? { + builder = builder.with_action_fee_agreement(agreement); + } let result = sdk .document_replace(builder, &identity_key, &qualified_identity) @@ -321,6 +397,7 @@ impl AppContext { qualified_identity, identity_key, token_payment_info, + action_fee_agreement, } => { let document = self .fetch_document_for_mutation( @@ -346,6 +423,15 @@ impl AppContext { if let Some(options) = maybe_options { builder = builder.with_state_transition_creation_options(options); } + // After the options: setting them replaces the struct the + // agreement is kept in. + if let Some(agreement) = checked_action_fee_agreement( + document_type.as_ref(), + DocumentTransitionActionType::Transfer, + action_fee_agreement, + )? { + builder = builder.with_action_fee_agreement(agreement); + } let result = sdk .document_transfer(builder, &identity_key, &qualified_identity) @@ -371,6 +457,7 @@ impl AppContext { qualified_identity, identity_key, token_payment_info, + action_fee_agreement, } => { let document = self .fetch_document_for_mutation( @@ -397,6 +484,15 @@ impl AppContext { if let Some(options) = maybe_options { builder = builder.with_state_transition_creation_options(options); } + // After the options: setting them replaces the struct the + // agreement is kept in. + if let Some(agreement) = checked_action_fee_agreement( + document_type.as_ref(), + DocumentTransitionActionType::Purchase, + action_fee_agreement, + )? { + builder = builder.with_action_fee_agreement(agreement); + } let result = sdk .document_purchase(builder, &identity_key, &qualified_identity) @@ -422,6 +518,7 @@ impl AppContext { qualified_identity, identity_key, token_payment_info, + action_fee_agreement, } => { let document = self .fetch_document_for_mutation( @@ -447,6 +544,15 @@ impl AppContext { if let Some(options) = maybe_options { builder = builder.with_state_transition_creation_options(options); } + // After the options: setting them replaces the struct the + // agreement is kept in. + if let Some(agreement) = checked_action_fee_agreement( + document_type.as_ref(), + DocumentTransitionActionType::UpdatePrice, + action_fee_agreement, + )? { + builder = builder.with_action_fee_agreement(agreement); + } let result = sdk .document_set_price(builder, &identity_key, &qualified_identity) @@ -468,8 +574,78 @@ impl AppContext { } } +/// The error to report for a fee multiplier refusal once the proved epoch +/// refresh it triggered has finished: the refusal itself when the cache now +/// holds the network's multiplier, otherwise a variant saying the contract +/// fee could not be updated (the cache keeps its previous value). +fn fee_refusal_after_refresh( + refusal: TaskError, + refreshed: Result<(), Box>, +) -> TaskError { + match (refusal, refreshed) { + (refusal, Ok(())) => refusal, + ( + TaskError::DocumentActionFeeMultiplierRose { + increase_tolerance_percent, + source_error, + .. + }, + Err(refresh_error), + ) => { + tracing::warn!( + refusal = ?source_error, + "Network refused a document action for a risen fee multiplier" + ); + TaskError::DocumentActionFeeMultiplierNotRefreshed { + increase_tolerance_percent, + source_error: refresh_error, + } + } + (other, Err(_)) => other, + } +} + #[cfg(test)] mod tests { + fn fee_refusal() -> TaskError { + TaskError::DocumentActionFeeMultiplierRose { + known_fee_multiplier_permille: 1000, + current_fee_multiplier_permille: 1500, + increase_tolerance_percent: 20, + source_error: Box::new(dash_sdk::Error::Generic("rose".to_string())), + } + } + + /// After a proved refresh the refusal is reported as is: the cache holds + /// the network's multiplier, so trying again quotes the current fee. + #[test] + fn a_fee_refusal_stands_once_the_epoch_is_refreshed() { + let error = fee_refusal_after_refresh(fee_refusal(), Ok(())); + assert!(matches!( + error, + TaskError::DocumentActionFeeMultiplierRose { .. } + )); + assert!(error.to_string().contains("has been updated")); + } + + /// When the proved refresh fails, the user is told the contract fee + /// could not be updated rather than that it was. + #[test] + fn a_failed_epoch_refresh_says_the_fee_was_not_updated() { + let error = fee_refusal_after_refresh( + fee_refusal(), + Err(Box::new(dash_sdk::Error::Generic("offline".to_string()))), + ); + assert!(matches!( + error, + TaskError::DocumentActionFeeMultiplierNotRefreshed { + increase_tolerance_percent: 20, + .. + } + )); + assert!(error.to_string().contains("could not be updated")); + } + use super::*; #[tokio::test] diff --git a/src/backend_task/platform_info.rs b/src/backend_task/platform_info.rs index 16ad8cc3a..6d6ee212e 100644 --- a/src/backend_task/platform_info.rs +++ b/src/backend_task/platform_info.rs @@ -565,8 +565,8 @@ fn build_withdrawals_result( impl AppContext { /// Fetches the current epoch — authenticated by proof — and adopts its /// fee multiplier and protocol version. The only path by which the fee - /// multiplier cache takes a network value, and fee estimates follow it, - /// so it must never come from an unproven source. + /// multiplier cache changes: document action fee agreements are signed + /// against it, so it must never come from an unproven source. pub(crate) async fn refresh_current_epoch( &self, sdk: &Sdk, diff --git a/src/backend_task/protocol_13_transitions.rs b/src/backend_task/protocol_13_transitions.rs index 5811df3f0..a1bca521f 100644 --- a/src/backend_task/protocol_13_transitions.rs +++ b/src/backend_task/protocol_13_transitions.rs @@ -11,6 +11,8 @@ use dash_sdk::dpp::dashcore::Network; use dash_sdk::dpp::data_contract::accessors::v0::DataContractV0Getters; use dash_sdk::dpp::data_contract::config::DataContractConfig; use dash_sdk::dpp::data_contract::document_type::DocumentType; +use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::DocumentActionFeeAgreement; +use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::v0::DocumentActionFeeAgreementV0; use dash_sdk::dpp::document::{Document, DocumentV0}; use dash_sdk::dpp::identity::accessors::IdentityGettersV0; use dash_sdk::dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; @@ -234,3 +236,27 @@ async fn a_document_is_created_in_the_protocol_13_encoding() { "protocol 13 cannot decode {base:?}" ); } + +/// A fee agreement cannot be encoded for a protocol 13 network: building +/// fails locally instead of producing a transition every node rejects. +#[tokio::test] +async fn a_fee_agreement_is_refused_on_protocol_13() { + let (_tmp, _ctx, platform_version) = mainnet_context(); + let options = StateTransitionCreationOptions { + action_fee_agreement: Some(DocumentActionFeeAgreement::V0( + DocumentActionFeeAgreementV0 { + owner: 5, + moderators: 0, + fee_multiplier: None, + }, + )), + ..Default::default() + }; + + assert!( + options + .validate_base_carries_action_fee_agreement(platform_version) + .is_err() + ); + assert!(create_note(platform_version, Some(options)).await.is_err()); +} diff --git a/src/context/mod.rs b/src/context/mod.rs index 421fc3c91..e52da9c44 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1182,7 +1182,9 @@ impl AppContext { batch_feature_version: None, method_feature_version: None, base_feature_version: None, - // Signing overrides only; DET agrees to no document action fee. + // Signing overrides only. A document action fee agreement is + // per transition: `backend_task::document` adds it after these + // options, from the contract the user was shown. action_fee_agreement: None, }) } else { diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index 53deabbfb..a82b10aa3 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -19,7 +19,6 @@ use dash_sdk::dpp::address_funds::{AddressFundsFeeStrategyStep, PlatformAddress} use dash_sdk::dpp::balances::credits::{CREDITS_PER_DUFF, Credits}; use dash_sdk::dpp::identity::core_script::CoreScript; use dash_sdk::dpp::prelude::{AddressNonce, AssetLockProof}; -use dash_sdk::dpp::state_transition::StateTransitionEstimatedFeeValidation; use dash_sdk::dpp::state_transition::address_credit_withdrawal_transition::AddressCreditWithdrawalTransition; use dash_sdk::dpp::state_transition::address_credit_withdrawal_transition::v0::AddressCreditWithdrawalTransitionV0; use dash_sdk::dpp::state_transition::address_funding_from_asset_lock_transition::v0::AddressFundingFromAssetLockTransitionV0; @@ -54,6 +53,16 @@ pub fn document_create_contest_fund_cap( pub const fn max_spendable_credits(balance: u64, estimated_fee: u64) -> u64 { balance.saturating_sub(estimated_fee) } +use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; +use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; +use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::{ + AgreedFeeMultiplier, DocumentActionFeeAgreement, +}; +use dash_sdk::dpp::prelude::FeeMultiplier; +use dash_sdk::dpp::state_transition::{ + StateTransitionEstimatedFeeValidation, + batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType, +}; use dash_sdk::dpp::version::PlatformVersion; use dash_sdk::dpp::withdrawal::Pooling; use std::collections::BTreeMap; @@ -1350,6 +1359,298 @@ pub fn shield_from_balance_fee_headroom( base_fee.saturating_mul(multiplier) / 1000 } +/// How far above the fee multiplier the user saw a document action fee may be +/// priced when it executes, in percent: a transition signed just before an +/// epoch boundary is not refused for a small move. Platform refuses the action +/// when the executing epoch's multiplier is higher still, so the user never +/// pays more than [`DocumentActionFeeQuote::max_total`]. +pub const ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT: u16 = 20; + +/// What a document action charges on top of the gas, as a document type +/// declares it (protocol version 14 `actionFees`), and the agreement the +/// transition must carry to be accepted. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct DocumentActionFeeQuote { + /// The agreement to sign: the declared amounts and, for a fee priced by + /// the fee multiplier, the multiplier the user saw plus the tolerance. + pub agreement: DocumentActionFeeAgreement, + /// The part going to the contract owner, priced at the multiplier the + /// user saw. + pub owner: Credits, + /// The part going to the contract's moderators, priced at the multiplier + /// the user saw. + pub moderators: Credits, + /// The whole fee at the multiplier the user saw. + pub total: Credits, + /// The most the fee can be when the action executes: at the highest + /// multiplier the agreement tolerates, or the declared amount for a fixed + /// fee. + pub max_total: Credits, +} + +/// The action fee `document_type` charges for `action` at the epoch fee +/// multiplier `fee_multiplier_permille`, or `None` when it charges nothing +/// (always, before protocol version 14). +pub fn document_action_fee_quote( + document_type: DocumentTypeRef<'_>, + action: DocumentTransitionActionType, + fee_multiplier_permille: u64, +) -> Option { + let fees = document_type.action_fees()?; + let declared = fees.action_fee(action)?; + let pricing = fees.pricing(); + let known_permille: FeeMultiplier = fee_multiplier_permille; + let agreement = DocumentActionFeeAgreement::for_declared_fee( + pricing, + declared, + AgreedFeeMultiplier { + known_permille, + increase_tolerance_percent: ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT, + }, + ); + // `charged` saturates at the maximum credits rather than overflowing, so + // it cannot fail; a fee that large is refused by Platform as unaffordable. + let now = declared + .charged(pricing, known_permille) + .unwrap_or(declared); + let highest_permille = known_permille + .saturating_mul(100 + u64::from(ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT)) + / 100; + let at_most = declared + .charged(pricing, highest_permille) + .unwrap_or(declared); + Some(DocumentActionFeeQuote { + agreement, + owner: now.owner, + moderators: now.moderators, + total: now.saturating_total(), + max_total: at_most.saturating_total(), + }) +} + +/// Why a document action cannot carry the fee agreement it was given. +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +pub enum ActionFeeAgreementError { + /// The document type charges a fee for the action and no agreement was + /// given: the user never confirmed it. + #[error( + "This contract charges a fee for this action, and you have not confirmed it yet. Try again and confirm the contract fee when asked." + )] + NotConfirmed, + /// The agreement names another fee than the document type declares, so + /// the contract changed after the user confirmed. + #[error( + "The contract fee for this action changed after you confirmed it. Try again to see and confirm the current fee." + )] + Outdated, +} + +/// The fee agreement a document action may carry: exactly the one the user +/// confirmed (`agreed`), checked against what `document_type` declares for +/// `action`. A charged fee without an agreement is refused — the agreement +/// is never derived on the user's behalf — and so is an agreement to another +/// fee. A type that charges nothing for the action carries none. +pub fn checked_action_fee_agreement( + document_type: DocumentTypeRef<'_>, + action: DocumentTransitionActionType, + agreed: Option, +) -> Result, ActionFeeAgreementError> { + let declared = document_type + .action_fees() + .and_then(|fees| fees.action_fee(action).map(|fee| (fees.pricing(), fee))); + match (declared, agreed) { + (None, _) => Ok(None), + (Some(_), None) => Err(ActionFeeAgreementError::NotConfirmed), + (Some((pricing, fee)), Some(agreement)) if agreement.matches_declared(pricing, fee) => { + Ok(Some(agreement)) + } + (Some(_), Some(_)) => Err(ActionFeeAgreementError::Outdated), + } +} + +#[cfg(test)] +mod action_fee_tests { + use super::*; + use dash_sdk::dpp::data_contract::config::DataContractConfig; + use dash_sdk::dpp::data_contract::document_type::DocumentType; + use dash_sdk::dpp::platform_value::{Identifier, Value, platform_value}; + + /// A document type declaring `action_fees`, parsed as Platform parses it. + fn document_type_with(action_fees: Option) -> DocumentType { + let pv = PlatformVersion::latest(); + let mut schema = platform_value!({ + "type": "object", + "properties": {"a": {"type": "string", "position": 0, "maxLength": 60_u32}}, + "additionalProperties": false, + }); + if let Some(action_fees) = action_fees { + schema + .insert("actionFees".to_string(), action_fees) + .expect("a map schema"); + } + let config = DataContractConfig::default_for_version(pv).expect("a default config"); + DocumentType::try_from_schema( + Identifier::new([1; 32]), + 1, + config.version(), + "post", + schema, + None, + &BTreeMap::new(), + &config, + true, + &mut Vec::new(), + pv, + ) + .expect("the document type parses") + } + + /// A charged fee is never agreed on the user's behalf. + #[test] + fn a_charged_fee_without_an_agreement_is_refused() { + let doc_type = document_type_with(Some(platform_value!({"create": {"owner": 5_u64}}))); + assert_eq!( + checked_action_fee_agreement( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + None + ), + Err(ActionFeeAgreementError::NotConfirmed) + ); + } + + #[test] + fn the_confirmed_agreement_is_carried_as_is() { + let doc_type = document_type_with(Some(platform_value!({"create": {"owner": 5_u64}}))); + let agreed = document_action_fee_quote( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + 1000, + ) + .expect("create is priced") + .agreement; + assert_eq!( + checked_action_fee_agreement( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + Some(agreed) + ), + Ok(Some(agreed)) + ); + } + + /// An agreement to another fee means the contract changed since the + /// user confirmed: refused before signing, not sent to be refused. + #[test] + fn an_agreement_to_another_fee_is_outdated() { + let before = document_type_with(Some(platform_value!({"create": {"owner": 5_u64}}))); + let after = document_type_with(Some(platform_value!({"create": {"owner": 9_u64}}))); + let agreed = + document_action_fee_quote(before.as_ref(), DocumentTransitionActionType::Create, 1000) + .expect("create is priced") + .agreement; + assert_eq!( + checked_action_fee_agreement( + after.as_ref(), + DocumentTransitionActionType::Create, + Some(agreed) + ), + Err(ActionFeeAgreementError::Outdated) + ); + } + + #[test] + fn an_uncharged_action_carries_no_agreement() { + let doc_type = document_type_with(Some(platform_value!({"delete": {"owner": 5_u64}}))); + assert_eq!( + checked_action_fee_agreement( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + None + ), + Ok(None) + ); + } + + #[test] + fn a_document_type_without_action_fees_quotes_nothing() { + let doc_type = document_type_with(None); + assert_eq!( + document_action_fee_quote( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + 1000 + ), + None + ); + } + + #[test] + fn an_action_the_type_does_not_price_quotes_nothing() { + let doc_type = document_type_with(Some(platform_value!({"delete": {"owner": 5_u64}}))); + assert_eq!( + document_action_fee_quote( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + 1000 + ), + None + ); + } + + #[test] + fn a_multiplier_priced_fee_scales_and_names_the_tolerance() { + let doc_type = document_type_with(Some(platform_value!({ + "create": {"owner": 10_000_000_u64, "moderators": 0_u64}, + }))); + let quote = document_action_fee_quote( + doc_type.as_ref(), + DocumentTransitionActionType::Create, + 1500, + ) + .expect("create is priced"); + + assert_eq!(quote.owner, 15_000_000, "1.5x the declared owner part"); + assert_eq!(quote.moderators, 0); + assert_eq!(quote.total, 15_000_000); + assert_eq!( + quote.max_total, 18_000_000, + "the tolerated 20% above the multiplier the user saw" + ); + assert_eq!(quote.agreement.owner(), 10_000_000, "declared, not scaled"); + let terms = quote + .agreement + .fee_multiplier() + .expect("a multiplier-priced fee names its terms"); + assert_eq!(terms.known_permille, 1500); + assert_eq!( + terms.increase_tolerance_percent, + ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT + ); + } + + #[test] + fn a_fixed_fee_is_charged_as_declared() { + let doc_type = document_type_with(Some(platform_value!({ + "pricing": "fixed", + "transfer": {"owner": 7_000_u64}, + }))); + let quote = document_action_fee_quote( + doc_type.as_ref(), + DocumentTransitionActionType::Transfer, + 3000, + ) + .expect("transfer is priced"); + + assert_eq!(quote.total, 7_000); + assert_eq!( + quote.max_total, 7_000, + "a fixed fee does not follow the multiplier" + ); + assert_eq!(quote.agreement.fee_multiplier(), None); + } +} + #[cfg(test)] mod tests { use super::*; From d5198aad0807fad0133d1fd0d206302c5f1d6838 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:09:52 +0000 Subject: [PATCH 2/6] fix(errors): explain document action fee refusals Map a missing or mismatched fee agreement, a changed contract fee and a multiplier risen past the tolerance to dedicated TaskError variants, plus one for a multiplier that could not be refreshed. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- src/backend_task/error.rs | 150 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index 60d509a76..a016c7bfc 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -2564,6 +2564,62 @@ pub enum TaskError { // ────────────────────────────────────────────────────────────────────────── // Document action fees, moderation and gas sponsorship (protocol version 14) // ────────────────────────────────────────────────────────────────────────── + /// A document action's fee agreement is missing or names another fee + /// than the document type declares; refused before anything is signed. + #[error(transparent)] + ActionFeeAgreement { + #[from] + source: crate::model::fee_estimation::ActionFeeAgreementError, + }, + + /// The document type charges an action fee and the transition carried no + /// agreement to it. + #[error( + "This contract charges a fee for this action, and the request did not include your agreement to it. Try again and confirm the contract fee when asked." + )] + DocumentActionFeeNotAgreed { + #[source] + source_error: Box, + }, + + /// The fee the transition agreed to differs from the one the document + /// type declares, typically because the contract changed meanwhile. + #[error( + "The contract fee for this action is not the one you agreed to, because the contract changed. Reload the contract to see its current fee, then try again." + )] + DocumentActionFeeChanged { + #[source] + source_error: Box, + }, + + /// Network fees rose past the increase the fee agreement tolerates. + /// Reported only after a proved epoch refresh updated the cached fee + /// multiplier; the node-reported multipliers here are unproven and are + /// never adopted (see `DocumentActionFeeMultiplierNotRefreshed`). + #[error( + "Network fees rose by more than {increase_tolerance_percent}% since you confirmed the contract fee, so the network refused the action. The contract fee has been updated to the current network fees. Try again to see and confirm the new amount." + )] + DocumentActionFeeMultiplierRose { + known_fee_multiplier_permille: u64, + current_fee_multiplier_permille: u64, + increase_tolerance_percent: u16, + #[source] + source_error: Box, + }, + + /// A document action was refused because network fees rose, and the + /// proved refresh of the current fees failed, so the cached fee + /// multiplier (and the next quote) keeps its previous value. + #[error( + "Network fees rose by more than {increase_tolerance_percent}% since you confirmed the contract fee, so the network refused the action. The current network fees could not be loaded, so the contract fee could not be updated. Check your connection, wait a moment, and then try again." + )] + DocumentActionFeeMultiplierNotRefreshed { + increase_tolerance_percent: u16, + /// Why the proved epoch refresh failed. + #[source] + source_error: Box, + }, + /// The identity is banned on the contract. #[error( "This identity is banned from contract {} and cannot act on its documents. Use a different identity for this contract.", @@ -4552,6 +4608,33 @@ impl From for TaskError { } })) } + ConsensusError::StateError( + StateError::DocumentActionFeeAgreementNotSetError(_), + ) => Some(Box::new(|source_error| { + TaskError::DocumentActionFeeNotAgreed { source_error } + })), + ConsensusError::StateError( + StateError::DocumentActionFeeAgreementMismatchError(_), + ) => Some(Box::new(|source_error| { + TaskError::DocumentActionFeeChanged { source_error } + })), + ConsensusError::StateError( + StateError::DocumentActionFeeMultiplierNotToleratedError(e), + ) => { + let (known, current, tolerance) = ( + e.known_fee_multiplier_permille(), + e.current_fee_multiplier_permille(), + e.increase_tolerance_percent(), + ); + Some(Box::new(move |source_error| { + TaskError::DocumentActionFeeMultiplierRose { + known_fee_multiplier_permille: known, + current_fee_multiplier_permille: current, + increase_tolerance_percent: tolerance, + source_error, + } + })) + } ConsensusError::StateError(StateError::ContractUserBannedError(e)) => { let (contract_id, identity_id) = (e.contract_id(), e.identity_id()); Some(Box::new(move |source_error| { @@ -7107,6 +7190,9 @@ mod tests { ContractUserBannedError, ContractUserSuspendedError, }; use dash_sdk::dpp::consensus::state::document::{ + document_action_fee_agreement_mismatch_error::DocumentActionFeeAgreementMismatchError, + document_action_fee_agreement_not_set_error::DocumentActionFeeAgreementNotSetError, + document_action_fee_multiplier_not_tolerated_error::DocumentActionFeeMultiplierNotToleratedError, document_immutable_property_changed_error::DocumentImmutablePropertyChangedError, referenced_document_type_not_deletable_error::ReferencedDocumentTypeNotDeletableError, }; @@ -7115,9 +7201,32 @@ mod tests { use dash_sdk::dpp::consensus::state::token::{ GasFeesPaidByNotAllowedError, InconsistentGasFeesPaidByInBatchError, }; + use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::{ + AgreedFeeMultiplier, DocumentActionFeeAgreement, + }; + use dash_sdk::dpp::data_contract::document_type::action_fees::{ + ActionFeePricing, DocumentActionFee, + }; use dash_sdk::dpp::tokens::gas_fees_paid_by::GasFeesPaidBy; let (contract_id, identity_id) = (Identifier::random(), Identifier::random()); + let fee = DocumentActionFee { + owner: 1_000, + moderators: 0, + }; + let agreed = AgreedFeeMultiplier { + known_permille: 1000, + increase_tolerance_percent: 20, + }; + let agreement = DocumentActionFeeAgreement::for_declared_fee( + ActionFeePricing::FeeMultiplier, + DocumentActionFee { + owner: 900, + moderators: 0, + }, + agreed, + ); + type Expectation = fn(&TaskError) -> bool; let cases: Vec<(ConsensusError, Expectation)> = vec![ (PublicKeyExpiredError::new(3, 1_000, 2_000).into(), |e| { @@ -7159,6 +7268,47 @@ mod tests { TaskError::SigningKeyContractBoundForNonBatch { key_id: 7, .. } ) }), + ( + DocumentActionFeeAgreementNotSetError::new( + "note".to_string(), + "create".to_string(), + ActionFeePricing::FeeMultiplier, + fee, + ) + .into(), + |e| matches!(e, TaskError::DocumentActionFeeNotAgreed { .. }), + ), + ( + DocumentActionFeeAgreementMismatchError::new( + "note".to_string(), + "create".to_string(), + ActionFeePricing::FeeMultiplier, + fee, + &agreement, + ) + .into(), + |e| matches!(e, TaskError::DocumentActionFeeChanged { .. }), + ), + ( + DocumentActionFeeMultiplierNotToleratedError::new( + "note".to_string(), + "create".to_string(), + agreed, + 1_500, + ) + .into(), + |e| { + matches!( + e, + TaskError::DocumentActionFeeMultiplierRose { + known_fee_multiplier_permille: 1000, + current_fee_multiplier_permille: 1_500, + increase_tolerance_percent: 20, + .. + } + ) + }, + ), ( ContractUserBannedError::new(contract_id, identity_id).into(), |e| matches!(e, TaskError::ContractUserBanned { .. }), From 2acab6b9111211e4b4acc1dcdeb32237d0090822 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:09:52 +0000 Subject: [PATCH 3/6] feat(ui): confirm document action fees and send exactly the confirmed action The estimated-fee panel shows the contract fee split between owner and moderators. Sending asks for confirmation naming the fee, the ceiling and the tolerance (or that the fee is fixed); confirming sends the action built when the dialog opened. An optional token cost can be skipped, the gas then being paid in credits. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../document_action_screen.rs | 476 ++++++++++++++---- 1 file changed, 389 insertions(+), 87 deletions(-) diff --git a/src/ui/contracts_documents/document_action_screen.rs b/src/ui/contracts_documents/document_action_screen.rs index 81715eec5..28ad81a61 100644 --- a/src/ui/contracts_documents/document_action_screen.rs +++ b/src/ui/contracts_documents/document_action_screen.rs @@ -4,11 +4,17 @@ use crate::backend_task::FeeResult; use crate::backend_task::{BackendTask, document::DocumentTask}; use crate::context::AppContext; use crate::model::fee_estimation::format_credits_as_dash; +use crate::model::fee_estimation::{ + ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT, DocumentActionFeeQuote, + document_action_fee_quote, +}; use crate::model::identity_key_usability::{KeyRequirements, SigningScope}; use crate::model::qualified_contract::QualifiedContract; use crate::model::qualified_identity::QualifiedIdentity; use crate::model::wallet::Wallet; use crate::ui::ScreenLike; +use crate::ui::components::Component; +use crate::ui::components::confirmation_dialog::{ConfirmationDialog, ConfirmationStatus}; use crate::ui::components::identity_selector::IdentitySelector; use crate::ui::components::left_panel::add_left_panel; use crate::ui::components::styled::{island_central_panel, styled_text_edit_singleline}; @@ -34,6 +40,7 @@ use dash_sdk::dpp::data_contract::associated_token::token_configuration_conventi use dash_sdk::dpp::data_contract::document_type::accessors::{ DocumentTypeV0Getters, DocumentTypeV1Getters, }; +use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::DocumentActionFeeAgreement; use dash_sdk::dpp::data_contract::document_type::methods::DocumentTypeBasicMethods; use dash_sdk::dpp::data_contract::document_type::{DocumentPropertyType, DocumentType}; use dash_sdk::dpp::document::property_names::PRICE; @@ -46,6 +53,10 @@ use dash_sdk::dpp::tokens::gas_fees_paid_by::GasFeesPaidBy; use dash_sdk::dpp::tokens::token_amount_on_contract_token::DocumentActionTokenEffect; use dash_sdk::dpp::tokens::token_payment_info::TokenPaymentInfo; use dash_sdk::dpp::tokens::token_payment_info::v0::TokenPaymentInfoV0; +use dash_sdk::dpp::{ + state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType, + tokens::token_amount_on_contract_token::DocumentActionTokenCost, +}; use dash_sdk::drive::query::WhereClause; use dash_sdk::platform::{DocumentQuery, Identifier, IdentityPublicKey}; use dash_sdk::query_types::IndexMap; @@ -65,6 +76,19 @@ pub enum DocumentActionType { } impl DocumentActionType { + /// The document transition this action broadcasts, as action fees and + /// token costs are declared per transition type. + fn transition_action(&self) -> DocumentTransitionActionType { + match self { + DocumentActionType::Create => DocumentTransitionActionType::Create, + DocumentActionType::Delete => DocumentTransitionActionType::Delete, + DocumentActionType::Purchase => DocumentTransitionActionType::Purchase, + DocumentActionType::Replace => DocumentTransitionActionType::Replace, + DocumentActionType::SetPrice => DocumentTransitionActionType::UpdatePrice, + DocumentActionType::Transfer => DocumentTransitionActionType::Transfer, + } + } + pub fn display_name(&self) -> &'static str { match self { DocumentActionType::Create => "Create Document", @@ -132,12 +156,28 @@ pub struct DocumentActionScreen { // Banner for in-progress operations refresh_banner: Option, + + /// Whether to pay a document type's optional token cost. Off, the action + /// carries no token payment and its gas is paid in credits instead. + pay_optional_token_cost: bool, + /// The confirmation of a document action fee, open while the user decides. + action_fee_confirmation: Option, + /// The action fee agreement the next built action carries. + agreed_action_fee: Option, } /// Shown when the selected identity holds no key this device can sign the /// chosen document action with. const NO_SIGNING_KEY_NOTICE: &str = "This identity has no key on this device that can sign this action. Add or load a suitable key from the identity's keys, or select another identity."; +/// An open contract fee confirmation and the action it was opened for: the +/// action is built, fee agreement included, when the dialog opens, and that +/// exact action is sent on confirm. +struct PendingActionFeeConfirmation { + dialog: ConfirmationDialog, + task: BackendTask, +} + impl DocumentActionScreen { pub fn new( app_context: Arc, @@ -192,6 +232,9 @@ impl DocumentActionScreen { fetched_documents: IndexMap::new(), completed_fee_result: None, refresh_banner: None, + pay_optional_token_cost: true, + action_fee_confirmation: None, + agreed_action_fee: None, } } @@ -214,6 +257,7 @@ impl DocumentActionScreen { self.wallet_unlock_popup = WalletUnlockPopup::new(); self.wallet_failure = None; self.broadcast_status = BroadcastStatus::NotBroadcasted; + self.action_fee_confirmation = None; self.selected_contract = None; self.selected_document_type = None; self.contract_search.clear(); @@ -901,9 +945,48 @@ impl DocumentActionScreen { )) .color(Color32::DARK_RED), ); + // Protocol version 14: an optional token cost may be left out, the + // action then paying its gas in credits with no sponsorship. + if token_creation_cost.optional { + ui.checkbox( + &mut self.pay_optional_token_cost, + "Pay the token cost", + ) + .on_hover_text( + "Paying the token cost is optional for this action. Without it, you pay the network fee yourself in credits.", + ); + } + } else { + self.pay_optional_token_cost = true; } } + /// The token payment for `cost`, or `None` when there is no cost or the + /// user chose not to pay an optional one. + fn token_payment_for(&self, cost: Option) -> Option { + cost.filter(|cost| !cost.optional || self.pay_optional_token_cost) + .map(|cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: cost.contract_id, + token_contract_position: cost.token_contract_position, + gas_fees_paid_by: cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(cost.token_amount), + }) + }) + } + + /// The action fee the selected document type charges for this action at + /// the current fee multiplier, `None` when it charges none. + fn action_fee_quote(&self) -> Option { + let doc_type = self.selected_document_type.as_ref()?; + document_action_fee_quote( + doc_type.as_ref(), + self.action_type.transition_action(), + self.app_context.fee_multiplier_permille(), + ) + } + fn render_broadcast_button(&mut self, ui: &mut Ui) -> AppAction { let mut action = AppAction::None; @@ -918,6 +1001,8 @@ impl DocumentActionScreen { DocumentActionType::SetPrice => fee_estimator.estimate_document_set_price(), }; + let action_fee = self.action_fee_quote(); + ui.add_space(10.0); let dark_mode = ui.style().visuals.dark_mode; Frame::new() @@ -937,6 +1022,20 @@ impl DocumentActionScreen { .size(14.0), ); }); + if let Some(quote) = &action_fee { + ui.horizontal(|ui| { + ui.label( + RichText::new("Contract fee:") + .color(DashColors::text_secondary(dark_mode)) + .size(14.0), + ); + ui.label( + RichText::new(action_fee_summary(quote)) + .color(DashColors::text_primary(dark_mode)) + .size(14.0), + ); + }); + } }); ui.add_space(10.0); @@ -950,11 +1049,29 @@ impl DocumentActionScreen { }; if ComponentStyles::add_primary_button(ui, button_text).clicked() && self.can_broadcast() { - let task = self.create_document_action(); - if task != BackendTask::None { - self.broadcast_status = BroadcastStatus::Broadcasting; - self.set_fetching_banner(ui.ctx(), "Broadcasting..."); - action = AppAction::BackendTask(task); + match action_fee { + // A contract fee is paid only with the user's explicit + // agreement to the amount shown. + Some(quote) => self.open_action_fee_confirmation(quote), + None => { + self.agreed_action_fee = None; + action = self.dispatch_document_action(ui.ctx()); + } + } + } + + let fee_response = self + .action_fee_confirmation + .as_mut() + .and_then(|pending| pending.dialog.show(ui).inner.dialog_response); + if let Some(response) = fee_response { + match response { + ConfirmationStatus::Confirmed => { + action = self.confirm_action_fee(ui.ctx()); + } + ConfirmationStatus::Canceled => { + self.action_fee_confirmation = None; + } } } @@ -970,6 +1087,52 @@ impl DocumentActionScreen { action } + /// Ask the user to agree to the contract fee `quote` before the action is + /// sent. + /// The action is built now, carrying the quoted agreement, and the dialog + /// blocks the form behind it, so what the user confirms is what is sent. + fn open_action_fee_confirmation(&mut self, quote: DocumentActionFeeQuote) { + self.agreed_action_fee = Some(quote.agreement); + let task = self.create_document_action(); + self.agreed_action_fee = None; + if task == BackendTask::None { + return; + } + self.action_fee_confirmation = Some(PendingActionFeeConfirmation { + dialog: ConfirmationDialog::new( + "Confirm contract fee".to_string(), + action_fee_confirmation_text("e), + ) + .blocks_input(true), + task, + }); + } + + /// The user agreed to the contract fee: send the action the confirmation + /// was opened for. + fn confirm_action_fee(&mut self, ctx: &egui::Context) -> AppAction { + match self.action_fee_confirmation.take() { + Some(pending) => self.dispatch_task(ctx, pending.task), + None => AppAction::None, + } + } + + /// Build and dispatch the document action, carrying the agreed action fee. + fn dispatch_document_action(&mut self, ctx: &egui::Context) -> AppAction { + let task = self.create_document_action(); + self.dispatch_task(ctx, task) + } + + /// Send `task`, a built document action, showing its progress. + fn dispatch_task(&mut self, ctx: &egui::Context, task: BackendTask) -> AppAction { + if task == BackendTask::None { + return AppAction::None; + } + self.broadcast_status = BroadcastStatus::Broadcasting; + self.set_fetching_banner(ctx, "Broadcasting..."); + AppAction::BackendTask(task) + } + /// Resolve the four selections every document action needs — document /// type, contract, identity, and signing key. /// @@ -1025,20 +1188,10 @@ impl DocumentActionScreen { }; let token_payment_info = - doc_type - .document_creation_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost - .token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + self.token_payment_for(doc_type.document_creation_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::BroadcastDocument { + action_fee_agreement: self.agreed_action_fee, document: doc, token_payment_info, entropy, @@ -1068,20 +1221,10 @@ impl DocumentActionScreen { return BackendTask::None; }; - let token_payment_info = - doc_type - .document_deletion_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost.token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + let token_payment_info = self.token_payment_for(doc_type.document_deletion_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::DeleteDocument { + action_fee_agreement: self.agreed_action_fee, document_id, document_type: doc_type.clone(), data_contract: Arc::new(contract.contract.clone()), @@ -1099,20 +1242,10 @@ impl DocumentActionScreen { return BackendTask::None; }; - let token_payment_info = - doc_type - .document_purchase_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost.token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + let token_payment_info = self.token_payment_for(doc_type.document_purchase_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::PurchaseDocument { + action_fee_agreement: self.agreed_action_fee, price: self.fetched_price.unwrap_or(0), document_id, document_type: doc_type.clone(), @@ -1133,20 +1266,10 @@ impl DocumentActionScreen { }; let token_payment_info = - doc_type - .document_replacement_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost - .token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + self.token_payment_for(doc_type.document_replacement_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::ReplaceDocument { + action_fee_agreement: self.agreed_action_fee, document: updated_doc, document_type: doc_type.clone(), data_contract: Arc::new(contract.contract.clone()), @@ -1171,19 +1294,10 @@ impl DocumentActionScreen { }; let token_payment_info = - doc_type - .document_replacement_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost.token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + self.token_payment_for(doc_type.document_replacement_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::ReplaceDocument { + action_fee_agreement: self.agreed_action_fee, document: DocumentV0::default().into(), document_type: doc_type.clone(), data_contract: Arc::new(contract.contract.clone()), @@ -1204,19 +1318,10 @@ impl DocumentActionScreen { }; let token_payment_info = - doc_type - .document_update_price_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost.token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + self.token_payment_for(doc_type.document_update_price_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::SetDocumentPrice { + action_fee_agreement: self.agreed_action_fee, price, document_id, document_type: doc_type.clone(), @@ -1237,20 +1342,10 @@ impl DocumentActionScreen { return BackendTask::None; }; - let token_payment_info = - doc_type - .document_transfer_token_cost() - .map(|token_creation_cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: token_creation_cost.contract_id, - token_contract_position: token_creation_cost.token_contract_position, - gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(token_creation_cost.token_amount), - }) - }); + let token_payment_info = self.token_payment_for(doc_type.document_transfer_token_cost()); BackendTask::DocumentTask(Box::new(DocumentTask::TransferDocument { + action_fee_agreement: self.agreed_action_fee, document_id, new_owner_id: recipient_id, document_type: doc_type.clone(), @@ -2009,9 +2104,63 @@ fn signing_scope<'a>( } } +/// The contract fee as a label value: the total, and its split when both +/// the owner and the moderators receive a part. +fn action_fee_summary(quote: &DocumentActionFeeQuote) -> String { + let total = format_credits_as_dash(quote.total); + match (quote.owner, quote.moderators) { + (_, 0) => format!("{total} to the contract owner"), + (0, _) => format!("{total} to the contract's moderators"), + (owner, moderators) => format!( + "{total} ({owner} to the contract owner, {moderators} to its moderators)", + owner = format_credits_as_dash(owner), + moderators = format_credits_as_dash(moderators) + ), + } +} + +/// The confirmation text for a contract fee, in complete sentences: who +/// receives what, whether the fee follows network fees (and the most it can +/// then reach), and that it comes on top of the network fee. The pricing is +/// read from the agreement itself, so a fee too small to show the tolerance +/// after rounding is still described as following network fees. +fn action_fee_confirmation_text(quote: &DocumentActionFeeQuote) -> String { + let fee = format_credits_as_dash(quote.total); + let recipients = match (quote.owner, quote.moderators) { + (_, 0) => format!( + "This contract charges a fee of {fee} for this action, paid to the contract owner." + ), + (0, _) => format!( + "This contract charges a fee of {fee} for this action, paid to the contract's moderators." + ), + (owner, moderators) => format!( + "This contract charges a fee of {fee} for this action: {owner} to the contract owner and {moderators} to its moderators.", + owner = format_credits_as_dash(owner), + moderators = format_credits_as_dash(moderators) + ), + }; + let pricing = if quote.agreement.fee_multiplier().is_some() { + format!( + "The fee follows network fees. If they rise before the action is processed, up to {max} can be charged. If they rise by more than {percent}%, the network refuses the action.", + max = format_credits_as_dash(quote.max_total), + percent = ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT + ) + } else { + "The fee is fixed and does not change with network fees.".to_string() + }; + format!( + "{recipients} {pricing} It is charged on top of the network fee. Do you want to continue?" + ) +} + #[cfg(test)] mod tests { use super::*; + use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::AgreedFeeMultiplier; + use dash_sdk::dpp::data_contract::document_type::action_fees::{ + ActionFeePricing, DocumentActionFee, + }; + fn editor_document_type(array: bool) -> DocumentType { use dash_sdk::dpp::data_contract::config::DataContractConfig; use dash_sdk::dpp::platform_value::platform_value; @@ -2254,6 +2403,34 @@ mod tests { ); } + fn quote( + pricing: ActionFeePricing, + owner: Credits, + moderators: Credits, + ) -> DocumentActionFeeQuote { + let total = owner + moderators; + let max_total = match pricing { + ActionFeePricing::FeeMultiplier => { + total * (100 + ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT as u64) / 100 + } + ActionFeePricing::Fixed => total, + }; + DocumentActionFeeQuote { + agreement: DocumentActionFeeAgreement::for_declared_fee( + pricing, + DocumentActionFee { owner, moderators }, + AgreedFeeMultiplier { + known_permille: 1000, + increase_tolerance_percent: ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT, + }, + ), + owner, + moderators, + total, + max_total, + } + } + /// Regression: with an identity selected but no key that can sign the /// action, the screen stopped below the identity selector with no word /// of why (the key chooser is behind Advanced Options). @@ -2284,4 +2461,129 @@ mod tests { "the missing key is explained" ); } + + /// Regression: Confirm rebuilt the action from the live form, so an input + /// changed while the fee confirmation was open was signed with the fee + /// agreed for the action shown. What is confirmed is what is sent. + #[test] + fn confirming_a_contract_fee_sends_the_action_it_was_shown_for() { + let dir = tempfile::tempdir().unwrap(); + let context = crate::context::test_support::test_app_context(dir.path()); + let contract = dpns(); + let domain = owned_document_type(&contract, "domain"); + let key = auth_key(1, domain.security_level_requirement(), None); + let mut screen = DocumentActionScreen::new(context, None, DocumentActionType::Delete); + screen.selected_contract = Some(contract); + screen.selected_document_type = Some(domain); + screen.selected_identity = Some(identity_holding(std::slice::from_ref(&key))); + screen.selected_key = Some(key); + let shown = Identifier::new([0x11; 32]); + screen.document_id_input = shown.to_string(Encoding::Base58); + + let quote = quote(ActionFeePricing::Fixed, 1_000, 0); + screen.open_action_fee_confirmation(quote); + // The form behind the dialog changes before the user confirms. + screen.document_id_input = Identifier::new([0x22; 32]).to_string(Encoding::Base58); + + let sent = screen.confirm_action_fee(&egui::Context::default()); + let AppAction::BackendTask(BackendTask::DocumentTask(task)) = sent else { + panic!("the confirmed action is sent, got {sent:?}"); + }; + let DocumentTask::DeleteDocument { + document_id, + action_fee_agreement, + .. + } = *task + else { + panic!("a delete was confirmed"); + }; + assert_eq!(document_id, shown); + assert_eq!(action_fee_agreement, Some(quote.agreement)); + } + + /// The user agrees to the most that can be charged, so the confirmation + /// names that ceiling and the tolerance behind it, not only today's price. + #[test] + fn a_multiplier_priced_fee_confirmation_names_the_ceiling_and_the_tolerance() { + let quote = quote(ActionFeePricing::FeeMultiplier, 100_000_000_000, 0); + let text = action_fee_confirmation_text("e); + assert!( + text.contains(&format!( + "up to {}", + format_credits_as_dash(quote.max_total) + )), + "the ceiling must be shown, got: {text}" + ); + assert!( + text.contains(&format!( + "more than {ACTION_FEE_MULTIPLIER_INCREASE_TOLERANCE_PERCENT}%" + )), + "the tolerance must be shown, got: {text}" + ); + assert!(text.contains(&format_credits_as_dash(quote.total))); + } + + #[test] + fn a_fixed_fee_confirmation_promises_no_increase() { + let quote = quote(ActionFeePricing::Fixed, 50_000_000_000, 0); + let text = action_fee_confirmation_text("e); + assert!(text.contains("The fee is fixed"), "got: {text}"); + assert!( + !text.contains("up to"), + "a fixed fee cannot rise, got: {text}" + ); + } + + /// Rounding can hide the tolerance of a tiny fee (4 credits * 1.2 floors + /// to 4): it still follows network fees and must say so. + #[test] + fn a_tiny_multiplier_priced_fee_is_not_called_fixed() { + let mut quote = quote(ActionFeePricing::FeeMultiplier, 4, 0); + quote.max_total = quote.total; + let text = action_fee_confirmation_text("e); + assert!(text.contains("follows network fees"), "got: {text}"); + assert!(!text.contains("fixed"), "got: {text}"); + } + + #[test] + fn a_fee_for_moderators_only_names_them() { + let quote = quote(ActionFeePricing::Fixed, 0, 7_000); + assert!(action_fee_confirmation_text("e).contains("paid to the contract's moderators")); + assert!(action_fee_summary("e).contains("to the contract's moderators")); + } + + #[test] + fn a_fee_split_with_moderators_names_both_parts() { + let quote = quote( + ActionFeePricing::FeeMultiplier, + 60_000_000_000, + 40_000_000_000, + ); + let summary = action_fee_summary("e); + assert!(summary.contains(&format!( + "{} to the contract owner", + format_credits_as_dash(quote.owner) + ))); + assert!(summary.contains(&format!( + "{} to its moderators", + format_credits_as_dash(quote.moderators) + ))); + } + + /// Action fees and token costs are declared per transition, so every + /// screen action must name the transition it broadcasts. + #[test] + fn every_action_maps_to_its_document_transition() { + use DocumentTransitionActionType as T; + for (action, expected) in [ + (DocumentActionType::Create, T::Create), + (DocumentActionType::Delete, T::Delete), + (DocumentActionType::Purchase, T::Purchase), + (DocumentActionType::Replace, T::Replace), + (DocumentActionType::SetPrice, T::UpdatePrice), + (DocumentActionType::Transfer, T::Transfer), + ] { + assert_eq!(action.transition_action(), expected); + } + } } From d383a841c236375b47ac41d801464b0200623663 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sat, 24 Oct 2026 20:09:52 +0000 Subject: [PATCH 4/6] docs(user-stories): add DOC-010 and DOC-011 for document action fees Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- docs/user-stories.md | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/docs/user-stories.md b/docs/user-stories.md index 156721e72..40fc06552 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1358,6 +1358,24 @@ As a developer, I want to set a price on a document and allow others to purchase --- +### DOC-010: Agree to a contract's fee for a document action [Implemented] +**Persona:** Alex, Priya + +As a user acting on a document whose contract charges a fee, I want to see that fee and agree to it before anything is sent, so that I am never charged more than I accepted. + +- The estimated-fee panel shows the contract fee next to the network fee, split between the contract owner and its moderators. +- Sending asks for confirmation naming the fee and, for a fee that follows network fees, the most that can be charged ("up to N DASH") and the tolerated increase. +- If network fees rise past that tolerance, the network refuses the action; the app updates the fee, and trying again shows the new amount to confirm. +- If the contract changes its fee after confirmation, nothing is sent and the user is asked to confirm the current fee. + +### DOC-011: Skip an optional token cost [Implemented] +**Persona:** Alex, Priya + +As a user, when a document action's token cost is optional, I want to choose not to pay it, so that I can pay the network fee in credits instead. + +- A "Pay the token cost" option appears only when the token cost is optional. +- Without it, the action carries no token payment and its network fee is paid from the identity's credits. + ## Developer and Power Tools (DEV) ### DEV-001: Decode state transitions [Implemented] From 86526c9b3e24d4f9c783d6fcc363bda9970c1cab Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sun, 25 Oct 2026 10:55:30 +0000 Subject: [PATCH 5/6] refactor(documents): keep this branch to document action fees The optional token cost (the "Pay the token cost" option, DOC-011) moves to its own branch, so every document action builds its token payment as before and this branch only adds the contract action fee agreement. The network's refusals of a missing or changed fee agreement now show the same text as the app's own check, which tells the user to reload the contract first, since either way the local copy may be out of date. The fee estimation imports sit in the file's top import block. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- docs/user-stories.md | 10 +- src/backend_task/error.rs | 30 +++- src/model/fee_estimation.rs | 33 +++-- .../document_action_screen.rs | 132 ++++++++++++------ 4 files changed, 129 insertions(+), 76 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index 40fc06552..8314ba7be 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1366,15 +1366,7 @@ As a user acting on a document whose contract charges a fee, I want to see that - The estimated-fee panel shows the contract fee next to the network fee, split between the contract owner and its moderators. - Sending asks for confirmation naming the fee and, for a fee that follows network fees, the most that can be charged ("up to N DASH") and the tolerated increase. - If network fees rise past that tolerance, the network refuses the action; the app updates the fee, and trying again shows the new amount to confirm. -- If the contract changes its fee after confirmation, nothing is sent and the user is asked to confirm the current fee. - -### DOC-011: Skip an optional token cost [Implemented] -**Persona:** Alex, Priya - -As a user, when a document action's token cost is optional, I want to choose not to pay it, so that I can pay the network fee in credits instead. - -- A "Pay the token cost" option appears only when the token cost is optional. -- Without it, the action carries no token payment and its network fee is paid from the identity's credits. +- If the contract changes its fee after confirmation, nothing is sent and the user is asked to reload the contract and confirm its current fee. ## Developer and Power Tools (DEV) diff --git a/src/backend_task/error.rs b/src/backend_task/error.rs index a016c7bfc..daf307b66 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -2574,9 +2574,7 @@ pub enum TaskError { /// The document type charges an action fee and the transition carried no /// agreement to it. - #[error( - "This contract charges a fee for this action, and the request did not include your agreement to it. Try again and confirm the contract fee when asked." - )] + #[error("{}", crate::model::fee_estimation::ActionFeeAgreementError::NotConfirmed)] DocumentActionFeeNotAgreed { #[source] source_error: Box, @@ -2584,9 +2582,7 @@ pub enum TaskError { /// The fee the transition agreed to differs from the one the document /// type declares, typically because the contract changed meanwhile. - #[error( - "The contract fee for this action is not the one you agreed to, because the contract changed. Reload the contract to see its current fee, then try again." - )] + #[error("{}", crate::model::fee_estimation::ActionFeeAgreementError::Outdated)] DocumentActionFeeChanged { #[source] source_error: Box, @@ -7175,6 +7171,28 @@ mod tests { }) } + /// A missing or outdated fee agreement reads the same whether this app or + /// the network refuses it, so the user gets one instruction for each. + #[test] + fn fee_agreement_refusals_read_the_same_locally_and_from_the_network() { + use crate::model::fee_estimation::ActionFeeAgreementError; + let source = || Box::new(SdkError::Generic("refused".to_string())); + assert_eq!( + TaskError::DocumentActionFeeNotAgreed { + source_error: source() + } + .to_string(), + ActionFeeAgreementError::NotConfirmed.to_string() + ); + assert_eq!( + TaskError::DocumentActionFeeChanged { + source_error: source() + } + .to_string(), + ActionFeeAgreementError::Outdated.to_string() + ); + } + /// The protocol-version-14 refusals of signing keys and of contract and /// document authoring map to their own variants, keep the SDK error as /// their source, and read as complete sentences free of protocol jargon. diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index a82b10aa3..c38a88bcc 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -17,8 +17,15 @@ use dash_sdk::dashcore_rpc::dashcore::Address; use dash_sdk::dpp::ProtocolError; use dash_sdk::dpp::address_funds::{AddressFundsFeeStrategyStep, PlatformAddress}; use dash_sdk::dpp::balances::credits::{CREDITS_PER_DUFF, Credits}; +use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; +use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; +use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::{ + AgreedFeeMultiplier, DocumentActionFeeAgreement, +}; use dash_sdk::dpp::identity::core_script::CoreScript; +use dash_sdk::dpp::prelude::FeeMultiplier; use dash_sdk::dpp::prelude::{AddressNonce, AssetLockProof}; +use dash_sdk::dpp::state_transition::StateTransitionEstimatedFeeValidation; use dash_sdk::dpp::state_transition::address_credit_withdrawal_transition::AddressCreditWithdrawalTransition; use dash_sdk::dpp::state_transition::address_credit_withdrawal_transition::v0::AddressCreditWithdrawalTransitionV0; use dash_sdk::dpp::state_transition::address_funding_from_asset_lock_transition::v0::AddressFundingFromAssetLockTransitionV0; @@ -26,11 +33,15 @@ use dash_sdk::dpp::state_transition::address_funding_from_asset_lock_transition: AddressFundingFromAssetLockTransition, calculate_address_funding_from_asset_lock_min_required_fee, }; +use dash_sdk::dpp::state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType; use dash_sdk::dpp::state_transition::identity_create_transition::IdentityCreateTransition; use dash_sdk::dpp::state_transition::identity_create_transition::v0::IdentityCreateTransitionV0; use dash_sdk::dpp::state_transition::identity_topup_transition::IdentityTopUpTransition; use dash_sdk::dpp::state_transition::identity_topup_transition::v0::IdentityTopUpTransitionV0; use dash_sdk::dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; +use dash_sdk::dpp::version::PlatformVersion; +use dash_sdk::dpp::withdrawal::Pooling; +use std::collections::BTreeMap; /// Keep contested document creation within the protocol's base fund, without auto-quoting a larger fund. pub fn document_create_contest_fund_cap( @@ -53,19 +64,6 @@ pub fn document_create_contest_fund_cap( pub const fn max_spendable_credits(balance: u64, estimated_fee: u64) -> u64 { balance.saturating_sub(estimated_fee) } -use dash_sdk::dpp::data_contract::document_type::DocumentTypeRef; -use dash_sdk::dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; -use dash_sdk::dpp::data_contract::document_type::action_fees::agreement::{ - AgreedFeeMultiplier, DocumentActionFeeAgreement, -}; -use dash_sdk::dpp::prelude::FeeMultiplier; -use dash_sdk::dpp::state_transition::{ - StateTransitionEstimatedFeeValidation, - batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType, -}; -use dash_sdk::dpp::version::PlatformVersion; -use dash_sdk::dpp::withdrawal::Pooling; -use std::collections::BTreeMap; /// Maximum number of platform address inputs allowed per state transition. pub(crate) const MAX_PLATFORM_INPUTS: usize = 16; @@ -1429,18 +1427,23 @@ pub fn document_action_fee_quote( } /// Why a document action cannot carry the fee agreement it was given. +/// +/// The network refuses the same two cases +/// (`TaskError::DocumentActionFeeNotAgreed`, `TaskError::DocumentActionFeeChanged`) +/// with this same text. Either way the app's copy of the contract may be +/// out of date, so the instruction is to reload it. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ActionFeeAgreementError { /// The document type charges a fee for the action and no agreement was /// given: the user never confirmed it. #[error( - "This contract charges a fee for this action, and you have not confirmed it yet. Try again and confirm the contract fee when asked." + "This contract charges a fee for this action that you have not agreed to. Reload the contract to see its current fee, then try again and confirm it when asked." )] NotConfirmed, /// The agreement names another fee than the document type declares, so /// the contract changed after the user confirmed. #[error( - "The contract fee for this action changed after you confirmed it. Try again to see and confirm the current fee." + "The contract fee for this action changed after you confirmed it. Reload the contract to see its current fee, then try again." )] Outdated, } diff --git a/src/ui/contracts_documents/document_action_screen.rs b/src/ui/contracts_documents/document_action_screen.rs index 28ad81a61..8b5764872 100644 --- a/src/ui/contracts_documents/document_action_screen.rs +++ b/src/ui/contracts_documents/document_action_screen.rs @@ -53,10 +53,7 @@ use dash_sdk::dpp::tokens::gas_fees_paid_by::GasFeesPaidBy; use dash_sdk::dpp::tokens::token_amount_on_contract_token::DocumentActionTokenEffect; use dash_sdk::dpp::tokens::token_payment_info::TokenPaymentInfo; use dash_sdk::dpp::tokens::token_payment_info::v0::TokenPaymentInfoV0; -use dash_sdk::dpp::{ - state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType, - tokens::token_amount_on_contract_token::DocumentActionTokenCost, -}; +use dash_sdk::dpp::state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType; use dash_sdk::drive::query::WhereClause; use dash_sdk::platform::{DocumentQuery, Identifier, IdentityPublicKey}; use dash_sdk::query_types::IndexMap; @@ -76,8 +73,8 @@ pub enum DocumentActionType { } impl DocumentActionType { - /// The document transition this action broadcasts, as action fees and - /// token costs are declared per transition type. + /// The document transition this action broadcasts, as action fees are + /// declared per transition type. fn transition_action(&self) -> DocumentTransitionActionType { match self { DocumentActionType::Create => DocumentTransitionActionType::Create, @@ -157,9 +154,6 @@ pub struct DocumentActionScreen { // Banner for in-progress operations refresh_banner: Option, - /// Whether to pay a document type's optional token cost. Off, the action - /// carries no token payment and its gas is paid in credits instead. - pay_optional_token_cost: bool, /// The confirmation of a document action fee, open while the user decides. action_fee_confirmation: Option, /// The action fee agreement the next built action carries. @@ -232,7 +226,6 @@ impl DocumentActionScreen { fetched_documents: IndexMap::new(), completed_fee_result: None, refresh_banner: None, - pay_optional_token_cost: true, action_fee_confirmation: None, agreed_action_fee: None, } @@ -945,37 +938,9 @@ impl DocumentActionScreen { )) .color(Color32::DARK_RED), ); - // Protocol version 14: an optional token cost may be left out, the - // action then paying its gas in credits with no sponsorship. - if token_creation_cost.optional { - ui.checkbox( - &mut self.pay_optional_token_cost, - "Pay the token cost", - ) - .on_hover_text( - "Paying the token cost is optional for this action. Without it, you pay the network fee yourself in credits.", - ); - } - } else { - self.pay_optional_token_cost = true; } } - /// The token payment for `cost`, or `None` when there is no cost or the - /// user chose not to pay an optional one. - fn token_payment_for(&self, cost: Option) -> Option { - cost.filter(|cost| !cost.optional || self.pay_optional_token_cost) - .map(|cost| { - TokenPaymentInfo::V0(TokenPaymentInfoV0 { - payment_token_contract_id: cost.contract_id, - token_contract_position: cost.token_contract_position, - gas_fees_paid_by: cost.gas_fees_paid_by, - minimum_token_cost: None, - maximum_token_cost: Some(cost.token_amount), - }) - }) - } - /// The action fee the selected document type charges for this action at /// the current fee multiplier, `None` when it charges none. fn action_fee_quote(&self) -> Option { @@ -1188,7 +1153,18 @@ impl DocumentActionScreen { }; let token_payment_info = - self.token_payment_for(doc_type.document_creation_token_cost()); + doc_type + .document_creation_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost + .token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::BroadcastDocument { action_fee_agreement: self.agreed_action_fee, @@ -1221,7 +1197,18 @@ impl DocumentActionScreen { return BackendTask::None; }; - let token_payment_info = self.token_payment_for(doc_type.document_deletion_token_cost()); + let token_payment_info = + doc_type + .document_deletion_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost.token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::DeleteDocument { action_fee_agreement: self.agreed_action_fee, @@ -1242,7 +1229,18 @@ impl DocumentActionScreen { return BackendTask::None; }; - let token_payment_info = self.token_payment_for(doc_type.document_purchase_token_cost()); + let token_payment_info = + doc_type + .document_purchase_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost.token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::PurchaseDocument { action_fee_agreement: self.agreed_action_fee, @@ -1266,7 +1264,18 @@ impl DocumentActionScreen { }; let token_payment_info = - self.token_payment_for(doc_type.document_replacement_token_cost()); + doc_type + .document_replacement_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost + .token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::ReplaceDocument { action_fee_agreement: self.agreed_action_fee, @@ -1294,7 +1303,17 @@ impl DocumentActionScreen { }; let token_payment_info = - self.token_payment_for(doc_type.document_replacement_token_cost()); + doc_type + .document_replacement_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost.token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::ReplaceDocument { action_fee_agreement: self.agreed_action_fee, @@ -1318,7 +1337,17 @@ impl DocumentActionScreen { }; let token_payment_info = - self.token_payment_for(doc_type.document_update_price_token_cost()); + doc_type + .document_update_price_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost.token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::SetDocumentPrice { action_fee_agreement: self.agreed_action_fee, @@ -1342,7 +1371,18 @@ impl DocumentActionScreen { return BackendTask::None; }; - let token_payment_info = self.token_payment_for(doc_type.document_transfer_token_cost()); + let token_payment_info = + doc_type + .document_transfer_token_cost() + .map(|token_creation_cost| { + TokenPaymentInfo::V0(TokenPaymentInfoV0 { + payment_token_contract_id: token_creation_cost.contract_id, + token_contract_position: token_creation_cost.token_contract_position, + gas_fees_paid_by: token_creation_cost.gas_fees_paid_by, + minimum_token_cost: None, + maximum_token_cost: Some(token_creation_cost.token_amount), + }) + }); BackendTask::DocumentTask(Box::new(DocumentTask::TransferDocument { action_fee_agreement: self.agreed_action_fee, @@ -2570,7 +2610,7 @@ mod tests { ))); } - /// Action fees and token costs are declared per transition, so every + /// Action fees are declared per transition, so every /// screen action must name the transition it broadcasts. #[test] fn every_action_maps_to_its_document_transition() { From e39b29bf6423a75c196c3c584306eaedb5e38b9e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Sun, 25 Oct 2026 11:17:57 +0000 Subject: [PATCH 6/6] fix(errors): name the real way to load a contract's current fee Loading a contract that is already stored keeps the stored copy, so the fee agreement refusals and DOC-010 now tell the user to remove the contract on the Contracts screen and load it again, an action the app offers, instead of an unnamed reload. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- docs/user-stories.md | 2 +- src/model/fee_estimation.rs | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/docs/user-stories.md b/docs/user-stories.md index ab37b26cb..55f559be3 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1366,7 +1366,7 @@ As a user acting on a document whose contract charges a fee, I want to see that - The estimated-fee panel shows the contract fee next to the network fee, split between the contract owner and its moderators. - Sending asks for confirmation naming the fee and, for a fee that follows network fees, the most that can be charged ("up to N DASH") and the tolerated increase. - If network fees rise past that tolerance, the network refuses the action; the app updates the fee, and trying again shows the new amount to confirm. -- If the contract changes its fee after confirmation, nothing is sent and the user is asked to reload the contract and confirm its current fee. +- If the contract changes its fee after confirmation, nothing is sent, and the user is told to remove the contract on the Contracts screen and load it again to see and confirm its current fee. ## Developer and Power Tools (DEV) diff --git a/src/model/fee_estimation.rs b/src/model/fee_estimation.rs index c38a88bcc..40c4ce422 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -1431,19 +1431,21 @@ pub fn document_action_fee_quote( /// The network refuses the same two cases /// (`TaskError::DocumentActionFeeNotAgreed`, `TaskError::DocumentActionFeeChanged`) /// with this same text. Either way the app's copy of the contract may be -/// out of date, so the instruction is to reload it. +/// out of date. Loading a contract that is already stored keeps the stored +/// copy, so the instruction is to remove it on the Contracts screen and load +/// it again. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] pub enum ActionFeeAgreementError { /// The document type charges a fee for the action and no agreement was /// given: the user never confirmed it. #[error( - "This contract charges a fee for this action that you have not agreed to. Reload the contract to see its current fee, then try again and confirm it when asked." + "This contract charges a fee for this action that you have not agreed to. On the Contracts screen, remove the contract and load it again to see its current fee, then try again and confirm the fee when asked." )] NotConfirmed, /// The agreement names another fee than the document type declares, so /// the contract changed after the user confirmed. #[error( - "The contract fee for this action changed after you confirmed it. Reload the contract to see its current fee, then try again." + "The contract fee for this action changed after you confirmed it. On the Contracts screen, remove the contract and load it again to see its current fee, then try again." )] Outdated, }