-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathpool.rs
255 lines (224 loc) · 8.9 KB
/
pool.rs
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
use std::{ops::Div, str::FromStr, sync::Arc};
use ain_dftx::pool::*;
use anyhow::format_err;
use bitcoin::BlockHash;
// use bitcoin::Address;
use log::debug;
use rust_decimal::Decimal;
use rust_decimal_macros::dec;
use super::Context;
use crate::{
indexer::{tx_result, Index, Result},
model::{self, PoolSwapResult, TxResult},
repository::{RepositoryOps, SecondaryIndex},
storage::SortOrder,
Error, Services,
};
pub const AGGREGATED_INTERVALS: [u32; 2] = [
PoolSwapAggregatedInterval::OneDay as u32,
PoolSwapAggregatedInterval::OneHour as u32,
];
#[derive(Debug, Clone, Copy)]
pub enum PoolSwapAggregatedInterval {
OneDay = 60 * 60 * 24,
OneHour = 60 * 60,
}
impl Index for PoolSwap {
fn index(self, services: &Arc<Services>, ctx: &Context) -> Result<()> {
debug!("[Poolswap] Indexing...");
let txid = ctx.tx.txid;
let idx = ctx.tx_idx;
let Some(TxResult::PoolSwap(PoolSwapResult { to_amount, pool_id })) =
services.result.get(&txid)?
else {
// TODO fallback through getaccounthistory when indexing against non-oceanarchive node
// let address = Address::from_script(&self.to_script, bitcoin::Network::Bitcoin)
// .map_err(|e| format_err!("Error getting address from script: {e}"));
debug!("Missing swap result for {}", ctx.tx.txid.to_string());
return Err("Missing swap result".into());
};
let from = self.from_script;
let to = self.to_script;
let from_token_id = self.from_token_id.0;
let from_amount = self.from_amount;
let swap = model::PoolSwap {
id: format!("{}-{}", pool_id, txid),
// TODO: use hex::encode eg: sort: hex::encode(ctx.block.height + idx)
sort: format!("{}-{}", ctx.block.height, idx),
txid,
txno: idx,
from_amount,
from_token_id,
to_token_id: self.to_token_id.0,
to_amount,
pool_id,
from,
to,
block: ctx.block.clone(),
};
debug!("swap : {:?}", swap);
services
.pool
.by_id
.put(&(pool_id, ctx.block.height, idx), &swap)?;
for interval in AGGREGATED_INTERVALS {
let repository = &services.pool_swap_aggregated;
let mut prevs = repository
.by_key
.list(Some((pool_id, interval, i64::MAX)), SortOrder::Descending)?
.take(1)
.take_while(|item| match item {
Ok((k, _)) => k.0 == pool_id && k.1 == interval,
_ => true,
})
.map(|e| repository.by_key.retrieve_primary_value(e))
.collect::<Result<Vec<_>>>()?;
if prevs.is_empty() {
log::error!(
"index swap {txid}: Unable to find {pool_id}-{interval} for Aggregate Indexing"
);
continue;
}
let aggregated = prevs.first_mut();
if let Some(aggregated) = aggregated {
let amount = aggregated
.aggregated
.amounts
.get(&from_token_id.to_string())
.map(|amt| Decimal::from_str(amt))
.transpose()?
.unwrap_or(dec!(0));
let aggregated_amount = amount
.checked_add(Decimal::from(from_amount).div(dec!(100_000_000)))
.ok_or(Error::OverflowError)?;
aggregated.aggregated.amounts.insert(
from_token_id.to_string(),
format!("{:.8}", aggregated_amount),
);
let parts = aggregated.id.split('-').collect::<Vec<&str>>();
if parts.len() != 3 {
return Err(format_err!("Invalid poolswap aggregated id format").into());
};
let pool_id = parts[0].parse::<u32>()?;
let interval = parts[1].parse::<u32>()?;
let hash = parts[2].parse::<BlockHash>()?;
repository
.by_id
.put(&(pool_id, interval, hash), aggregated)?;
}
}
Ok(())
}
fn invalidate(&self, services: &Arc<Services>, ctx: &Context) -> Result<()> {
let txid = ctx.tx.txid;
let Some(TxResult::PoolSwap(PoolSwapResult { pool_id, .. })) =
services.result.get(&txid)?
else {
return Err("Missing swap result".into());
};
services
.pool
.by_id
.delete(&(pool_id, ctx.block.height, ctx.tx_idx))?;
tx_result::invalidate(services, &txid)?;
for interval in AGGREGATED_INTERVALS {
let repository = &services.pool_swap_aggregated;
let mut prevs = repository
.by_key
.list(Some((pool_id, interval, i64::MAX)), SortOrder::Descending)?
.take(1)
.take_while(|item| match item {
Ok((k, _)) => k.0 == pool_id && k.1 == interval,
_ => true,
})
.map(|e| repository.by_key.retrieve_primary_value(e))
.collect::<Result<Vec<_>>>()?;
if prevs.is_empty() {
log::error!(
"invalidate swap {txid}: Unable to find {pool_id}-{interval} for Aggregate Indexing"
);
continue;
}
let from_token_id = self.from_token_id.0;
let from_amount = self.from_amount;
let aggregated = prevs.first_mut();
if let Some(aggregated) = aggregated {
let amount = aggregated
.aggregated
.amounts
.get(&from_token_id.to_string())
.map(|amt| Decimal::from_str(amt))
.transpose()?
.unwrap_or(dec!(0));
let aggregated_amount = amount
.checked_sub(Decimal::from(from_amount).div(dec!(100_000_000)))
.ok_or(Error::UnderflowError)?;
aggregated.aggregated.amounts.insert(
from_token_id.to_string(),
format!("{:.8}", aggregated_amount),
);
let parts = aggregated.id.split('-').collect::<Vec<&str>>();
if parts.len() != 3 {
return Err(format_err!("Invalid poolswap aggregated id format").into());
};
let pool_id = parts[0].parse::<u32>()?;
let interval = parts[1].parse::<u32>()?;
let hash = parts[2].parse::<BlockHash>()?;
repository
.by_id
.put(&(pool_id, interval, hash), aggregated)?;
}
}
Ok(())
}
}
impl Index for CompositeSwap {
fn index(self, services: &Arc<Services>, ctx: &Context) -> Result<()> {
debug!("[CompositeSwap] Indexing...");
let txid = ctx.tx.txid;
let Some(TxResult::PoolSwap(PoolSwapResult { to_amount, .. })) =
services.result.get(&txid)?
else {
// TODO fallback through getaccounthistory when indexing against non-oceanarchive node
// let address =
// Address::from_script(&self.pool_swap.to_script, bitcoin::Network::Bitcoin)
// .map_err(|e| format_err!("Error getting address from script: {e}"));
debug!("Missing swap result for {}", txid.to_string());
return Err("Missing swap result".into());
};
let from = self.pool_swap.from_script;
let to = self.pool_swap.to_script;
for pool in self.pools.as_ref() {
let pool_id = pool.id.0 as u32;
let swap = model::PoolSwap {
id: format!("{}-{}", pool_id, txid),
sort: format!("{}-{}", ctx.block.height, ctx.tx_idx),
txid,
txno: ctx.tx_idx,
from_amount: self.pool_swap.from_amount,
from_token_id: self.pool_swap.from_token_id.0,
to_token_id: self.pool_swap.to_token_id.0,
to_amount,
pool_id,
from: from.clone(),
to: to.clone(),
block: ctx.block.clone(),
};
services
.pool
.by_id
.put(&(pool_id, ctx.block.height, ctx.tx_idx), &swap)?;
}
Ok(())
}
fn invalidate(&self, services: &Arc<Services>, ctx: &Context) -> Result<()> {
for pool in self.pools.as_ref() {
let pool_id = pool.id.0 as u32;
services
.pool
.by_id
.delete(&(pool_id, ctx.block.height, ctx.tx_idx))?;
}
tx_result::invalidate(services, &ctx.tx.txid)
}
}