forked from QuickLendX/quicklendx-protocol
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrency.rs
More file actions
366 lines (334 loc) · 13.7 KB
/
Copy pathcurrency.rs
File metadata and controls
366 lines (334 loc) · 13.7 KB
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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
//! Multi-currency whitelist: admin-managed list of token addresses allowed for invoice currency.
//! Rejects invoice creation and bids for non-whitelisted tokens (e.g. USDC, EURC, stablecoins).
//!
//! ## Empty-list semantics
//! When the whitelist contains **zero** entries every currency is accepted. This preserves
//! backward compatibility for deployments that have not yet configured a whitelist. The moment
//! at least one currency is added, the list becomes restrictive.
//!
//! ## Authorization model
//! All write operations require **two** independent checks:
//! 1. `AdminStorage::get_admin` - verifies an admin has been initialised and retrieves it.
//! 2. `admin.require_auth()` - the Soroban host enforces that the transaction is signed by
//! that address. Neither check alone is sufficient.
//!
use crate::admin::AdminStorage;
use crate::errors::QuickLendXError;
use soroban_sdk::{symbol_short, Address, Env, String, Vec};
const WHITELIST_KEY: soroban_sdk::Symbol = symbol_short!("curr_wl");
/// Currency whitelist storage and operations.
pub struct CurrencyWhitelist;
impl CurrencyWhitelist {
/// Add a token address to the whitelist (admin only).
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `admin` - Address that must match the stored contract admin.
/// - `currency` - Token contract address to allow.
///
/// # Behaviour
/// - **Idempotent**: if `currency` is already present the call succeeds without
/// modifying state.
/// - Both the storage admin check and `require_auth()` must pass.
///
/// # Errors
/// - `NotAdmin` - `admin` does not match the stored admin or no admin is set.
/// - `InvalidCurrency` - `currency` is the admin address, zero address, or self.
pub fn add_currency(
env: &Env,
admin: &Address,
currency: &Address,
) -> Result<(), QuickLendXError> {
AdminStorage::require_admin(env, admin)?;
// Ensure currency is not a reserved address
let zero = Self::zero_address(env);
if currency == admin || currency == &zero || currency == &env.current_contract_address() {
return Err(QuickLendXError::InvalidCurrency);
}
let mut list = Self::get_whitelisted_currencies(env);
if list.iter().any(|a| a == *currency) {
return Ok(()); // idempotent: already present
}
list.push_back(currency.clone());
env.storage().instance().set(&WHITELIST_KEY, &list);
Ok(())
}
/// Add multiple token addresses to the whitelist in a single admin call.
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `admin` - Address that must match the stored contract admin.
/// - `currencies` - Token contract addresses to add.
///
/// # Behaviour
/// - Returns a `Vec<bool>` of the same length as `currencies`:
/// `true` at index i = currency[i] was newly added;
/// `false` at index i = currency[i] was already present (idempotent, skipped).
/// - Duplicates within the input are handled against the evolving list:
/// the first occurrence is added (`true`), subsequent occurrences are skipped (`false`).
/// - Empty input returns an empty result with no storage write.
/// - Admin auth is enforced before any mutation.
///
/// # Errors
/// - `NotAdmin` - `admin` does not match the stored admin.
/// - `OperationNotAllowed` - no admin has been initialised.
pub fn add_currencies_batch(
env: &Env,
admin: &Address,
currencies: &Vec<Address>,
) -> Result<Vec<bool>, QuickLendXError> {
AdminStorage::require_admin(env, admin)?;
// Reject reserved addresses in batch
let zero = Self::zero_address(env);
let contract_addr = env.current_contract_address();
for currency in currencies.iter() {
if currency == *admin || currency == zero || currency == contract_addr {
return Err(QuickLendXError::InvalidCurrency);
}
}
let mut results: Vec<bool> = Vec::new(env);
if currencies.is_empty() {
return Ok(results);
}
let mut list = Self::get_whitelisted_currencies(env);
let mut any_added = false;
for currency in currencies.iter() {
if list.iter().any(|a| a == currency) {
results.push_back(false);
} else {
list.push_back(currency.clone());
results.push_back(true);
any_added = true;
}
}
if any_added {
env.storage().instance().set(&WHITELIST_KEY, &list);
}
Ok(results)
}
/// Remove a token address from the whitelist (admin only).
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `admin` - Address that must match the stored contract admin.
/// - `currency` - Token contract address to remove.
///
/// # Behaviour
/// - **No-op when absent**: if `currency` is not in the list the call succeeds and
/// state is unchanged.
/// - Rebuilds the list without the target address in a single pass.
///
/// # Errors
/// - `NotAdmin` - `admin` does not match the stored admin or no admin is set.
pub fn remove_currency(
env: &Env,
admin: &Address,
currency: &Address,
) -> Result<(), QuickLendXError> {
let current_admin = AdminStorage::get_admin(env).ok_or(QuickLendXError::NotAdmin)?;
if *admin != current_admin {
return Err(QuickLendXError::NotAdmin);
}
admin.require_auth();
let list = Self::get_whitelisted_currencies(env);
let mut new_list = Vec::new(env);
for a in list.iter() {
if a != *currency {
new_list.push_back(a);
}
}
env.storage().instance().set(&WHITELIST_KEY, &new_list);
Ok(())
}
/// Remove multiple token addresses from the whitelist in a single admin call.
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `admin` - Address that must match the stored contract admin.
/// - `currencies` - Token contract addresses to remove.
///
/// # Behaviour
/// - Returns a `Vec<bool>` of the same length as `currencies`:
/// `true` at index i = currency[i] was present and has been removed;
/// `false` at index i = currency[i] was not in the whitelist (no-op for that item).
/// - If the same address appears more than once in the input, all positions return
/// `true` when the address was present, but the physical removal happens only once.
/// - Empty input returns an empty result with no storage write.
/// - Admin auth is enforced before any mutation.
///
/// # Errors
/// - `NotAdmin` - `admin` does not match the stored admin or no admin is set.
pub fn remove_currencies_batch(
env: &Env,
admin: &Address,
currencies: &Vec<Address>,
) -> Result<Vec<bool>, QuickLendXError> {
let current_admin = AdminStorage::get_admin(env).ok_or(QuickLendXError::NotAdmin)?;
if *admin != current_admin {
return Err(QuickLendXError::NotAdmin);
}
admin.require_auth();
let mut results: Vec<bool> = Vec::new(env);
if currencies.is_empty() {
return Ok(results);
}
let list = Self::get_whitelisted_currencies(env);
let mut to_remove: Vec<Address> = Vec::new(env);
for currency in currencies.iter() {
let was_present = list.iter().any(|a| a == currency);
results.push_back(was_present);
if was_present && !to_remove.iter().any(|a: Address| a == currency) {
to_remove.push_back(currency.clone());
}
}
if !to_remove.is_empty() {
let mut new_list: Vec<Address> = Vec::new(env);
for a in list.iter() {
if !to_remove.iter().any(|r: Address| r == a) {
new_list.push_back(a);
}
}
env.storage().instance().set(&WHITELIST_KEY, &new_list);
}
Ok(results)
}
/// Return `true` if `currency` is present in the whitelist.
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `currency` - Token contract address to test.
///
/// # Security
/// Read-only; no authentication required. Does **not** apply the empty-list bypass
/// rule - use `require_allowed_currency` for enforcement.
pub fn is_allowed_currency(env: &Env, currency: &Address) -> bool {
let list = Self::get_whitelisted_currencies(env);
list.iter().any(|a| a == *currency)
}
/// Return the full whitelist as stored.
///
/// Returns an empty `Vec` when no whitelist has been persisted yet.
pub fn get_whitelisted_currencies(env: &Env) -> Vec<Address> {
env.storage()
.instance()
.get(&WHITELIST_KEY)
.unwrap_or_else(|| Vec::new(env))
}
/// Returns the canonical zero address used for validation.
fn zero_address(env: &Env) -> Address {
Address::from_string(&String::from_str(
env,
"GAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAWHF",
))
}
/// Assert that `currency` is permitted, respecting empty-list backward compatibility.
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `currency` - Token contract address being validated.
///
/// # Behaviour
/// - When the whitelist is **empty** the call succeeds unconditionally (allow-all mode).
/// - When the whitelist is **non-empty** the currency must appear in it.
///
/// # Errors
/// - `InvalidCurrency` - whitelist is non-empty and `currency` is not in it.
pub fn require_allowed_currency(env: &Env, currency: &Address) -> Result<(), QuickLendXError> {
let list = Self::get_whitelisted_currencies(env);
if list.is_empty() {
return Ok(());
}
if Self::is_allowed_currency(env, currency) {
Ok(())
} else {
Err(QuickLendXError::InvalidCurrency)
}
}
/// Atomically replace the entire whitelist (admin only).
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `admin` - Address that must match the stored contract admin.
/// - `currencies` - New list of allowed token addresses.
///
/// # Behaviour
/// - **Atomic**: the old list is fully replaced in one storage write.
/// - **Deduplicates**: duplicate addresses in `currencies` are silently collapsed
/// to a single entry, preserving first-occurrence order.
/// - Prefer this over multiple `add_currency` calls to avoid partial-state
/// windows between transactions.
///
/// # Errors
/// - `NotAdmin` - `admin` does not match the stored admin or no admin is set.
pub fn set_currencies(
env: &Env,
admin: &Address,
currencies: &Vec<Address>,
) -> Result<(), QuickLendXError> {
AdminStorage::require_admin(env, admin)?;
let mut deduped: Vec<Address> = Vec::new(env);
for currency in currencies.iter() {
if !deduped.iter().any(|a| a == currency) {
deduped.push_back(currency);
}
}
env.storage().instance().set(&WHITELIST_KEY, &deduped);
Ok(())
}
/// Clear the entire whitelist (admin only).
///
/// # Parameters
/// - `env` - Soroban execution environment.
/// - `admin` - Address that must match the stored contract admin.
///
/// # Behaviour
/// After this call `currency_count()` returns 0 and `require_allowed_currency`
/// succeeds for every token (empty-list backward-compat rule).
///
/// # Errors
/// - `NotAdmin` - `admin` does not match the stored admin or no admin is set.
pub fn clear_currencies(env: &Env, admin: &Address) -> Result<(), QuickLendXError> {
let current_admin = AdminStorage::get_admin(env).ok_or(QuickLendXError::NotAdmin)?;
if *admin != current_admin {
return Err(QuickLendXError::NotAdmin);
}
admin.require_auth();
env.storage()
.instance()
.set(&WHITELIST_KEY, &Vec::<Address>::new(env));
Ok(())
}
/// Return the number of whitelisted currencies.
pub fn currency_count(env: &Env) -> u32 {
Self::get_whitelisted_currencies(env).len()
}
/// @notice Return a paginated slice of the whitelist with metadata.
/// @param env The contract environment
/// @param offset Starting index for pagination (0-based)
/// @param limit Maximum number of results to return (capped at MAX_QUERY_LIMIT)
/// @return [`PaginatedCurrencies`] with items, total_count, and has_more
/// @dev Enforces MAX_QUERY_LIMIT hard cap for security and performance
pub fn get_whitelisted_currencies_paged(
env: &Env,
offset: u32,
limit: u32,
) -> crate::types::PaginatedCurrencies {
let list = Self::get_whitelisted_currencies(env);
let total_count = list.len();
let mut page: Vec<Address> = Vec::new(env);
let (start, end) = crate::pagination::calculate_safe_bounds(offset, limit, total_count);
let mut idx = start;
while idx < end {
if let Some(addr) = list.get(idx) {
page.push_back(addr);
}
idx = idx.saturating_add(1);
}
let (_, has_more) = crate::pagination::pagination_metadata(offset, limit, total_count);
crate::types::PaginatedCurrencies {
items: page,
total_count,
has_more,
}
}
}