forked from Invoice-Liquidity-Network/ILN-Smart-Contract
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstorage.rs
More file actions
515 lines (451 loc) · 16.1 KB
/
Copy pathstorage.rs
File metadata and controls
515 lines (451 loc) · 16.1 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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
use soroban_sdk::{contracttype, Address, BytesN, Env, Symbol};
use crate::config::Config;
use crate::invoice::{
AppealRecord, Invoice, InvoiceCore, InvoiceMetadata, LpFundRequest, ReputationScore,
};
#[contracttype]
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DataKey {
// Instance Storage
Admin,
Config,
FeeRate,
MaxDiscountRate,
DistributionContract,
Paused,
/// Minimum payer reputation required to fund an invoice (Issue #28). Default 0.
MinPayerReputation,
NextInvoiceId,
// Persistent Storage
Invoice(u64), // DEPRECATED: kept for backwards compatibility
InvoiceCore(u64), // NEW: hot-path core data (accessed >95% of time)
InvoiceMetadata(u64), // NEW: cold-path metadata (accessed <5% of time)
InvoiceCount,
Token,
PayerScore(Address),
InvoiceFunders(u64),
ApprovedToken(Address),
TokenList,
/// Decimal precision for each allowlisted token (e.g. 6 for USDC, 7 for XLM).
TokenDecimals(Address),
/// Detailed reputation profile per address (Issue #26).
Reputation(Address),
Appeal(u64),
PreDefaultPayerScore(u64),
LpScore(Address),
FundQueue(u64),
QueueResolution(u64),
/// Ledger sequence when the first LP joined the fund queue for an invoice.
/// Used to enforce a minimum maturity delay before `resolve_fund_queue` may
/// be called, preventing MEV / front-running (Issue #MEV-1).
FundQueueOpenedAt(u64),
// Stats (Persistent)
TotalInvoices,
TotalFunded,
TotalPaid,
TotalVolumeUsdc,
TotalVolumeEurc,
TotalVolumeXlm,
TokenVolume(Address),
/// Referral counts keyed by fixed-size code
ReferralCount(BytesN<32>),
Dispute(u64),
SubmitterInvoices(Address),
LpInvoices(Address),
/// Fixed-size min-heap of the top payers by reputation score (Issue #77).
TopPayersHeap,
/// NFT Metadata storage (Issue #423)
InvoiceNft(u64),
/// NFT Owner tracking (Issue #423)
InvoiceNftOwner(u64),
/// Issue #533: Fee tier configuration — ordered list of (min_amount, fee_rate_bps).
FeeTiers,
/// Issue #539: Storage version tracking for migration safety.
StorageVersion,
/// Reentrancy guard lock (Issue #535)
ReentrancyLock,
/// Last ledger sequence when each rate-limited function was called (Issue #541).
/// Keyed by a Symbol representing the function name.
RateLimit(Symbol),
/// Issue #532: governance-controlled oracle registry default, keyed by feed type.
OracleRegistry(crate::oracle_registry::OracleFeedType),
/// Issue #532: per-token oracle override, takes priority over OracleRegistry.
TokenOracle(crate::oracle_registry::OracleFeedType, Address),
/// Issue #532: last recorded oracle health snapshot for a feed type + token.
OracleHealth(crate::oracle_registry::OracleFeedType, Address),
/// Issue #529: deployed insurance pool contract address, consulted by
/// claim_default() to compensate enrolled LPs on a confirmed default.
InsurancePool,
}
// ----------------------------------------------------------------
// Config Helpers
// ----------------------------------------------------------------
pub fn get_admin(env: &Env) -> Option<Address> {
env.storage().instance().get(&DataKey::Admin)
}
pub fn set_admin(env: &Env, admin: &Address) {
env.storage().instance().set(&DataKey::Admin, admin);
}
pub fn get_config(env: &Env) -> Option<Config> {
env.storage().instance().get(&DataKey::Config)
}
pub fn set_config(env: &Env, config: &Config) {
env.storage().instance().set(&DataKey::Config, config);
}
/// Issue #529: the configured insurance pool contract address, if any.
pub fn get_insurance_pool(env: &Env) -> Option<Address> {
env.storage().instance().get(&DataKey::InsurancePool)
}
pub fn set_insurance_pool(env: &Env, pool: &Address) {
env.storage().instance().set(&DataKey::InsurancePool, pool);
}
pub fn is_paused(env: &Env) -> bool {
env.storage()
.instance()
.get(&DataKey::Paused)
.unwrap_or(false)
}
pub fn set_paused(env: &Env, paused: bool) {
env.storage().instance().set(&DataKey::Paused, &paused);
}
// ----------------------------------------------------------------
// Invoice Helpers
// ----------------------------------------------------------------
/// Save invoice by splitting into hot and cold data for optimized storage.
///
/// This function saves the invoice in two separate storage entries:
/// - InvoiceCore: Contains frequently-accessed fields (>95% of operations)
/// - InvoiceMetadata: Contains rarely-accessed fields (<5% of operations)
///
/// This optimization reduces gas costs by:
/// 1. Minimizing serialization/deserialization of cold data on hot paths
/// 2. Reducing the size of data moved in/out of storage
///
/// **Gas savings:** ~10-15% on fund_invoice and mark_paid operations
pub fn save_invoice(env: &Env, invoice: &Invoice) {
let id = invoice.id;
// Save hot-path core data
let core_key = DataKey::InvoiceCore(id);
let core = invoice.to_core();
env.storage().persistent().set(&core_key, &core);
env.storage()
.persistent()
.extend_ttl(&core_key, 1_000_000, 2_000_000);
// Save cold-path metadata
let metadata_key = DataKey::InvoiceMetadata(id);
let metadata = invoice.to_metadata();
env.storage().persistent().set(&metadata_key, &metadata);
env.storage()
.persistent()
.extend_ttl(&metadata_key, 1_000_000, 2_000_000);
}
/// Load invoice by combining hot and cold data from storage.
///
/// This function reconstructs the full Invoice by loading:
/// - InvoiceCore: Hot-path data (always present)
/// - InvoiceMetadata: Cold-path data (always present after split)
///
/// Falls back to old Invoice key format for backwards compatibility
/// with data written before the split was implemented.
pub fn load_invoice(env: &Env, id: u64) -> Invoice {
// Try new split format first (preferred)
if let Some(core) = env
.storage()
.persistent()
.get::<DataKey, crate::invoice::InvoiceCore>(&DataKey::InvoiceCore(id))
{
if let Some(metadata) = env
.storage()
.persistent()
.get::<DataKey, crate::invoice::InvoiceMetadata>(&DataKey::InvoiceMetadata(id))
{
return core.with_metadata(metadata);
}
}
// Fall back to old format for backwards compatibility
env.storage()
.persistent()
.get(&DataKey::Invoice(id))
.expect("invoice not found")
}
pub fn invoice_exists(env: &Env, id: u64) -> bool {
// Check new split format first, then fall back to old format
env.storage().persistent().has(&DataKey::InvoiceCore(id))
|| env.storage().persistent().has(&DataKey::Invoice(id))
}
/// Load only the hot-path core data of an invoice.
///
/// This function is optimized for hot paths (fund_invoice, mark_paid)
/// that don't need metadata. Avoids deserializing cold data.
///
/// Returns None if invoice not found, panics with "invoice core not found"
/// if the core is missing (data corruption).
pub fn load_invoice_core(env: &Env, id: u64) -> crate::invoice::InvoiceCore {
// Try new split format first
if let Some(core) = env
.storage()
.persistent()
.get::<DataKey, crate::invoice::InvoiceCore>(&DataKey::InvoiceCore(id))
{
return core;
}
// Fall back to old format and extract core
if let Some(invoice) = env
.storage()
.persistent()
.get::<DataKey, Invoice>(&DataKey::Invoice(id))
{
return invoice.to_core();
}
panic!("invoice core not found");
}
/// Try to load only the hot-path core data of an invoice.
///
/// This function is optimized for hot paths and returns None if not found.
pub fn try_load_invoice_core(env: &Env, id: u64) -> Option<crate::invoice::InvoiceCore> {
// Try new split format first
if let Some(core) = env
.storage()
.persistent()
.get::<DataKey, crate::invoice::InvoiceCore>(&DataKey::InvoiceCore(id))
{
return Some(core);
}
// Fall back to old format and extract core
if let Some(invoice) = env
.storage()
.persistent()
.get::<DataKey, Invoice>(&DataKey::Invoice(id))
{
return Some(invoice.to_core());
}
None
}
pub fn read_next_invoice_id(env: &Env) -> u64 {
env.storage()
.instance()
.get(&DataKey::NextInvoiceId)
.unwrap_or(1)
}
pub fn write_next_invoice_id(env: &Env, id: u64) {
env.storage().instance().set(&DataKey::NextInvoiceId, &id);
}
pub fn next_invoice_id(env: &Env) -> Result<u64, crate::errors::ContractError> {
let current_id = read_next_invoice_id(env);
let next_id = current_id
.checked_add(1)
.ok_or(crate::errors::ContractError::ArithmeticOverflow)?;
write_next_invoice_id(env, next_id);
Ok(current_id)
}
// ----------------------------------------------------------------
// Funder List Helpers
// ----------------------------------------------------------------
pub fn get_invoice_funders(env: &Env, id: u64) -> soroban_sdk::Vec<(Address, i128)> {
env.storage()
.persistent()
.get(&DataKey::InvoiceFunders(id))
.unwrap_or_else(|| soroban_sdk::Vec::new(env))
}
pub fn save_invoice_funders(env: &Env, id: u64, funders: &soroban_sdk::Vec<(Address, i128)>) {
env.storage()
.persistent()
.set(&DataKey::InvoiceFunders(id), funders);
}
// ----------------------------------------------------------------
// Reputation Helpers
// ----------------------------------------------------------------
pub fn get_lp_score(env: &Env, lp: &Address) -> u32 {
env.storage()
.persistent()
.get(&DataKey::LpScore(lp.clone()))
.unwrap_or(50)
}
pub fn set_lp_score(env: &Env, lp: &Address, score: u32) {
let score = score.min(100);
env.storage()
.persistent()
.set(&DataKey::LpScore(lp.clone()), &score);
}
// ----------------------------------------------------------------
// LP Queue Helpers
// ----------------------------------------------------------------
pub fn get_fund_queue(env: &Env, invoice_id: u64) -> soroban_sdk::Vec<LpFundRequest> {
env.storage()
.persistent()
.get(&DataKey::FundQueue(invoice_id))
.unwrap_or_else(|| soroban_sdk::Vec::new(env))
}
pub fn save_fund_queue(env: &Env, invoice_id: u64, queue: &soroban_sdk::Vec<LpFundRequest>) {
env.storage()
.persistent()
.set(&DataKey::FundQueue(invoice_id), queue);
}
pub fn get_queue_resolution(env: &Env, invoice_id: u64) -> Option<Address> {
env.storage()
.persistent()
.get(&DataKey::QueueResolution(invoice_id))
}
pub fn save_queue_resolution(env: &Env, invoice_id: u64, approved_lp: &Address) {
env.storage()
.persistent()
.set(&DataKey::QueueResolution(invoice_id), approved_lp);
}
/// Record the ledger sequence when the first LP joined the fund queue.
/// Must only be called once per invoice (when the queue transitions from empty
/// to non-empty). Subsequent joins do not overwrite this timestamp.
pub fn try_set_fund_queue_opened_at(env: &Env, invoice_id: u64) {
let key = DataKey::FundQueueOpenedAt(invoice_id);
if !env.storage().persistent().has(&key) {
env.storage()
.persistent()
.set(&key, &env.ledger().sequence());
}
}
/// Return the ledger sequence when the fund queue for `invoice_id` was first
/// opened (i.e. the first LP join), or `None` if the queue is still empty.
pub fn get_fund_queue_opened_at(env: &Env, invoice_id: u64) -> Option<u32> {
env.storage()
.persistent()
.get(&DataKey::FundQueueOpenedAt(invoice_id))
}
// ----------------------------------------------------------------
// Appeal Helpers
// ----------------------------------------------------------------
pub fn get_appeal(env: &Env, invoice_id: u64) -> Option<AppealRecord> {
env.storage().persistent().get(&DataKey::Appeal(invoice_id))
}
pub fn save_appeal(env: &Env, invoice_id: u64, record: &AppealRecord) {
env.storage()
.persistent()
.set(&DataKey::Appeal(invoice_id), record);
}
pub fn save_pre_default_payer_score(env: &Env, invoice_id: u64, score: u32) {
env.storage()
.persistent()
.set(&DataKey::PreDefaultPayerScore(invoice_id), &score);
}
pub fn get_pre_default_payer_score(env: &Env, invoice_id: u64) -> Option<u32> {
env.storage()
.persistent()
.get(&DataKey::PreDefaultPayerScore(invoice_id))
}
// ----------------------------------------------------------------
// Contract Stats Helpers
// ----------------------------------------------------------------
/// In-memory stats accumulator for optimizing batch updates.
/// Use this struct to accumulate multiple stat changes and commit
/// them with a single storage operation for better gas efficiency.
#[derive(Clone, Debug)]
pub struct StatsAccumulator {
pub invoices_delta: i64,
pub funded_delta: i64,
pub paid_delta: i64,
}
impl StatsAccumulator {
pub fn new() -> Self {
StatsAccumulator {
invoices_delta: 0,
funded_delta: 0,
paid_delta: 0,
}
}
pub fn add_invoice(&mut self) {
self.invoices_delta = self.invoices_delta.saturating_add(1);
}
pub fn add_funded(&mut self) {
self.funded_delta = self.funded_delta.saturating_add(1);
}
pub fn add_paid(&mut self) {
self.paid_delta = self.paid_delta.saturating_add(1);
}
/// Commit accumulated deltas to persistent storage.
/// This is more efficient than calling increment_* functions multiple times.
pub fn commit(self, env: &Env) {
if self.invoices_delta > 0 {
let current: u64 = env
.storage()
.persistent()
.get(&DataKey::TotalInvoices)
.unwrap_or(0);
env.storage().persistent().set(
&DataKey::TotalInvoices,
¤t.saturating_add(self.invoices_delta as u64),
);
}
if self.funded_delta > 0 {
let current: u64 = env
.storage()
.persistent()
.get(&DataKey::TotalFunded)
.unwrap_or(0);
env.storage().persistent().set(
&DataKey::TotalFunded,
¤t.saturating_add(self.funded_delta as u64),
);
}
if self.paid_delta > 0 {
let current: u64 = env
.storage()
.persistent()
.get(&DataKey::TotalPaid)
.unwrap_or(0);
env.storage().persistent().set(
&DataKey::TotalPaid,
¤t.saturating_add(self.paid_delta as u64),
);
}
}
}
pub fn increment_total_invoices(env: &Env) {
let current: u64 = env
.storage()
.persistent()
.get(&DataKey::TotalInvoices)
.unwrap_or(0);
env.storage()
.persistent()
.set(&DataKey::TotalInvoices, ¤t.saturating_add(1));
}
pub fn increment_total_funded(env: &Env) {
let current: u64 = env
.storage()
.persistent()
.get(&DataKey::TotalFunded)
.unwrap_or(0);
env.storage()
.persistent()
.set(&DataKey::TotalFunded, ¤t.saturating_add(1));
}
pub fn increment_total_paid(env: &Env) {
let current: u64 = env
.storage()
.persistent()
.get(&DataKey::TotalPaid)
.unwrap_or(0);
env.storage()
.persistent()
.set(&DataKey::TotalPaid, ¤t.saturating_add(1));
}
// add_volume moved to invoice.rs where the configured token addresses are available
/// Get current total invoices count.
pub fn get_total_invoices(env: &Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::TotalInvoices)
.unwrap_or(0)
}
/// Get current total funded count.
pub fn get_total_funded(env: &Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::TotalFunded)
.unwrap_or(0)
}
/// Get current total paid count.
pub fn get_total_paid(env: &Env) -> u64 {
env.storage()
.persistent()
.get(&DataKey::TotalPaid)
.unwrap_or(0)
}