diff --git a/docs/user-stories.md b/docs/user-stories.md index ba5b1d61d..571a4904d 100644 --- a/docs/user-stories.md +++ b/docs/user-stories.md @@ -1431,6 +1431,16 @@ 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 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) ### DEV-001: Decode state transitions [Implemented] 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/error.rs b/src/backend_task/error.rs index d9c0206a3..c95912c4d 100644 --- a/src/backend_task/error.rs +++ b/src/backend_task/error.rs @@ -2659,6 +2659,58 @@ 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("{}", crate::model::fee_estimation::ActionFeeAgreementError::NotConfirmed)] + 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("{}", crate::model::fee_estimation::ActionFeeAgreementError::Outdated)] + 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.", @@ -4732,6 +4784,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| { @@ -7295,6 +7374,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. @@ -7311,6 +7412,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, }; @@ -7319,9 +7423,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| { @@ -7363,6 +7490,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 { .. }), diff --git a/src/context/mod.rs b/src/context/mod.rs index 1e52f5099..dcb261c49 100644 --- a/src/context/mod.rs +++ b/src/context/mod.rs @@ -1148,7 +1148,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 c7b6f8639..5c350787c 100644 --- a/src/model/fee_estimation.rs +++ b/src/model/fee_estimation.rs @@ -17,7 +17,13 @@ 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; @@ -27,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; use dash_sdk::dpp::version::fee::data_contract_registration::FeeDataContractRegistrationVersion; /// Keep contested document creation within the protocol's base fund, without auto-quoting a larger fund. @@ -55,9 +65,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::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; @@ -1420,6 +1427,305 @@ 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. +/// +/// 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. 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. 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. On the Contracts screen, remove the contract and load it again to see its current fee, then try again." + )] + 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::*; diff --git a/src/ui/contracts_documents/document_action_screen.rs b/src/ui/contracts_documents/document_action_screen.rs index ed0e58420..0f0e1350e 100644 --- a/src/ui/contracts_documents/document_action_screen.rs +++ b/src/ui/contracts_documents/document_action_screen.rs @@ -7,11 +7,17 @@ use crate::backend_task::{BackendTask, document::DocumentTask}; use crate::context::AppContext; use crate::model::document::new_document_for_creation; 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}; @@ -38,6 +44,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::{DocumentPropertyType, DocumentType}; use dash_sdk::dpp::document::property_names::PRICE; use dash_sdk::dpp::document::{Document, DocumentV0, DocumentV0Getters, DocumentV0Setters}; @@ -49,6 +56,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; use dash_sdk::drive::query::WhereClause; use dash_sdk::platform::{DocumentQuery, Identifier, IdentityPublicKey}; use dash_sdk::query_types::IndexMap; @@ -68,6 +76,19 @@ pub enum DocumentActionType { } impl DocumentActionType { + /// 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, + 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", @@ -166,6 +187,10 @@ pub struct DocumentActionScreen { // Banner for in-progress operations refresh_banner: Option, + /// 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, // The document fetch whose result the form waits for pending_fetch: PendingRequest, @@ -178,6 +203,14 @@ pub struct DocumentActionScreen { /// 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, @@ -232,6 +265,8 @@ impl DocumentActionScreen { fetched_documents: IndexMap::new(), completed_fee_result: None, refresh_banner: None, + action_fee_confirmation: None, + agreed_action_fee: None, pending_fetch: PendingRequest::default(), pending_broadcast: PendingRequest::default(), } @@ -346,6 +381,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(); @@ -1021,6 +1057,17 @@ impl DocumentActionScreen { } } + /// 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; @@ -1035,6 +1082,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() @@ -1054,6 +1103,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); @@ -1071,9 +1134,29 @@ impl DocumentActionScreen { if ComponentStyles::add_primary_button_enabled(ui, idle, button_text).clicked() && self.can_broadcast() { - let task = self.create_document_action(); - if task != BackendTask::None { - action = self.start_broadcast(ui.ctx(), 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; + } } } @@ -1089,6 +1172,50 @@ 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.start_broadcast(ctx, task) + } + /// Resolve the four selections every document action needs — document /// type, contract, identity, and signing key. /// @@ -1158,6 +1285,7 @@ impl DocumentActionScreen { }); BackendTask::DocumentTask(Box::new(DocumentTask::BroadcastDocument { + action_fee_agreement: self.agreed_action_fee, document: doc, token_payment_info, entropy, @@ -1209,6 +1337,7 @@ impl DocumentActionScreen { }); 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()), @@ -1240,6 +1369,7 @@ impl DocumentActionScreen { }); 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(), @@ -1274,6 +1404,7 @@ impl DocumentActionScreen { }); 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()), @@ -1311,6 +1442,7 @@ impl DocumentActionScreen { }); 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()), @@ -1344,6 +1476,7 @@ impl DocumentActionScreen { }); BackendTask::DocumentTask(Box::new(DocumentTask::SetDocumentPrice { + action_fee_agreement: self.agreed_action_fee, price, document_id, document_type: doc_type.clone(), @@ -1378,6 +1511,7 @@ impl DocumentActionScreen { }); 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(), @@ -2145,9 +2279,62 @@ 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; @@ -3064,6 +3251,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). @@ -3094,4 +3309,133 @@ 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::BackendTaskWithContext { + task: 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 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); + } + } }