1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//! Wallet and Balance Management Patterns
//!
//! Macros for wallet operations with balance tracking and validation
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
/// Derive macro for wallet entities with balance management
pub fn derive_wallet_entity(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let struct_name = &input.ident;
eprintln!("[pleme-codegen] WalletEntity pattern applied to {} - saving ~200 lines", struct_name);
let expanded = quote! {
impl #struct_name {
/// Get available balance (confirmed funds)
pub fn available_balance(&self) -> rust_decimal::Decimal {
self.balance
}
/// Get total balance (including pending)
pub fn total_balance(&self) -> rust_decimal::Decimal {
self.balance + self.pending_balance
}
/// Add balance with validation and tracking
pub fn add_balance(&mut self, amount: rust_decimal::Decimal, description: &str) -> Result<(), PaymentError> {
if amount <= rust_decimal::Decimal::ZERO {
return Err(PaymentError::InvalidAmount);
}
let balance_before = self.balance;
self.balance += amount;
self.lifetime_earnings += amount;
self.updated_at = chrono::Utc::now();
// Track balance change
tracing::info!(
wallet_id = %self.id,
user_id = %self.user_id,
amount = %amount,
balance_before = %balance_before,
balance_after = %self.balance,
description = %description,
"Balance added to wallet"
);
Ok(())
}
/// Subtract balance with validation
pub fn subtract_balance(&mut self, amount: rust_decimal::Decimal, description: &str) -> Result<(), PaymentError> {
if amount <= rust_decimal::Decimal::ZERO {
return Err(PaymentError::InvalidAmount);
}
if self.balance < amount {
return Err(PaymentError::InsufficientFunds);
}
let balance_before = self.balance;
self.balance -= amount;
self.lifetime_spending += amount;
self.updated_at = chrono::Utc::now();
// Track balance change
tracing::info!(
wallet_id = %self.id,
user_id = %self.user_id,
amount = %amount,
balance_before = %balance_before,
balance_after = %self.balance,
description = %description,
"Balance subtracted from wallet"
);
Ok(())
}
/// Add tokens to wallet
pub fn add_tokens(&mut self, tokens: i64, description: &str) -> Result<(), PaymentError> {
if tokens < 0i64 {
return Err(PaymentError::InvalidAmount);
}
let tokens_before: i64 = self.tokens;
self.tokens = tokens_before.saturating_add(tokens);
self.updated_at = chrono::Utc::now();
tracing::info!(
wallet_id = %self.id,
user_id = %self.user_id,
tokens_added = %tokens,
tokens_before = %tokens_before,
tokens_after = %self.tokens,
description = %description,
"Tokens added to wallet"
);
Ok(())
}
/// Spend tokens with validation
pub fn spend_tokens(&mut self, tokens: i64, description: &str) -> Result<(), PaymentError> {
if tokens < 0i64 {
return Err(PaymentError::InvalidAmount);
}
if self.tokens < tokens {
return Err(PaymentError::InsufficientFunds);
}
let tokens_before: i64 = self.tokens;
let tokens_to_subtract: i64 = tokens;
self.tokens = tokens_before - tokens_to_subtract;
self.updated_at = chrono::Utc::now();
tracing::info!(
wallet_id = %self.id,
user_id = %self.user_id,
tokens_spent = %tokens,
tokens_before = %tokens_before,
tokens_after = %self.tokens,
description = %description,
"Tokens spent from wallet"
);
Ok(())
}
/// Add pending balance (funds awaiting clearance)
pub fn add_pending(&mut self, amount: rust_decimal::Decimal, description: &str) -> Result<(), PaymentError> {
if amount <= rust_decimal::Decimal::ZERO {
return Err(PaymentError::InvalidAmount);
}
self.pending_balance += amount;
self.updated_at = chrono::Utc::now();
tracing::info!(
wallet_id = %self.id,
amount = %amount,
pending_balance = %self.pending_balance,
description = %description,
"Pending balance added"
);
Ok(())
}
/// Clear pending balance (move to available)
pub fn clear_pending(&mut self, amount: rust_decimal::Decimal, description: &str) -> Result<(), PaymentError> {
if amount <= rust_decimal::Decimal::ZERO {
return Err(PaymentError::InvalidAmount);
}
if self.pending_balance < amount {
return Err(PaymentError::InvalidAmount);
}
self.pending_balance -= amount;
self.balance += amount;
self.lifetime_earnings += amount;
self.updated_at = chrono::Utc::now();
tracing::info!(
wallet_id = %self.id,
amount = %amount,
balance = %self.balance,
pending_balance = %self.pending_balance,
description = %description,
"Pending balance cleared to available"
);
Ok(())
}
/// Cancel pending balance
pub fn cancel_pending(&mut self, amount: rust_decimal::Decimal, description: &str) -> Result<(), PaymentError> {
if amount <= rust_decimal::Decimal::ZERO {
return Err(PaymentError::InvalidAmount);
}
if self.pending_balance < amount {
return Err(PaymentError::InvalidAmount);
}
self.pending_balance -= amount;
self.updated_at = chrono::Utc::now();
tracing::info!(
wallet_id = %self.id,
amount = %amount,
pending_balance = %self.pending_balance,
description = %description,
"Pending balance cancelled"
);
Ok(())
}
/// Calculate payout amount after fees
pub fn calculate_payout(
&self,
amount: rust_decimal::Decimal,
fee_percentage: rust_decimal::Decimal
) -> Result<PayoutCalculation, PaymentError> {
if amount > self.balance {
return Err(PaymentError::InsufficientFunds);
}
let fee = amount * (fee_percentage / rust_decimal::Decimal::from(100));
let net_amount = amount - fee;
Ok(PayoutCalculation {
gross_amount: amount,
fee_percentage,
fee_amount: fee,
net_amount,
})
}
/// Check wallet health metrics
pub fn health_metrics(&self) -> WalletHealthMetrics {
let total_balance = self.total_balance();
let pending_ratio = if total_balance > rust_decimal::Decimal::ZERO {
self.pending_balance / total_balance
} else {
rust_decimal::Decimal::ZERO
};
WalletHealthMetrics {
balance: self.balance,
pending_balance: self.pending_balance,
total_balance,
tokens: self.tokens,
lifetime_earnings: self.lifetime_earnings,
lifetime_spending: self.lifetime_spending,
net_earnings: self.lifetime_earnings - self.lifetime_spending,
pending_ratio: {
use std::str::FromStr;
f64::from_str(&pending_ratio.to_string()).unwrap_or(0.0)
},
last_activity: self.updated_at,
}
}
/// Validate minimum balance for operations
pub fn validate_minimum_balance(&self, minimum: rust_decimal::Decimal) -> Result<(), PaymentError> {
if self.balance < minimum {
return Err(PaymentError::InsufficientFunds);
}
Ok(())
}
/// Lock wallet for maintenance or security
pub fn lock(&mut self, reason: &str) -> Result<(), PaymentError> {
if self.locked {
return Err(PaymentError::InvalidAmount); // Using available error type
}
self.locked = true;
self.locked_at = Some(chrono::Utc::now());
self.lock_reason = Some(reason.to_string());
self.updated_at = chrono::Utc::now();
tracing::warn!(
wallet_id = %self.id,
user_id = %self.user_id,
reason = %reason,
"Wallet locked"
);
Ok(())
}
/// Unlock wallet
pub fn unlock(&mut self) -> Result<(), PaymentError> {
if !self.locked {
return Err(PaymentError::InvalidAmount); // Using available error type
}
self.locked = false;
self.locked_at = None;
self.lock_reason = None;
self.updated_at = chrono::Utc::now();
tracing::info!(
wallet_id = %self.id,
user_id = %self.user_id,
"Wallet unlocked"
);
Ok(())
}
/// Check if wallet is active
pub fn is_active(&self) -> bool {
!self.locked
}
}
/// Payout calculation result
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutCalculation {
pub gross_amount: rust_decimal::Decimal,
pub fee_percentage: rust_decimal::Decimal,
pub fee_amount: rust_decimal::Decimal,
pub net_amount: rust_decimal::Decimal,
}
/// Wallet health metrics
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct WalletHealthMetrics {
pub balance: rust_decimal::Decimal,
pub pending_balance: rust_decimal::Decimal,
pub total_balance: rust_decimal::Decimal,
pub tokens: i64,
pub lifetime_earnings: rust_decimal::Decimal,
pub lifetime_spending: rust_decimal::Decimal,
pub net_earnings: rust_decimal::Decimal,
pub pending_ratio: f64,
pub last_activity: chrono::DateTime<chrono::Utc>,
}
};
TokenStream::from(expanded)
}