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
// Copyright 2021-2022 Semantic Network Ltd.
// This file is part of Tidechain.

// Tidechain is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// Tidechain is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with Tidechain.  If not, see <http://www.gnu.org/licenses/>.
#![cfg_attr(not(feature = "std"), no_std)]

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

#[cfg(feature = "runtime-benchmarks")]
mod benchmarking;

pub mod weights;
pub use weights::*;

// Re-export pallet items so that they can be accessed from the crate namespace.
pub use pallet::*;

#[frame_support::pallet]
pub mod pallet {
  use super::*;
  use frame_support::{
    inherent::Vec,
    pallet_prelude::*,
    traits::{
      fungibles::{Inspect, InspectHold, Mutate, Transfer},
      OriginTrait,
    },
    PalletId,
  };
  use frame_system::{pallet_prelude::*, RawOrigin};
  use sp_runtime::traits::{AccountIdConversion, StaticLookup};
  use sp_std::vec;
  use tidefi_primitives::{
    pallet::AssetRegistryExt, AssetId, Balance, BalanceInfo, CurrencyBalance, CurrencyId,
    CurrencyMetadata,
  };

  type CurrenciesMetadata = (CurrencyId, CurrencyMetadata<Vec<u8>>);
  type AssetGenesis<T> = (
    CurrencyId,
    Vec<u8>,
    Vec<u8>,
    u8,
    Vec<(
      <T as frame_system::Config>::AccountId,
      <T as pallet_assets::Config>::Balance,
    )>,
  );

  /// Asset registry configuration
  #[pallet::config]
  pub trait Config:
    frame_system::Config + pallet_assets::Config<AssetId = AssetId, Balance = Balance>
  {
    /// Events
    type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

    /// Pallet ID
    #[pallet::constant]
    type AssetRegistryPalletId: Get<PalletId>;

    /// Weights
    type WeightInfo: WeightInfo;

    /// Tidechain currency wrapper
    type CurrencyTidefi: Inspect<Self::AccountId, AssetId = CurrencyId, Balance = Balance>
      + Mutate<Self::AccountId, AssetId = CurrencyId, Balance = Balance>
      + Transfer<Self::AccountId, AssetId = CurrencyId, Balance = Balance>
      + InspectHold<Self::AccountId, AssetId = CurrencyId, Balance = Balance>;
  }

  #[pallet::pallet]
  #[pallet::generate_store(pub (super) trait Store)]
  pub struct Pallet<T>(_);

  /// Assets Account ID owner
  #[pallet::storage]
  #[pallet::getter(fn account_id)]
  pub type AssetRegistryAccountId<T: Config> = StorageValue<_, T::AccountId, OptionQuery>;

  /// Genesis configuration
  #[pallet::genesis_config]
  pub struct GenesisConfig<T: Config> {
    /// Assets to create on initialization
    /// \[currency_id, name, symbol, decimals\]
    pub assets: Vec<AssetGenesis<T>>,
    /// Assets owner
    /// Only this account can modify storage on this pallet.
    pub account: T::AccountId,
  }

  #[cfg(feature = "std")]
  impl<T: Config> Default for GenesisConfig<T> {
    fn default() -> Self {
      Self {
        // empty assets by default
        assets: Vec::new(),
        // We use pallet account ID by default,
        // but should always be set in the genesis config.
        account: T::AssetRegistryPalletId::get().into_account_truncating(),
      }
    }
  }

  #[pallet::genesis_build]
  impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {
    fn build(&self) {
      // 1. Save asset registry account id
      AssetRegistryAccountId::<T>::put(self.account.clone());

      // 2. Loop through all currency defined in our genesis config
      for (currency_id, name, symbol, decimals, pre_filled_account) in self.assets.clone() {
        // If it's a wrapped token, register it with pallet_assets
        if let CurrencyId::Wrapped(asset_id) = currency_id {
          Pallet::<T>::register_asset(asset_id, name, symbol, decimals, 1)
            .expect("Unable to register asset");
        }

        for (account_id, mint_amount) in pre_filled_account {
          T::CurrencyTidefi::mint_into(currency_id, &account_id, mint_amount)
            .expect("Unable to mint asset");
        }
      }
    }
  }

