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
#![cfg_attr(not(feature = "std"), no_std)]
#![allow(clippy::all)]
use codec::{Decode, Encode};
use common::prelude::Balance;
use common::{AssetInfoProvider, FromGenericPair, SwapAction, SwapRulesValidation};
use frame_support::dispatch::{DispatchError, DispatchResult};
use frame_support::{ensure, Parameter};
use sp_runtime::traits::{MaybeSerializeDeserialize, Member};
use sp_runtime::RuntimeDebug;
use common::TECH_ACCOUNT_MAGIC_PREFIX;
use sp_core::H256;
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
type AccountIdOf<T> = <T as frame_system::Config>::AccountId;
type TechAccountIdOf<T> = <T as Config>::TechAccountId;
type AssetIdOf<T> = <T as assets::Config>::AssetId;
type TechAssetIdOf<T> = <T as Config>::TechAssetId;
type DEXIdOf<T> = <T as common::Config>::DEXId;
#[derive(Clone, Eq, PartialEq, RuntimeDebug, Encode, Decode, scale_info::TypeInfo)]
#[scale_info(skip_type_params(T))]
pub struct PendingSwap<T: Config> {
pub source: T::AccountId,
pub action: T::SwapAction,
pub condition: T::Condition,
}
pub fn tech_account_id_encoded_to_account_id_32(tech_account_id: &[u8]) -> H256 {
use ::core::hash::Hasher;
let mut h0 = twox_hash::XxHash::with_seed(0);
let mut h1 = twox_hash::XxHash::with_seed(1);
h0.write(tech_account_id);
h1.write(tech_account_id);
let r0 = h0.finish();
let r1 = h1.finish();
let mut repr: H256 = H256::zero();
repr[..16].copy_from_slice(&TECH_ACCOUNT_MAGIC_PREFIX);
repr[16..24].copy_from_slice(&r0.to_le_bytes());
repr[24..].copy_from_slice(&r1.to_le_bytes());
repr
}
impl<T: Config> Pallet<T> {
pub fn create_swap_unchecked(
source: AccountIdOf<T>,
action: &T::SwapAction,
base_asset_id: &T::AssetId,
) -> DispatchResult {
common::with_transaction(|| {
action.reserve(&source, base_asset_id)?;
if action.is_able_to_claim() {
if action.instant_auto_claim_used() {
if action.claim(&source) {
Self::deposit_event(Event::SwapSuccess(source));
} else if !action.triggered_auto_claim_used() {
action.cancel(&source);
} else {
return Err(Error::<T>::NotImplemented)?;
}
} else {
return Err(Error::<T>::NotImplemented)?;
}
} else if action.triggered_auto_claim_used() {
return Err(Error::<T>::NotImplemented)?;
} else {
return Err(Error::<T>::NotImplemented)?;
}
Ok(())
})
}
pub fn create_swap(
source: AccountIdOf<T>,
action: &mut T::SwapAction,
base_asset_id: &T::AssetId,
) -> DispatchResult {
ensure!(
!action.is_abstract_checking(),
Error::<T>::OperationWithAbstractCheckingIsImposible
);
action.prepare_and_validate(Some(&source), base_asset_id)?;
Pallet::<T>::create_swap_unchecked(source, action, base_asset_id)
}
pub fn tech_account_id_to_account_id(
tech_account_id: &T::TechAccountId,
) -> Result<T::AccountId, DispatchError> {
let repr = tech_account_id_encoded_to_account_id_32(&tech_account_id.encode());
T::AccountId::decode(&mut &repr[..]).map_err(|_| Error::<T>::DecodeAccountIdFailed.into())
}
pub fn lookup_tech_account_id(
account_id: &T::AccountId,
) -> Result<T::TechAccountId, DispatchError> {
Self::tech_account(account_id).ok_or(Error::<T>::AssociatedAccountIdNotFound.into())
}
pub fn ensure_account_registered(
account_id: &T::AccountId,
) -> Result<T::TechAccountId, DispatchError> {
Self::lookup_tech_account_id(account_id)
.map_err(|_| Error::<T>::TechAccountIdIsNotRegistered.into())
}
pub fn ensure_tech_account_registered(tech_account_id: &T::TechAccountId) -> DispatchResult {
let account_id = Self::tech_account_id_to_account_id(tech_account_id)?;
Self::ensure_account_registered(&account_id).map(|_| ())
}
pub fn register_tech_account_id(tech_account_id: T::TechAccountId) -> DispatchResult {
let account_id = Self::tech_account_id_to_account_id(&tech_account_id)?;
if let Err(_) = Self::lookup_tech_account_id(&account_id) {
frame_system::Pallet::<T>::inc_providers(&account_id);
}
TechAccounts::<T>::insert(account_id, tech_account_id);
Ok(())
}
pub fn register_tech_account_id_if_not_exist(
tech_account_id: &T::TechAccountId,
) -> DispatchResult {
let account_id = Self::tech_account_id_to_account_id(tech_account_id)?;
if let Err(_) = Self::lookup_tech_account_id(&account_id) {
frame_system::Pallet::<T>::inc_providers(&account_id);
TechAccounts::<T>::insert(account_id, tech_account_id.clone());
}
Ok(())
}
pub fn deregister_tech_account_id(tech_account_id: T::TechAccountId) -> DispatchResult {
let account_id = Self::tech_account_id_to_account_id(&tech_account_id)?;
if let Ok(_) = Self::lookup_tech_account_id(&account_id) {
frame_system::Pallet::<T>::dec_providers(&account_id)?;
TechAccounts::<T>::remove(account_id);
}
Ok(())
}
pub fn transfer_in(
asset: &AssetIdOf<T>,
source: &T::AccountId,
tech_dest: &T::TechAccountId,
amount: Balance,
) -> DispatchResult {
let to = Self::tech_account_id_to_account_id(tech_dest)?;
Self::ensure_account_registered(&to)?;
assets::Pallet::<T>::transfer_from(asset, source, &to, amount)?;
Ok(())
}
pub fn transfer_out(
asset: &AssetIdOf<T>,
tech_source: &T::TechAccountId,
to: &<T as frame_system::Config>::AccountId,
amount: Balance,
) -> DispatchResult {
let from = Self::tech_account_id_to_account_id(tech_source)?;
Self::ensure_account_registered(&from)?;
assets::Pallet::<T>::transfer_from(asset, &from, to, amount)?;
Ok(())
}
pub fn transfer(
asset: &AssetIdOf<T>,
tech_source: &T::TechAccountId,
tech_dest: &T::TechAccountId,
amount: Balance,
) -> DispatchResult {
let from = Self::tech_account_id_to_account_id(tech_source)?;
Self::ensure_account_registered(&from)?;
let to = Self::tech_account_id_to_account_id(tech_dest)?;
Self::ensure_account_registered(&to)?;
assets::Pallet::<T>::transfer_from(asset, &from, &to, amount)
}
pub fn mint(
asset: &AssetIdOf<T>,
tech_dest: &T::TechAccountId,
amount: Balance,
) -> DispatchResult {
let account_id = Self::tech_account_id_to_account_id(tech_dest)?;
Self::ensure_account_registered(&account_id)?;
assets::Pallet::<T>::mint_to(asset, &account_id, &account_id, amount)
}
pub fn total_balance(
asset_id: &T::AssetId,
tech_id: &T::TechAccountId,
) -> Result<Balance, DispatchError> {
let account_id = Self::tech_account_id_to_account_id(tech_id)?;
Self::ensure_account_registered(&account_id)?;
assets::Pallet::<T>::total_balance(asset_id, &account_id)
}
}
pub use pallet::*;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_support::traits::StorageVersion;
use frame_system::pallet_prelude::*;
#[pallet::config]
pub trait Config: frame_system::Config + common::Config + assets::Config {
type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
type TechAssetId: Copy
+ Ord
+ Member
+ Parameter
+ Into<AssetIdOf<Self>>
+ From<AssetIdOf<Self>>;
type TechAccountId: Ord
+ Member
+ Parameter
+ Default
+ FromGenericPair
+ MaybeSerializeDeserialize
+ common::ToFeeAccount
+ common::ToXykTechUnitFromDEXAndTradingPair<
DEXIdOf<Self>,
common::TradingPair<Self::TechAssetId>,
> + common::ToOrderTechUnitFromDEXAndTradingPair<
DEXIdOf<Self>,
common::TradingPair<Self::TechAssetId>,
> + Into<common::TechAccountId<Self::AccountId, Self::TechAssetId, Self::DEXId>>;
type Trigger: Default + Copy + Member + Parameter;
type Condition: Default + Copy + Member + Parameter;
type SwapAction: common::SwapRulesValidation<Self::AccountId, Self::TechAccountId, Self::AssetId, Self>
+ Parameter;
}
const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);
#[pallet::pallet]
#[pallet::generate_store(pub(super) trait Store)]
#[pallet::storage_version(STORAGE_VERSION)]
#[pallet::without_storage_info]
pub struct Pallet<T>(PhantomData<T>);
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}
#[pallet::call]
impl<T: Config> Pallet<T> {}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
Minted(TechAssetIdOf<T>, TechAccountIdOf<T>, Balance, Balance),
Burned(TechAssetIdOf<T>, TechAccountIdOf<T>, Balance, Balance),
OutputTransferred(
TechAssetIdOf<T>,
TechAccountIdOf<T>,
AccountIdOf<T>,
Balance,
),
InputTransferred(
TechAssetIdOf<T>,
AccountIdOf<T>,
TechAccountIdOf<T>,
Balance,
),
SwapSuccess(AccountIdOf<T>),
}
#[pallet::error]
pub enum Error<T> {
StorageOverflow,
InsufficientBalance,
AlreadyExist,
InvalidProof,
SourceMismatch,
AlreadyClaimed,
ClaimActionMismatch,
DurationNotPassed,
OnlyRegularAsset,
OnlyRegularAccount,
OnlyRegularBalance,
OnlyPureTechnicalAccount,
Overflow,
TechAccountIdMustBePure,
UnableToGetReprFromTechAccountId,
RepresentativeMustBeSupported,
TechAccountIdIsNotRegistered,
NotImplemented,
DecodeAccountIdFailed,
AssociatedAccountIdNotFound,
OperationWithAbstractCheckingIsImposible,
}
#[pallet::storage]
#[pallet::getter(fn tech_account)]
pub(super) type TechAccounts<T: Config> =
StorageMap<_, Blake2_128Concat, AccountIdOf<T>, TechAccountIdOf<T>>;
#[pallet::genesis_config]
pub struct GenesisConfig<T: Config> {
pub register_tech_accounts: Vec<(AccountIdOf<T>, TechAccountIdOf<T>)>,
}
#[cfg(feature = "std")]
impl<T: Config> Default for GenesisConfig<T> {
fn default() -> Self {
Self {
register_tech_accounts: Default::default(),
}
}
}
#[pallet::genesis_build]
impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
fn build(&self) {
self.register_tech_accounts.iter().for_each(|(k, v)| {
frame_system::Pallet::<T>::inc_providers(k);
TechAccounts::<T>::insert(k, v);
});
}
}
}