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
use crate::pallet::{Config, Pallet};
use common::{Balance, LiquiditySourceType, ToFeeAccount, TradingPair};
use frame_support::pallet_prelude::{Get, StorageVersion};
use frame_support::traits::OnRuntimeUpgrade;
use frame_support::weights::WeightMeter;
use frame_support::{
log::{error, info},
weights::Weight,
};
use sp_runtime::DispatchResult;
use sp_std::prelude::Vec;
use crate::{PoolProviders, Properties, Reserves, TotalIssuances, WeightInfo};
use ceres_liquidity_locker::LockerData;
use demeter_farming_platform::UserInfos;
use trading_pair::EnabledSources;
pub struct XYKPoolUpgrade<T, L>(core::marker::PhantomData<(T, L)>);
impl<T, L> XYKPoolUpgrade<T, L>
where
T: crate::Config,
L: Get<Vec<(T::AssetId, T::AssetId, T::DEXId)>>,
{
fn pull_out_user_from_pool(
weight_meter: &mut WeightMeter,
user_account: T::AccountId,
base_asset: T::AssetId,
target_asset: T::AssetId,
dex_id: T::DEXId,
lp_tokens: u128,
) -> DispatchResult {
weight_meter.check_accrue(
T::DbWeight::get()
.reads_writes(2, 2)
.saturating_add(<T as Config>::WeightInfo::withdraw_liquidity()),
);
UserInfos::<T>::mutate(&user_account, |user_infos| {
for user_info in user_infos.iter_mut() {
if user_info.is_farm == true
&& user_info.base_asset == base_asset
&& user_info.pool_asset == target_asset
{
user_info.pooled_tokens = 0;
}
}
});
LockerData::<T>::mutate_exists(&user_account, |user_lock_infos| {
if let Some(ref mut infos_vec) = *user_lock_infos {
infos_vec.retain(|user_info| {
user_info.asset_a != base_asset && user_info.asset_b != target_asset
});
if infos_vec.is_empty() {
*user_lock_infos = None;
}
}
});
Pallet::<T>::withdraw_liquidity_unchecked(
user_account.clone(),
dex_id,
base_asset,
target_asset,
lp_tokens,
1,
1,
)?;
Ok(())
}
fn remove_pool(
weight_meter: &mut WeightMeter,
dex_id: T::DEXId,
base_asset: T::AssetId,
target_asset: T::AssetId,
pool_account: T::AccountId,
) -> DispatchResult {
weight_meter.check_accrue(T::DbWeight::get().reads_writes(4, 8));
let (_, tech_acc_id) =
Pallet::<T>::tech_account_from_dex_and_asset_pair(dex_id, base_asset, target_asset)?;
let pair = TradingPair::<T::AssetId> {
base_asset_id: base_asset.clone(),
target_asset_id: target_asset.clone(),
};
EnabledSources::<T>::mutate(&dex_id, &pair, |opt_set| {
if let Some(sources) = opt_set.as_mut() {
sources.remove(&LiquiditySourceType::XYKPool);
}
});
Properties::<T>::remove(base_asset, target_asset);
let fee_acc_id = tech_acc_id
.to_fee_account()
.ok_or(crate::Error::<T>::FeeAccountIsInvalid)?;
technical::Pallet::<T>::deregister_tech_account_id(tech_acc_id)?;
technical::Pallet::<T>::deregister_tech_account_id(fee_acc_id)?;
Reserves::<T>::remove(&base_asset, &target_asset);
TotalIssuances::<T>::remove(&pool_account);
Ok(())
}
pub fn migrate(weight_meter: &mut WeightMeter) -> DispatchResult {
weight_meter.check_accrue(T::DbWeight::get().reads(1));
if StorageVersion::get::<Pallet<T>>() >= StorageVersion::new(3) {
info!("Migration to version 3 has already been applied");
return Ok(());
}
info!("Migrating PoolXYK to v3");
let swap_pairs_to_be_deleted: Vec<(T::AssetId, T::AssetId, T::DEXId)> = L::get();
for (base_asset, target_asset, dex_id) in swap_pairs_to_be_deleted {
weight_meter.check_accrue(T::DbWeight::get().reads(1));
let pool_account =
if let Some(pool_property) = Properties::<T>::get(&base_asset, &target_asset) {
pool_property.0
} else {
info!(
"Pool with base asset {:?} and target asset {:?} is not present, skipping",
base_asset, target_asset
);
continue;
};
info!(
"Pool with assets {:?} and {:?} reserves before liquidity withdrawal: {:?}",
base_asset,
target_asset,
Reserves::<T>::get(&base_asset, &target_asset)
);
let liquidity_holders: Vec<(T::AccountId, Balance)> =
PoolProviders::<T>::iter_prefix(&pool_account)
.inspect(|_| {
weight_meter.check_accrue(T::DbWeight::get().reads(1));
})
.collect();
for (user_account, lp_tokens) in liquidity_holders {
Self::pull_out_user_from_pool(
weight_meter,
user_account,
base_asset,
target_asset,
dex_id,
lp_tokens,
)?;
}
info!(
"Pool with assets {:?} and {:?} reserves after liquidity withdrawal: {:?}",
base_asset,
target_asset,
Reserves::<T>::get(&base_asset, &target_asset)
);
Self::remove_pool(weight_meter, dex_id, base_asset, target_asset, pool_account)?;
}
weight_meter.check_accrue(T::DbWeight::get().writes(1));
StorageVersion::new(3).put::<Pallet<T>>();
Ok(())
}
}
impl<T, L> OnRuntimeUpgrade for XYKPoolUpgrade<T, L>
where
T: crate::Config,
L: Get<Vec<(T::AssetId, T::AssetId, T::DEXId)>>,
{
fn on_runtime_upgrade() -> Weight {
let mut weight_meter = WeightMeter::max_limit();
if let Err(err) =
frame_support::storage::with_storage_layer(|| Self::migrate(&mut weight_meter))
{
error!("Failed to migrate PoolXYK to v3: {:?}, rollback", err);
} else {
info!("Successfully migrated PoolXYK to v3");
};
weight_meter.consumed
}
#[cfg(feature = "try-runtime")]
fn pre_upgrade() -> Result<Vec<u8>, &'static str> {
frame_support::ensure!(
StorageVersion::get::<Pallet<T>>() == StorageVersion::new(2),
"must upgrade linearly"
);
Ok(Vec::new())
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(_state: Vec<u8>) -> Result<(), &'static str> {
frame_support::ensure!(
StorageVersion::get::<Pallet<T>>() == StorageVersion::new(3),
"should be upgraded to version 3"
);
Ok(())
}
}