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
//! Service for economy plugin
use super::resources::{ConversionRules, ExchangeRates, ResourceDefinitions};
use super::state::{ResourceInventory, Wallet};
use super::types::{Currency, CurrencyId, ResourceId};
use crate::service::Service;
use std::any::Any;
/// Result type for economy operations
pub type EconomyResult<T> = Result<T, EconomyError>;
/// Errors that can occur in economy operations
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum EconomyError {
InsufficientFunds,
InsufficientResource,
ExchangeRateNotFound,
ConversionRuleNotFound,
ResourceNotFound,
ResourceNotFinite,
}
/// Service for currency calculations and transactions
#[derive(Clone, Default)]
pub struct EconomyService;
impl EconomyService {
// ========================================================================
// Currency Operations
// ========================================================================
/// Check balance of a specific currency in the wallet
pub fn balance(&self, wallet: &Wallet, currency_id: &CurrencyId) -> Currency {
wallet.get(currency_id).cloned().unwrap_or(Currency::ZERO)
}
/// Add currency to the wallet
pub fn deposit(&self, wallet: &mut Wallet, currency_id: &CurrencyId, amount: Currency) {
let current = self.balance(wallet, currency_id);
wallet.insert(currency_id.clone(), current + amount);
}
/// Subtract currency from the wallet
///
/// Returns `Ok(())` if successful, `Err(())` if insufficient funds (and wallet doesn't allow debt - though Currency allows negative).
/// For now, we allow negative balance as debt, so this always succeeds.
/// Future improvements could add debt limits.
pub fn withdraw(&self, wallet: &mut Wallet, currency_id: &CurrencyId, amount: Currency) {
let current = self.balance(wallet, currency_id);
wallet.insert(currency_id.clone(), current - amount);
}
/// Transfer currency between two wallets (if we had multiple wallets, but currently we have one global wallet store)
/// This method is a placeholder for future multi-wallet support.
pub fn transfer(
&self,
from_wallet: &mut Wallet,
to_wallet: &mut Wallet,
currency_id: &CurrencyId,
amount: Currency,
) {
self.withdraw(from_wallet, currency_id, amount);
self.deposit(to_wallet, currency_id, amount);
}
// ========================================================================
// Currency Exchange Operations
// ========================================================================
/// Exchange currency from one type to another
///
/// This performs: wallet[from] -= from_amount, wallet[to] += converted_amount
///
/// Returns the amount of target currency received.
pub fn exchange(
&self,
wallet: &mut Wallet,
exchange_rates: &ExchangeRates,
from_currency: &CurrencyId,
to_currency: &CurrencyId,
from_amount: Currency,
) -> EconomyResult<Currency> {
// Check if exchange rate exists
let rate = exchange_rates
.get(from_currency, to_currency)
.ok_or(EconomyError::ExchangeRateNotFound)?;
// Check if wallet has enough funds
let current_balance = self.balance(wallet, from_currency);
if current_balance < from_amount {
return Err(EconomyError::InsufficientFunds);
}
// Calculate converted amount
let to_amount = rate.convert(from_amount);
// Execute exchange
self.withdraw(wallet, from_currency, from_amount);
self.deposit(wallet, to_currency, to_amount);
Ok(to_amount)
}
// ========================================================================
// Resource Operations
// ========================================================================
/// Get resource quantity
pub fn resource_quantity(
&self,
inventory: &ResourceInventory,
resource_id: &ResourceId,
) -> i64 {
inventory.get(resource_id).cloned().unwrap_or(0)
}
/// Add resource to inventory
pub fn add_resource(
&self,
inventory: &mut ResourceInventory,
_resource_definitions: &ResourceDefinitions,
resource_id: &ResourceId,
amount: i64,
) -> EconomyResult<()> {
// For infinite resources, this just updates the capacity/power level
let current = self.resource_quantity(inventory, resource_id);
inventory.insert(resource_id.clone(), current + amount);
Ok(())
}
/// Consume resource from inventory
///
/// Returns error if insufficient resource (for finite resources).
/// For infinite resources, this operation doesn't actually consume but may
/// represent a temporary reduction in capacity.
pub fn consume_resource(
&self,
inventory: &mut ResourceInventory,
resource_definitions: &ResourceDefinitions,
resource_id: &ResourceId,
amount: i64,
) -> EconomyResult<()> {
let current = self.resource_quantity(inventory, resource_id);
// Check if we have enough (only for finite resources)
if !resource_definitions.is_infinite(resource_id) && current < amount {
return Err(EconomyError::InsufficientResource);
}
inventory.insert(resource_id.clone(), current - amount);
Ok(())
}
// ========================================================================
// Resource to Currency Conversion
// ========================================================================
/// Convert resource to currency
///
/// This consumes the resource and generates currency in the wallet.
///
/// Returns the amount of currency generated.
#[allow(clippy::too_many_arguments)]
pub fn convert_resource_to_currency(
&self,
inventory: &mut ResourceInventory,
wallet: &mut Wallet,
resource_definitions: &ResourceDefinitions,
conversion_rules: &ConversionRules,
resource_id: &ResourceId,
currency_id: &CurrencyId,
resource_amount: i64,
) -> EconomyResult<Currency> {
// Get conversion rule
let rule = conversion_rules
.get_rule(resource_id, currency_id)
.ok_or(EconomyError::ConversionRuleNotFound)?;
// Consume resource (if finite, this will check availability)
self.consume_resource(
inventory,
resource_definitions,
resource_id,
resource_amount,
)?;
// Generate currency
let currency_amount = rule.convert(resource_amount);
self.deposit(wallet, currency_id, currency_amount);
Ok(currency_amount)
}
}
#[async_trait::async_trait]
impl Service for EconomyService {
fn name(&self) -> &'static str {
"economy_service"
}
fn clone_box(&self) -> Box<dyn Service> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
}