  #[pallet::event]
  #[pallet::generate_deposit(pub(super) fn deposit_event)]
  pub enum Event<T: Config> {
    /// Asset was registered. \[currency_id\]
    Registered(CurrencyId),
    /// Asset was updated. \[currency_id, is_enabled\]
    StatusChanged(CurrencyId, bool),
  }

  // Errors inform users that something went wrong.
  #[pallet::error]
  pub enum Error<T> {
    /// The access to the Asset registry pallet is not allowed for this account ID.
    AccessDenied,
    /// Asset ID is not registered in the asset-registry.
    AssetNotRegistered,
    /// Asset ID status is already the same as requested.
    NoStatusChangeRequested,
    /// Asset is already registered.
    AssetAlreadyRegistered,
    /// Invalid Currency Id
    CurrencyIdNotValid,
  }

  #[pallet::call]
  impl<T: Config> Pallet<T> {
    /// Register new asset on chain.
    ///
    /// - `currency_id`: The currency ID to register
    /// - `name`: Currency name. Ex: `Bitcoin`
    /// - `symbol`: Currency symbol. Ex: `BTC`
    /// - `decimals`: Number of decimals for the asset. Ex: `8`
    /// - `existential_deposit`: Number of token required to keep the balance alive. Ex: `1`
    ///
    /// Emits `Registered` event when successful.
    ///
    /// Weight: `O(1)`
    #[pallet::call_index(0)]
    #[pallet::weight(<T as Config>::WeightInfo::set_status())]
    pub fn register(
      origin: OriginFor<T>,
      currency_id: CurrencyId,
      name: Vec<u8>,
      symbol: Vec<u8>,
      decimals: u8,
      existential_deposit: <T as pallet_assets::Config>::Balance,
    ) -> DispatchResult {
      // 1. Make sure it's signed from the asset-registry owner
      ensure!(
        Some(ensure_signed(origin)?) == Self::account_id(),
        Error::<T>::AccessDenied
      );

      // 2. Make sure the asset isn't already registered
      ensure!(
        !Self::is_currency_exist(currency_id),
        Error::<T>::AssetAlreadyRegistered
      );

      // 3. If it's a wrapped token, let's register it with pallet_assets
      if let CurrencyId::Wrapped(asset_id) = currency_id {
        Self::register_asset(asset_id, name, symbol, decimals, existential_deposit)?;
      }

      // 5. Emit new registered currency
      Self::deposit_event(<Event<T>>::Registered(currency_id));

      Ok(())
    }

    /// Update asset status.
    ///
    /// - `currency_id`: The currency ID to register
    /// - `is_enabled`: Is the currency enabled on chain?
    ///
    /// Emits `StatusChanged` event when successful.
    ///
    /// Weight: `O(1)`
    #[pallet::call_index(1)]
    #[pallet::weight(<T as Config>::WeightInfo::set_status())]
    pub fn set_status(
      origin: OriginFor<T>,
      currency_id: CurrencyId,
      is_enabled: bool,
    ) -> DispatchResult {
      // 1. Make sure it's signed from the asset-registry owner
      ensure!(
        Some(ensure_signed(origin)?) == Self::account_id(),
        Error::<T>::AccessDenied
      );

      // 2. Make sure the currency is already registered
      ensure!(
        Self::is_currency_exist(currency_id),
        Error::<T>::AssetNotRegistered
      );

      // 3. Freeze/unfreeze at the chain level, do nothing if
      // we requested a TDFY freeze
      if let CurrencyId::Wrapped(asset_id) = currency_id {
        match is_enabled {
          true => {
            // unfreeze asset
            pallet_assets::Pallet::<T>::thaw_asset(
              RawOrigin::Signed(T::AssetRegistryPalletId::get().into_account_truncating()).into(),
              asset_id.into(),
            )?;
          }
          false => {
            // freeze asset
            pallet_assets::Pallet::<T>::freeze_asset(
              RawOrigin::Signed(T::AssetRegistryPalletId::get().into_account_truncating()).into(),
              asset_id.into(),
            )?;
          }
        };
      }

      // 4. Emit new registered currency
      Self::deposit_event(<Event<T>>::StatusChanged(currency_id, is_enabled));

      Ok(())
    }
  }

