forked from Haroldwonder/SwiftRemit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig.rs
More file actions
262 lines (216 loc) · 10.4 KB
/
Copy pathconfig.rs
File metadata and controls
262 lines (216 loc) · 10.4 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
//! Centralized configuration constants for the SwiftRemit contract.
//!
//! This module defines all contract-wide constants to ensure consistency
//! and prevent duplicate definitions. All magic numbers should be defined
//! here with clear documentation.
/// Number of ledgers to extend a remittance's persistent storage TTL when it
/// transitions from Pending to Processing (#624).
///
/// At a 5-second ledger time this equals approximately 7 days, giving agents
/// a reasonable window to complete the off-chain fiat payout before the
/// escrow record would otherwise expire.
pub const PROCESSING_WINDOW_LEDGERS: u32 = 120_960; // ~7 days at 5s/ledger
// ============================================================================
// Batch Processing Limits
// ============================================================================
/// Maximum number of remittances that can be settled in a single batch operation.
///
/// This limit prevents excessive resource consumption during batch settlement
/// operations. Used by batch settlement functions to validate input size.
pub const MAX_BATCH_SIZE: u32 = 100;
/// Maximum number of expired remittances that can be processed in a single batch.
///
/// This limit prevents excessive resource consumption during expired remittance
/// cleanup operations. Set lower than MAX_BATCH_SIZE due to additional processing
/// overhead for expiry checks and refunds.
pub const MAX_EXPIRED_BATCH_SIZE: u32 = 50;
/// Maximum number of items that can be exported/imported in a single migration batch.
///
/// This limit prevents excessive resource consumption during contract migration
/// operations. Used by migration export/import functions to validate batch size.
pub const MAX_MIGRATION_BATCH_SIZE: u32 = 100;
/// Maximum number of remittances that can be netted in a single compute_net_settlements call.
///
/// This limit prevents DoS attacks via large remittance batches that could cause
/// excessive gas consumption or ledger timeouts.
pub const MAX_NETTING_BATCH_SIZE: u32 = 50;
/// Maximum size of timestamp vector in rate limiting sliding window.
///
/// Caps the Vec size to prevent unbounded growth and O(n²) pruning behavior
/// during high-activity periods. Timestamps older than the window are pruned
/// in a single pass using retain-style filtering.
///
/// **Constraint**: must always be strictly greater than the largest per-window
/// request limit (`MAX_QUERIES_PER_WINDOW`). If this invariant is violated the
/// sliding-window cap would prune entries that are still inside the rate-limit
/// window, silently lowering the effective limit below its configured value.
/// The compile-time assertion below enforces this.
pub const MAX_VEC_SIZE: usize = 1000;
// Ensure the cap never silently reduces the effective rate limit.
const _: () = assert!(
MAX_VEC_SIZE > MAX_QUERIES_PER_WINDOW as usize,
"MAX_VEC_SIZE must be strictly greater than MAX_QUERIES_PER_WINDOW to avoid silent data loss in the sliding-window rate limiter",
);
// ============================================================================
// Fee Calculation Constants
// ============================================================================
/// Maximum allowed fee in basis points (100% = 10000 bps).
///
/// This limit prevents accidentally setting fees above 100%.
/// Used in initialize() and update_fee() for validation.
/// - 1 bps = 0.01%
/// - 100 bps = 1%
/// - 10000 bps = 100%
pub const MAX_FEE_BPS: u32 = 10000;
/// Minimum fee charged per transaction, in stroops.
///
/// Prevents integer-division truncation from producing a zero fee for very
/// small amounts (e.g. amount < 400 stroops at 250 bps).
pub const MIN_FEE: i128 = 1;
/// Divisor for converting basis points to actual fee amounts.
///
/// Formula: fee_amount = amount * fee_bps / FEE_DIVISOR
/// Used in fee calculation functions throughout the contract.
/// - Value: 10000 (basis points scale)
pub const FEE_DIVISOR: i128 = 10000;
// ============================================================================
// Rate Limiting Configuration
// ============================================================================
/// Default maximum number of requests allowed per rate limit window.
///
/// Used during rate limit initialization to set the default request limit.
/// Can be updated by admin via update_rate_limit().
pub const DEFAULT_RATE_LIMIT_MAX_REQUESTS: u32 = 100;
/// Default rate limit window duration in seconds.
///
/// Used during rate limit initialization to set the default time window.
/// Can be updated by admin via update_rate_limit().
/// - Value: 60 seconds (1 minute)
pub const DEFAULT_RATE_LIMIT_WINDOW_SECONDS: u64 = 60;
// ── Abuse-protection sliding-window constants ────────────────────────────────
/// Sliding-window duration used by abuse_protection rate limiting (seconds).
pub const RATE_LIMIT_WINDOW_SECONDS: u64 = 60;
/// Maximum number of transfer actions allowed per sliding window.
pub const MAX_TRANSFERS_PER_WINDOW: u32 = 10;
/// Maximum number of cancellation actions allowed per sliding window.
pub const MAX_CANCELLATIONS_PER_WINDOW: u32 = 5;
/// Maximum number of query actions allowed per sliding window.
pub const MAX_QUERIES_PER_WINDOW: u32 = 100;
/// Minimum seconds that must elapse between consecutive transfer/settlement actions.
pub const TRANSFER_COOLDOWN_SECONDS: u64 = 5;
// ============================================================================
// Daily Send Limits
// ============================================================================
/// Daily send limit rolling window duration in seconds.
///
/// Used to enforce daily sending limits per user. Transactions within this
/// window are counted toward the daily limit.
/// - Value: 86400 seconds (24 hours)
pub const DAILY_LIMIT_WINDOW_SECONDS: u64 = 24 * 60 * 60;
/// Default currency code for daily send limits.
///
/// Used when no specific currency is provided for daily limit checks.
/// - Value: "USDC" (USD Coin)
pub const DEFAULT_DAILY_LIMIT_CURRENCY: &str = "USDC";
/// Default country code for daily send limits.
///
/// Used when no specific country is provided for daily limit checks.
/// - Value: "GLOBAL" (applies to all countries)
pub const DEFAULT_DAILY_LIMIT_COUNTRY: &str = "GLOBAL";
/// Rolling sender volume window for discount tiers.
///
/// Used to calculate high-volume sender fee discounts in a 30-day window.
pub const SENDER_VOLUME_DISCOUNT_WINDOW_SECONDS: u64 = 30 * 24 * 60 * 60;
/// Bucket duration for sender volume aggregation.
///
/// Aggregates transaction volume into daily buckets to keep storage efficient
/// while providing a rolling 30-day view.
pub const SENDER_VOLUME_DISCOUNT_BUCKET_SECONDS: u64 = 24 * 60 * 60;
/// High-volume sender threshold for discounted fees.
///
/// Senders whose 30-day volume meets or exceeds this threshold pay the
/// discounted fee tier instead of the default platform fee.
pub const SENDER_VOLUME_TIER_THRESHOLD_10K: i128 = 10_000;
/// Discounted fee basis points for senders above the high-volume threshold.
///
/// This is the fee applied when the sender reaches the 30-day volume threshold.
pub const SENDER_VOLUME_TIER_FEE_BPS_10K: u32 = 150;
// ============================================================================
// Storage and Event Schema
// ============================================================================
/// Schema version for event structures.
///
/// Used to track event format versions for forward compatibility.
/// Increment when making breaking changes to event structures.
pub const SCHEMA_VERSION: u32 = 1;
/// Flag indicating a settlement has been executed.
///
/// Used in storage to mark settlements as completed and prevent duplicates.
pub const SETTLEMENT_EXECUTED_FLAG: u32 = 1;
/// Flag indicating a settlement event has been emitted.
///
/// Used in storage to track event emission status.
pub const SETTLEMENT_EVENT_EMITTED_FLAG: u32 = 1 << 1;
// ============================================================================
// Migration Configuration
// ============================================================================
/// Migration snapshot version for forward compatibility.
///
/// Used to track migration snapshot format versions. Increment when making
/// breaking changes to migration data structures.
pub const MIGRATION_SNAPSHOT_VERSION: u32 = 1;
// ============================================================================
// Idempotency TTL (#841)
// ============================================================================
/// Default TTL for idempotency records: 7 days in seconds.
///
/// Records older than this can be removed by `cleanup_expired_idempotency_keys`.
/// The value matches the typical settlement window so that stale deduplication
/// keys do not accumulate in persistent storage indefinitely.
pub const IDEMPOTENCY_TTL_SECONDS: u64 = 7 * 24 * 60 * 60; // 604_800 seconds
// ============================================================================
// Circuit Breaker Cooldown
// ============================================================================
/// Default post-unpause cooldown period in seconds (1 hour).
///
/// During this window after an emergency unpause, per-sender rate limits are
/// halved to throttle traffic and prevent immediate exploitation.
pub const DEFAULT_COOLDOWN_PERIOD_SECONDS: u64 = 3_600;
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_batch_size_constants() {
assert!(MAX_BATCH_SIZE > 0);
assert!(MAX_EXPIRED_BATCH_SIZE > 0);
assert!(MAX_MIGRATION_BATCH_SIZE > 0);
assert!(MAX_EXPIRED_BATCH_SIZE <= MAX_BATCH_SIZE);
}
#[test]
fn test_fee_constants() {
assert_eq!(MAX_FEE_BPS, 10000);
assert_eq!(FEE_DIVISOR, 10000);
}
#[test]
fn test_rate_limit_constants() {
assert!(DEFAULT_RATE_LIMIT_MAX_REQUESTS > 0);
assert!(DEFAULT_RATE_LIMIT_WINDOW_SECONDS > 0);
}
#[test]
fn test_daily_limit_constants() {
assert_eq!(DAILY_LIMIT_WINDOW_SECONDS, 86400);
assert_eq!(DEFAULT_DAILY_LIMIT_CURRENCY, "USDC");
assert_eq!(DEFAULT_DAILY_LIMIT_COUNTRY, "GLOBAL");
}
#[test]
fn test_schema_version() {
assert!(SCHEMA_VERSION > 0);
}
#[test]
fn test_settlement_flags() {
assert_eq!(SETTLEMENT_EXECUTED_FLAG, 1);
assert_eq!(SETTLEMENT_EVENT_EMITTED_FLAG, 2);
// Ensure flags don't overlap
assert_eq!(SETTLEMENT_EXECUTED_FLAG & SETTLEMENT_EVENT_EMITTED_FLAG, 0);
}
}