use std::collections::BTreeSet;
use std::fmt;
use chia_protocol::{Bytes32, CoinSpend};
use chia_puzzle_types::standard::StandardArgs;
use chia_wallet_sdk::driver::{Layer, Puzzle, StandardLayer};
use chia_wallet_sdk::puzzles::{SETTLEMENT_PAYMENT_HASH, SINGLETON_LAUNCHER_HASH};
use chia_wallet_sdk::utils::Address;
use clvmr::serde::node_from_bytes;
use clvmr::Allocator;
use dig_wallet_backend::client::{analyze, DecodedOutput, SpendEffect};
use crate::error::{AccountError, Result};
use crate::wallet::policy::CustodyPolicy;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum SpendDestination {
Address,
ProtocolStructure,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct SpendRecipient {
pub address: String,
pub amount_mojos: u64,
pub asset_id: Option<String>,
pub destination: SpendDestination,
}
impl SpendRecipient {
pub fn to_address<A, S>(address: A, amount_mojos: u64, asset_id: Option<S>) -> Self
where
A: Into<String>,
S: Into<String>,
{
Self {
address: address.into(),
amount_mojos,
asset_id: asset_id.map(Into::into),
destination: SpendDestination::Address,
}
}
pub fn to_protocol_structure<A, S>(structure: A, amount_mojos: u64, asset_id: Option<S>) -> Self
where
A: Into<String>,
S: Into<String>,
{
Self {
address: structure.into(),
amount_mojos,
asset_id: asset_id.map(Into::into),
destination: SpendDestination::ProtocolStructure,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SpendTier {
AutoSend,
Confirm,
Vault,
}
impl SpendTier {
pub fn classify(policy: &CustodyPolicy, total_mojos: u64) -> Self {
match policy {
CustodyPolicy::Vault(_) => SpendTier::Vault,
CustodyPolicy::Hot(hot) if total_mojos <= hot.auto_send_limit => SpendTier::AutoSend,
CustodyPolicy::Hot(_) => SpendTier::Confirm,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SpendSummary {
pub tier: SpendTier,
pub recipients: Vec<SpendRecipient>,
pub fee: u64,
pub melted_singletons: Vec<String>,
pub nft_operations: Vec<String>,
}
impl SpendSummary {
pub fn new(tier: SpendTier, recipients: Vec<SpendRecipient>, fee: u64) -> Self {
Self {
tier,
recipients,
fee,
melted_singletons: Vec::new(),
nft_operations: Vec::new(),
}
}
pub fn melting(
tier: SpendTier,
recipients: Vec<SpendRecipient>,
fee: u64,
melted_singletons: Vec<String>,
) -> Self {
Self {
tier,
recipients,
fee,
melted_singletons,
nft_operations: Vec::new(),
}
}
#[must_use]
pub fn with_nft_operations(mut self, nft_operations: Vec<String>) -> Self {
self.nft_operations = nft_operations;
self
}
pub fn destroys_singletons(&self) -> bool {
!self.melted_singletons.is_empty()
}
pub fn moves_nfts(&self) -> bool {
!self.nft_operations.is_empty()
}
pub fn from_coin_spends(coin_spends: &[CoinSpend], tier: SpendTier) -> Result<Self> {
Self::from_effect(&derive_effect(coin_spends)?, coin_spends, tier)
}
pub fn classified(coin_spends: &[CoinSpend], policy: &CustodyPolicy) -> Result<Self> {
Ok(DerivedSpend::derive(coin_spends, policy)?.summary)
}
fn from_effect(
effect: &SpendEffect,
coin_spends: &[CoinSpend],
tier: SpendTier,
) -> Result<Self> {
let returns_to_spender = p2_destinations(coin_spends);
let leaves_to_an_address = effect
.outputs
.iter()
.filter(|output| !returns_to_spender.contains(&output.puzzle_hash))
.map(address_line);
let nft_operations = effect
.nft_operations
.iter()
.map(|operation| {
operation.describe().map_err(|e| {
AccountError::Spend(format!("cannot name an NFT this spend acts on: {e}"))
})
})
.collect::<Result<Vec<_>>>()?;
Ok(Self {
tier,
recipients: leaves_to_an_address
.chain(effect.protocol_sink.iter().map(protocol_structure_line))
.collect(),
fee: effect.fee,
melted_singletons: effect
.melted_singletons
.iter()
.map(|coin_id| hex::encode(coin_id.as_ref()))
.collect(),
nft_operations,
})
}
pub fn native_total_mojos(&self) -> u64 {
self.checked_native_total_mojos().unwrap_or(u64::MAX)
}
pub fn checked_native_total_mojos(&self) -> Result<u64> {
let native_out = self
.recipients
.iter()
.filter(|recipient| recipient.asset_id.is_none())
.try_fold(0u64, |sum, recipient| {
sum.checked_add(recipient.amount_mojos)
})
.ok_or_else(|| Self::unsummable("the native recipient amounts"))?;
native_out
.checked_add(self.fee)
.ok_or_else(|| Self::unsummable("the native recipient amounts plus the fee"))
}
pub fn moves_non_native_assets(&self) -> bool {
self.recipients
.iter()
.any(|recipient| recipient.asset_id.is_some())
}
fn unsummable(what: &str) -> AccountError {
AccountError::PolicyIndeterminate(format!(
"{what} overflow u64, so this spend has no native total to weigh against a limit"
))
}
}
const MOJOS_PER_XCH: u64 = 1_000_000_000_000;
fn format_xch(mojos: u64) -> String {
let whole = mojos / MOJOS_PER_XCH;
let fraction = mojos % MOJOS_PER_XCH;
if fraction == 0 {
return whole.to_string();
}
let digits = format!("{fraction:012}");
format!("{whole}.{}", digits.trim_end_matches('0'))
}
impl fmt::Display for SpendSummary {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:?}: ", self.tier)?;
if self.recipients.is_empty() {
write!(f, "no recipients")?;
} else {
for (i, recipient) in self.recipients.iter().enumerate() {
if i > 0 {
write!(f, ", ")?;
}
match recipient.asset_id.as_deref() {
None => write!(
f,
"{} XCH -> {}",
format_xch(recipient.amount_mojos),
recipient.address
)?,
Some(asset) => write!(
f,
"{} base units of CAT {asset} -> {}",
recipient.amount_mojos, recipient.address
)?,
}
}
}
write!(f, " (fee {} XCH)", format_xch(self.fee))?;
for coin_id in &self.melted_singletons {
write!(f, " — destroys singleton {coin_id} permanently")?;
}
for operation in &self.nft_operations {
write!(f, " — {operation}")?;
}
Ok(())
}
}
pub(crate) fn p2_destinations(coin_spends: &[CoinSpend]) -> BTreeSet<Bytes32> {
let mut allocator = Allocator::new();
let mut destinations = BTreeSet::new();
for spend in coin_spends {
let Ok(puzzle_ptr) = node_from_bytes(&mut allocator, &spend.puzzle_reveal) else {
continue;
};
let puzzle = Puzzle::parse(&allocator, puzzle_ptr);
let Ok(Some(p2)) = StandardLayer::parse_puzzle(&allocator, puzzle) else {
continue;
};
let curried = Bytes32::new(StandardArgs::curry_tree_hash(p2.synthetic_key).to_bytes());
if curried == spend.coin.puzzle_hash {
destinations.insert(spend.coin.puzzle_hash);
}
}
destinations
}
fn address_line(output: &DecodedOutput) -> SpendRecipient {
SpendRecipient::to_address(
Address::new(
output.puzzle_hash,
crate::constants::MAINNET_ADDRESS_PREFIX.to_string(),
)
.encode()
.unwrap_or_else(|_| hex::encode(output.puzzle_hash)),
output.amount,
output.asset_id.map(hex::encode),
)
}
fn protocol_structure_line(output: &DecodedOutput) -> SpendRecipient {
let structure = if output.puzzle_hash == Bytes32::new(SETTLEMENT_PAYMENT_HASH) {
"the offer settlement puzzle".to_string()
} else if output.puzzle_hash == Bytes32::new(SINGLETON_LAUNCHER_HASH) {
"the singleton launcher".to_string()
} else {
format!(
"an unrecognized protocol structure ({})",
hex::encode(output.puzzle_hash)
)
};
SpendRecipient::to_protocol_structure(
structure,
output.amount,
output.asset_id.map(hex::encode),
)
}
fn derive_effect(coin_spends: &[CoinSpend]) -> Result<SpendEffect> {
coin_spends
.iter()
.try_fold(0u64, |sum, spend| sum.checked_add(spend.coin.amount))
.ok_or_else(|| {
AccountError::PolicyIndeterminate(
"the spent coins' amounts do not sum in a u64, so this spend's value cannot be \
accounted for"
.to_string(),
)
})?;
analyze(coin_spends)
.map_err(|e| AccountError::Spend(format!("cannot derive spend summary: {e}")))
}
pub(crate) struct DerivedSpend {
pub(crate) summary: SpendSummary,
pub(crate) native_total_mojos: u64,
}
impl DerivedSpend {
pub(crate) fn derive(coin_spends: &[CoinSpend], policy: &CustodyPolicy) -> Result<Self> {
let effect = derive_effect(coin_spends)?;
let mut summary = SpendSummary::from_effect(&effect, coin_spends, SpendTier::Confirm)?;
let native_total_mojos = summary.checked_native_total_mojos()?;
summary.tier = SpendTier::classify(policy, native_total_mojos);
if summary.tier == SpendTier::AutoSend && summary.moves_non_native_assets() {
summary.tier = SpendTier::Confirm;
}
if summary.tier == SpendTier::AutoSend && summary.destroys_singletons() {
summary.tier = SpendTier::Confirm;
}
if summary.tier == SpendTier::AutoSend && summary.moves_nfts() {
summary.tier = SpendTier::Confirm;
}
Ok(Self {
summary,
native_total_mojos,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::wallet::policy::{HotWallet, Vault};
fn paying(address: &str, amount_mojos: u64, asset_id: Option<&str>) -> SpendRecipient {
SpendRecipient::to_address(address, amount_mojos, asset_id)
}
#[test]
fn a_rendered_destination_is_an_address_the_transfer_builder_will_pay() {
let puzzle_hash = Bytes32::new([0x5C; 32]);
let line = address_line(&decoded_output(puzzle_hash, 600));
let request = crate::TransferRequest::to_address(&line.address, 600)
.expect("a destination the ceremony displays must be one the builder will pay");
assert_eq!(
request.recipient(),
puzzle_hash,
"the displayed address must decode back to the puzzle hash the output creates"
);
}
#[cfg(test)]
fn spend_creating(
outputs: &[(Bytes32, u64)],
fee: u64,
) -> (Vec<CoinSpend>, crate::keys::wallet_key::WalletKey) {
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use chia_protocol::Coin;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::SpendContext;
use chia_wallet_sdk::types::Conditions;
const COIN_AMOUNT: u64 = 10_000;
let key = WalletKey::from_seed_at(&[0x42u8; 32], ProfileIx::ROOT);
let mut ctx = SpendContext::new();
let coin = Coin::new(Bytes32::new([1u8; 32]), key.puzzle_hash(), COIN_AMOUNT);
let mut conditions = Conditions::new();
let mut spent = fee;
for (puzzle_hash, amount) in outputs {
conditions = conditions.create_coin(*puzzle_hash, *amount, Memos::None);
spent += amount;
if dig_wallet_backend::client::is_protocol_sink_hash(*puzzle_hash) {
conditions = conditions.assert_coin_announcement(Bytes32::new([0xAB; 32]));
}
}
conditions = conditions
.create_coin(key.puzzle_hash(), COIN_AMOUNT - spent, Memos::None)
.reserve_fee(fee);
StandardLayer::new(key.public_key())
.spend(&mut ctx, coin, conditions)
.expect("the fixture spend is well-formed");
(ctx.take(), key)
}
#[test]
fn only_an_output_returning_to_a_proven_p2_destination_is_treated_as_change() {
let stranger = Bytes32::new([0x7Au8; 32]);
let (coin_spends, key) = spend_creating(&[(stranger, 600)], 10);
let summary = SpendSummary::from_coin_spends(&coin_spends, SpendTier::Confirm).unwrap();
assert_eq!(
summary.recipients.len(),
1,
"the change back to the spent coin's own p2 hash is the ONLY excusable output: {summary:?}"
);
assert_eq!(summary.recipients[0].amount_mojos, 600);
assert_eq!(summary.recipients[0].destination, SpendDestination::Address);
assert_eq!(
Address::decode(&summary.recipients[0].address)
.expect("an address line must decode")
.puzzle_hash,
stranger,
"the line must name the stranger, not the wallet"
);
assert_ne!(stranger, key.puzzle_hash());
}
#[test]
fn value_committed_to_a_protocol_structure_is_counted_and_named_not_addressed() {
let launcher = Bytes32::new(SINGLETON_LAUNCHER_HASH);
let stranger = Bytes32::new([0x7Au8; 32]);
let (coin_spends, _) = spend_creating(&[(stranger, 600), (launcher, 1)], 10);
let summary = SpendSummary::from_coin_spends(&coin_spends, SpendTier::Confirm).unwrap();
let sink = summary
.recipients
.iter()
.find(|line| line.destination == SpendDestination::ProtocolStructure)
.expect("the launcher commitment must appear in the summary");
assert_eq!(sink.amount_mojos, 1);
assert_eq!(sink.address, "the singleton launcher");
assert!(
Address::decode(&sink.address).is_err(),
"a structural commitment must not render as a payable address"
);
assert_eq!(
summary.recipients.len(),
2,
"the ordinary recipient is counted too: {summary:?}"
);
assert_eq!(summary.native_total_mojos(), 600 + 1 + 10);
}
#[test]
fn the_offer_settlement_puzzle_is_named_distinctly_from_the_launcher() {
let settlement = Bytes32::new(SETTLEMENT_PAYMENT_HASH);
let (coin_spends, _) = spend_creating(&[(settlement, 500)], 10);
let summary = SpendSummary::from_coin_spends(&coin_spends, SpendTier::Confirm).unwrap();
assert_eq!(summary.recipients.len(), 1);
assert_eq!(summary.recipients[0].address, "the offer settlement puzzle");
assert_eq!(
summary.recipients[0].destination,
SpendDestination::ProtocolStructure
);
}
#[test]
fn an_unrecognized_protocol_structure_is_reported_as_unrecognized() {
let unknown = Bytes32::new([0x33u8; 32]);
let line = protocol_structure_line(&decoded_output(unknown, 9));
assert!(
line.address.contains("unrecognized") && line.address.contains(&hex::encode(unknown)),
"the line must say it cannot name the structure, and show which one: {line:?}"
);
assert_eq!(line.destination, SpendDestination::ProtocolStructure);
assert_eq!(line.amount_mojos, 9);
}
fn decoded_output(puzzle_hash: Bytes32, amount: u64) -> DecodedOutput {
let (coin_spends, _) = spend_creating(&[(puzzle_hash, amount)], 0);
analyze(&coin_spends)
.expect("the fixture spend is analyzable")
.outputs
.into_iter()
.find(|output| output.puzzle_hash == puzzle_hash)
.expect("the fixture creates this output")
}
#[test]
fn classify_maps_vault_to_the_vault_tier() {
assert_eq!(
SpendTier::classify(&CustodyPolicy::Vault(Vault::default()), 1),
SpendTier::Vault
);
}
#[test]
fn classify_auto_sends_within_the_hot_allowance() {
let policy = CustodyPolicy::Hot(HotWallet {
auto_send_limit: 1_000,
});
assert_eq!(SpendTier::classify(&policy, 1_000), SpendTier::AutoSend);
assert_eq!(SpendTier::classify(&policy, 1_001), SpendTier::Confirm);
}
#[test]
fn classify_confirms_every_spend_on_a_zero_allowance_hot_wallet() {
let policy = CustodyPolicy::Hot(HotWallet::default());
assert_eq!(SpendTier::classify(&policy, 0), SpendTier::AutoSend);
assert_eq!(SpendTier::classify(&policy, 1), SpendTier::Confirm);
}
#[test]
fn native_total_sums_xch_recipients_and_fee_ignoring_cats() {
let summary = SpendSummary::new(
SpendTier::Confirm,
vec![
paying("xch1a", 600, None),
paying("xch1b", 999, Some("deadbeef")),
],
10,
);
assert_eq!(summary.native_total_mojos(), 610);
}
#[test]
fn display_renders_xch_amounts_in_whole_coins_not_base_units() {
let summary = SpendSummary::new(
SpendTier::AutoSend,
vec![paying("xch1abc", 1_500_000_000_000, None)],
5_000_000_000,
);
let line = summary.to_string();
assert!(line.contains("1.5 XCH -> xch1abc"), "{line}");
assert!(!line.contains("1500000000000"), "{line}");
assert!(line.contains("fee 0.005 XCH"), "{line}");
assert!(!line.contains("5000000000"), "{line}");
}
#[test]
fn display_renders_a_single_mojo_without_rounding_it_away() {
let summary = SpendSummary::new(SpendTier::AutoSend, vec![paying("xch1abc", 1, None)], 0);
let line = summary.to_string();
assert!(line.contains("0.000000000001 XCH -> xch1abc"), "{line}");
assert!(line.contains("fee 0 XCH"), "{line}");
}
#[test]
fn a_non_decodable_coin_spend_set_is_refused() {
let err = SpendSummary::from_coin_spends(&[], SpendTier::Confirm).unwrap_err();
assert!(matches!(err, AccountError::Spend(_)));
let err =
SpendSummary::classified(&[], &CustodyPolicy::Hot(HotWallet::default())).unwrap_err();
assert!(matches!(err, AccountError::Spend(_)));
}
#[test]
fn display_handles_a_summary_with_no_recipients() {
let summary = SpendSummary::new(SpendTier::Vault, vec![], 3);
let line = summary.to_string();
assert!(line.contains("no recipients"), "{line}");
assert!(line.contains("fee 0.000000000003 XCH"), "{line}");
}
#[test]
fn display_names_a_cat_asset() {
let summary = SpendSummary::new(
SpendTier::Confirm,
vec![paying("xch1cat", 7, Some("cafe"))],
0,
);
assert!(
summary
.to_string()
.contains("7 base units of CAT cafe -> xch1cat"),
"a CAT amount is base units, said in those words: {summary}"
);
}
#[test]
fn a_multi_recipient_summary_separates_its_recipients_in_order() {
let summary = SpendSummary::new(
SpendTier::Confirm,
vec![
paying("xch1first", 100, None),
paying("xch1second", 250, Some("cafe")),
],
7,
);
assert_eq!(
summary.to_string(),
concat!(
"Confirm: 0.0000000001 XCH -> xch1first, ",
"250 base units of CAT cafe -> xch1second (fee 0.000000000007 XCH)"
)
);
}
#[test]
fn classified_re_derives_and_tiers_a_real_send() {
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use chia_protocol::{Bytes32, Coin};
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::{SpendContext, StandardLayer};
use chia_wallet_sdk::types::Conditions;
let key = WalletKey::from_seed_at(&[0x42u8; 32], ProfileIx::ROOT);
let mut ctx = SpendContext::new();
let coin = Coin::new(Bytes32::new([1u8; 32]), key.puzzle_hash(), 1_000);
let recipient = Bytes32::new([7u8; 32]);
let hint = ctx.hint(recipient).unwrap();
let conditions = Conditions::new()
.create_coin(recipient, 600, hint)
.create_coin(key.puzzle_hash(), 390, Memos::None)
.reserve_fee(10);
StandardLayer::new(key.public_key())
.spend(&mut ctx, coin, conditions)
.unwrap();
let coin_spends = ctx.take();
let policy = CustodyPolicy::Hot(HotWallet {
auto_send_limit: 1_000,
});
let summary = SpendSummary::classified(&coin_spends, &policy).unwrap();
assert_eq!(summary.recipients.len(), 1);
assert_eq!(summary.recipients[0].amount_mojos, 600);
assert_eq!(summary.fee, 10);
assert_eq!(summary.tier, SpendTier::AutoSend);
}
}
#[cfg(test)]
mod melting_a_singleton_is_named_not_charged {
use super::*;
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::wallet::melt_fixture::{melted_coin_id_hex, store_melt_owned_by};
use crate::wallet::policy::HotWallet;
fn money_key() -> WalletKey {
WalletKey::from_seed_at(&[0x42u8; 32], ProfileIx::ROOT)
}
fn generous_hot_wallet() -> CustodyPolicy {
CustodyPolicy::Hot(HotWallet {
auto_send_limit: 1_000_000,
})
}
#[test]
fn a_melt_names_the_singleton_it_destroys() {
let coin_spends = store_melt_owned_by(money_key().public_key(), 0x11);
let summary = SpendSummary::from_coin_spends(&coin_spends, SpendTier::Confirm)
.expect("a terminal singleton melt is a verifiable spend");
assert_eq!(
summary.melted_singletons,
vec![melted_coin_id_hex(&coin_spends)],
"the summary must name the lineage this spend ends"
);
assert!(
summary.recipients.is_empty(),
"a melt creates no coin, so it can never be reviewed as a payment"
);
}
#[test]
fn a_deletion_that_ends_two_singletons_names_both() {
let key = money_key().public_key();
let first = store_melt_owned_by(key, 0x11);
let second = store_melt_owned_by(key, 0x22);
let both: Vec<CoinSpend> = first.iter().chain(second.iter()).cloned().collect();
let summary = SpendSummary::from_coin_spends(&both, SpendTier::Confirm)
.expect("two terminal melts in one bundle are verifiable");
let mut named = summary.melted_singletons.clone();
let mut expected = vec![melted_coin_id_hex(&first), melted_coin_id_hex(&second)];
named.sort();
expected.sort();
assert_eq!(named, expected, "both destroyed lineages must be named");
assert_ne!(
expected[0], expected[1],
"the fixture must melt two DIFFERENT singletons, or it cannot see a dropped entry"
);
}
#[test]
fn a_melt_is_confirmed_by_a_human_even_when_its_value_fits_the_allowance() {
let coin_spends = store_melt_owned_by(money_key().public_key(), 0x11);
let summary = SpendSummary::classified(&coin_spends, &generous_hot_wallet())
.expect("a terminal singleton melt is a verifiable spend");
assert!(
summary.native_total_mojos() <= 1_000_000,
"the fixture must fit the allowance, or the escalation proves nothing"
);
assert_eq!(
summary.tier,
SpendTier::Confirm,
"destruction is not a value a limit can bound; it always reaches a human"
);
}
#[test]
fn an_ordinary_send_of_the_same_value_under_the_same_policy_is_auto_sent() {
use chia_protocol::Coin;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::SpendContext;
use chia_wallet_sdk::types::Conditions;
let key = money_key();
let mut ctx = SpendContext::new();
let coin = Coin::new(Bytes32::new([1u8; 32]), key.puzzle_hash(), 1_000);
let conditions = Conditions::new()
.create_coin(Bytes32::new([7u8; 32]), 1, Memos::None)
.create_coin(key.puzzle_hash(), 999, Memos::None);
StandardLayer::new(key.public_key())
.spend(&mut ctx, coin, conditions)
.expect("the control spend is well-formed");
let summary = SpendSummary::classified(&ctx.take(), &generous_hot_wallet())
.expect("an ordinary send is a verifiable spend");
assert_eq!(
summary.tier,
SpendTier::AutoSend,
"the control must be auto-sent, or the melt escalation above is vacuous"
);
}
#[test]
fn the_rendered_summary_says_the_spend_destroys_a_singleton() {
let coin_spends = store_melt_owned_by(money_key().public_key(), 0x11);
let summary = SpendSummary::from_coin_spends(&coin_spends, SpendTier::Confirm)
.expect("a terminal singleton melt is a verifiable spend");
let rendered = summary.to_string();
assert!(
rendered.contains("destroys"),
"the melt must be stated, not left to a fee: {rendered}"
);
assert!(
rendered.contains(&melted_coin_id_hex(&coin_spends)),
"the destroyed lineage must be identified: {rendered}"
);
}
#[test]
fn an_ordinary_send_renders_no_destruction_clause() {
let rendered = SpendSummary::new(
SpendTier::Confirm,
vec![SpendRecipient::to_address("xch1abc", 600, None::<String>)],
10,
)
.to_string();
assert!(
!rendered.contains("destroys"),
"a send must not claim to destroy anything: {rendered}"
);
}
}
#[cfg(test)]
mod an_nft_act_is_named_not_priced {
use super::*;
use crate::id::ProfileIx;
use crate::keys::wallet_key::WalletKey;
use crate::wallet::nft_fixture::{
launcher_id, nft_mint_to, nft_transfer_to, RECIPIENT_PUZZLE_HASH,
};
use crate::wallet::policy::HotWallet;
const OTHER_OWNER: Bytes32 = Bytes32::new([0x3e; 32]);
fn money_key() -> WalletKey {
WalletKey::from_seed_at(&[0x42u8; 32], ProfileIx::ROOT)
}
fn address(hash: Bytes32, prefix: &str) -> String {
chia_wallet_sdk::utils::Address::new(hash, prefix.to_string())
.encode()
.expect("a 32-byte hash encodes")
}
fn generous_hot_wallet() -> CustodyPolicy {
CustodyPolicy::Hot(HotWallet {
auto_send_limit: 1_000_000,
})
}
#[test]
fn a_transfer_names_the_nft_and_the_owner_it_moves_to() {
let key = money_key().public_key();
let coin_spends = nft_transfer_to(key, RECIPIENT_PUZZLE_HASH, 0x44);
let summary = SpendSummary::from_coin_spends(&coin_spends, SpendTier::Confirm)
.expect("a canonical sdk NFT transfer is a verifiable spend");
let nft = address(launcher_id(key, money_key().puzzle_hash(), 0x44), "nft");
let new_owner = address(RECIPIENT_PUZZLE_HASH, "xch");
assert!(
summary
.nft_operations
.contains(&format!("transfer {nft} to {new_owner}")),
"the summary must name the NFT and where it goes, got {:?}",
summary.nft_operations
);
}
#[test]
fn two_transfers_of_the_same_nft_to_different_owners_read_differently() {
let key = money_key().public_key();
let honest = SpendSummary::from_coin_spends(
&nft_transfer_to(key, RECIPIENT_PUZZLE_HASH, 0x44),
SpendTier::Confirm,
)
.expect("the honest transfer is verifiable");
let elsewhere = SpendSummary::from_coin_spends(
&nft_transfer_to(key, OTHER_OWNER, 0x44),
SpendTier::Confirm,
)
.expect("the re-homed transfer is verifiable");
assert_eq!(
honest.native_total_mojos(),
elsewhere.native_total_mojos(),
"the two fixtures must move the same value, or the destination is not what \
distinguishes them"
);
assert_ne!(
honest.nft_operations, elsewhere.nft_operations,
"two transfers of one NFT to different owners must not read the same"
);
}
#[test]
fn two_mints_of_the_same_launcher_to_different_owners_read_differently() {
let key = money_key().public_key();
let to_recipient = SpendSummary::from_coin_spends(
&nft_mint_to(key, RECIPIENT_PUZZLE_HASH, 0x55),
SpendTier::Confirm,
)
.expect("the first mint is verifiable");
let to_other = SpendSummary::from_coin_spends(
&nft_mint_to(key, OTHER_OWNER, 0x55),
SpendTier::Confirm,
)
.expect("the second mint is verifiable");
assert_eq!(
launcher_id(key, RECIPIENT_PUZZLE_HASH, 0x55),
launcher_id(key, OTHER_OWNER, 0x55),
"the fixture must mint ONE launcher id to two owners, or the owner is not what \
distinguishes the sentences"
);
assert_ne!(
to_recipient.nft_operations, to_other.nft_operations,
"two mints of the same launcher id to different owners must not read the same"
);
}
#[test]
fn an_nft_transfer_is_confirmed_by_a_human_even_when_its_value_fits_the_allowance() {
let coin_spends = nft_transfer_to(money_key().public_key(), RECIPIENT_PUZZLE_HASH, 0x44);
let summary = SpendSummary::classified(&coin_spends, &generous_hot_wallet())
.expect("a canonical sdk NFT transfer is a verifiable spend");
assert!(
summary.native_total_mojos() <= 1_000_000,
"the fixture must fit the allowance, or the escalation proves nothing"
);
assert_eq!(
summary.tier,
SpendTier::Confirm,
"an NFT's value is not a figure a mojo limit can bound; it always reaches a human"
);
}
#[test]
fn an_ordinary_send_of_the_same_value_under_the_same_policy_is_auto_sent() {
use chia_protocol::Coin;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::SpendContext;
use chia_wallet_sdk::types::Conditions;
let key = money_key();
let mut ctx = SpendContext::new();
let coin = Coin::new(Bytes32::new([1u8; 32]), key.puzzle_hash(), 1_000);
StandardLayer::new(key.public_key())
.spend(
&mut ctx,
coin,
Conditions::new()
.create_coin(Bytes32::new([7u8; 32]), 4, Memos::None)
.create_coin(key.puzzle_hash(), 996, Memos::None),
)
.expect("the control spend is well-formed");
let summary = SpendSummary::classified(&ctx.take(), &generous_hot_wallet())
.expect("an ordinary send is a verifiable spend");
assert_eq!(
summary.tier,
SpendTier::AutoSend,
"the control must be auto-sent, or the NFT escalation above is vacuous"
);
}
#[test]
fn the_rendered_summary_names_the_nft_act_and_its_new_owner() {
let key = money_key().public_key();
let summary = SpendSummary::from_coin_spends(
&nft_transfer_to(key, RECIPIENT_PUZZLE_HASH, 0x44),
SpendTier::Confirm,
)
.expect("a canonical sdk NFT transfer is a verifiable spend");
let rendered = summary.to_string();
assert!(
rendered.contains("transfer nft1")
&& rendered.contains(&address(RECIPIENT_PUZZLE_HASH, "xch")),
"the act must be stated, not left to four dust lines: {rendered}"
);
}
#[test]
fn an_ordinary_send_states_no_nft_act() {
use chia_protocol::Coin;
use chia_puzzle_types::Memos;
use chia_wallet_sdk::driver::SpendContext;
use chia_wallet_sdk::types::Conditions;
let key = money_key();
let mut ctx = SpendContext::new();
StandardLayer::new(key.public_key())
.spend(
&mut ctx,
Coin::new(Bytes32::new([1u8; 32]), key.puzzle_hash(), 1_000),
Conditions::new().create_coin(Bytes32::new([7u8; 32]), 1_000, Memos::None),
)
.expect("the control spend is well-formed");
let summary = SpendSummary::from_coin_spends(&ctx.take(), SpendTier::Confirm)
.expect("an ordinary send is a verifiable spend");
assert!(summary.nft_operations.is_empty());
assert!(!summary.to_string().contains("nft1"));
}
}