  impl<T: Config> Pallet<T> {
    fn register_asset(
      asset_id: T::AssetId,
      name: Vec<u8>,
      symbol: Vec<u8>,
      decimals: u8,
      existential_deposit: <T as pallet_assets::Config>::Balance,
    ) -> Result<(), DispatchError> {
      // 1. Create asset
      pallet_assets::Pallet::<T>::force_create(
        T::RuntimeOrigin::root(),
        asset_id.into(),
        // make the pallet account id the owner, so only this pallet can handle the funds.
        T::Lookup::unlookup(T::AssetRegistryPalletId::get().into_account_truncating()),
        true,
        existential_deposit,
      )?;

      // 2. Set metadata
      pallet_assets::Pallet::<T>::force_set_metadata(
        RawOrigin::Signed(T::AssetRegistryPalletId::get().into_account_truncating()).into(),
        asset_id.into(),
        name,
        symbol,
        decimals,
        false,
      )?;

      Ok(())
    }

    pub fn is_currency_exist(currency_id: CurrencyId) -> bool {
      match currency_id {
        // TDFY always exist
        CurrencyId::Tdfy => true,
        CurrencyId::Wrapped(asset_id) => {
          pallet_assets::Pallet::<T>::asset_details(asset_id).is_some()
        }
      }
    }

    pub fn get_account_balance(
      account_id: &T::AccountId,
      asset_id: CurrencyId,
    ) -> Result<CurrencyBalance<BalanceInfo>, DispatchError> {
      // we use `reducible_balance` to return the real available value for the account
      // we also force the `keep_alive`

      // FIXME: Review the `keep_alive` system for TDFY & assets, we should probably have
      // a user settings, where they can enable or force opting-out to keep-alive.
      // that mean if they use all of their funds, the account is deleted from the chain
      // and and will be re-created on next deposit. this could drain all persistent settings
      // of the user as well
      let balance = T::CurrencyTidefi::reducible_balance(asset_id, account_id, true);
      let reserved = T::CurrencyTidefi::balance_on_hold(asset_id, account_id);
      Ok(CurrencyBalance::<BalanceInfo> {
        available: BalanceInfo { amount: balance },
        reserved: BalanceInfo { amount: reserved },
      })
    }

    pub fn get_assets() -> Result<Vec<CurrenciesMetadata>, DispatchError> {
      let mut final_assets = vec![(
        CurrencyId::Tdfy,
        CurrencyMetadata {
          name: "Tidefi Token".into(),
          symbol: "TDFY".into(),
          decimals: 12,
          is_frozen: false,
        },
      )];

      let mut asset_metadatas = pallet_assets::Metadata::<T>::iter()
        .map(|(asset_id, asset_metadata)| {
          (
            CurrencyId::Wrapped(asset_id),
            CurrencyMetadata {
              name: asset_metadata.name.into(),
              symbol: asset_metadata.symbol.into(),
              decimals: asset_metadata.decimals,
              is_frozen: asset_metadata.is_frozen,
            },
          )
        })
        .collect();

      final_assets.append(&mut asset_metadatas);

      Ok(final_assets)
    }

    pub fn get_account_balances(
      account_id: &T::AccountId,
    ) -> Result<Vec<(CurrencyId, CurrencyBalance<BalanceInfo>)>, DispatchError> {
      let mut final_balances = vec![(
        CurrencyId::Tdfy,
        Self::get_account_balance(account_id, CurrencyId::Tdfy)?,
      )];
      let mut asset_balances = pallet_assets::Account::<T>::iter_prefix(account_id)
        .map(|(asset_id, balance)| {
          (
            CurrencyId::Wrapped(asset_id),
            CurrencyBalance::<BalanceInfo> {
              available: BalanceInfo {
                amount: balance.balance,
              },
              reserved: BalanceInfo {
                amount: balance.reserved,
              },
            },
          )
        })
        .collect();
      final_balances.append(&mut asset_balances);
      Ok(final_balances)
    }
  }

  impl<T: Config> AssetRegistryExt for Pallet<T> {
    fn is_currency_enabled(currency_id: CurrencyId) -> bool {
      match currency_id {
        // we can't disable TDFY
        CurrencyId::Tdfy => true,
        CurrencyId::Wrapped(asset_id) => pallet_assets::Pallet::<T>::asset_details(asset_id)
          .map(|detail| detail.status == pallet_assets::AssetStatus::Live)
          .unwrap_or(false),
      }
    }
  }
}