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
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
//! # Redeem Pallet
//! Based on the [specification](https://spec.interlay.io/spec/redeem.html).

#![deny(warnings)]
#![cfg_attr(test, feature(proc_macro_hygiene))]
#![cfg_attr(not(feature = "std"), no_std)]

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

mod default_weights;
pub use default_weights::WeightInfo;

#[cfg(test)]
mod mock;

#[cfg(test)]
mod tests;

#[cfg(test)]
extern crate mocktopus;

#[cfg(test)]
use mocktopus::macros::mockable;

mod ext;
pub mod types;

#[doc(inline)]
pub use crate::types::{DefaultRedeemRequest, RedeemRequest, RedeemRequestStatus};

use crate::types::{BalanceOf, RedeemRequestExt, Version};
use bitcoin::types::FullTransactionProof;
use btc_relay::BtcAddress;
use currency::{Amount, Rounding};
use frame_support::{
    dispatch::{DispatchError, DispatchResult},
    ensure,
    pallet_prelude::Weight,
    transactional,
};
use frame_system::{ensure_root, ensure_signed};
use sp_core::H256;
use sp_std::{convert::TryInto, vec::Vec};
use types::DefaultVaultId;
use vault_registry::{
    types::{CurrencyId, DefaultVaultCurrencyPair},
    CurrencySource,
};

pub use pallet::*;

/// Complexity:
/// - `O(H + I + O + B)` where:
///   - `H` is the number of hashes in the merkle tree
///   - `I` is the number of transaction inputs
///   - `O` is the number of transaction outputs
///   - `B` is `transaction` size in bytes (length-fee-bounded)
fn weight_for_execute_redeem<T: Config>(proof: &FullTransactionProof) -> Weight {
    <T as Config>::WeightInfo::execute_redeem(
        proof.user_tx_proof.merkle_proof.hashes.len() as u32, // H
        proof.user_tx_proof.transaction.inputs.len() as u32,  // I
        proof.user_tx_proof.transaction.outputs.len() as u32, // O
        proof.user_tx_proof.tx_encoded_len,
    )
    .saturating_add(<T as Config>::WeightInfo::execute_redeem(
        proof.coinbase_proof.merkle_proof.hashes.len() as u32, // H
        proof.coinbase_proof.transaction.inputs.len() as u32,  // I
        proof.coinbase_proof.transaction.outputs.len() as u32, // O
        proof.coinbase_proof.tx_encoded_len,
    ))
}

#[frame_support::pallet]
pub mod pallet {
    use super::*;
    use frame_support::pallet_prelude::*;
    use frame_system::pallet_prelude::*;
    use primitives::VaultId;
    use vault_registry::types::DefaultVaultCurrencyPair;

    /// ## Configuration
    /// The pallet's configuration trait.
    #[pallet::config]
    pub trait Config: frame_system::Config + vault_registry::Config + btc_relay::Config + fee::Config {
        /// The overarching event type.
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;

        /// Weight information for the extrinsics in this module.
        type WeightInfo: WeightInfo;
    }

    #[pallet::event]
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
    pub enum Event<T: Config> {
        RequestRedeem {
            redeem_id: H256,
            redeemer: T::AccountId,
            vault_id: DefaultVaultId<T>,
            amount: BalanceOf<T>,
            fee: BalanceOf<T>,
            premium: BalanceOf<T>,
            btc_address: BtcAddress,
            transfer_fee: BalanceOf<T>,
        },
        LiquidationRedeem {
            redeemer: T::AccountId,
            amount: BalanceOf<T>,
        },
        ExecuteRedeem {
            redeem_id: H256,
            redeemer: T::AccountId,
            vault_id: DefaultVaultId<T>,
            amount: BalanceOf<T>,
            fee: BalanceOf<T>,
            transfer_fee: BalanceOf<T>,
        },
        CancelRedeem {
            redeem_id: H256,
            redeemer: T::AccountId,
            vault_id: DefaultVaultId<T>,
            slashed_amount: BalanceOf<T>,
            status: RedeemRequestStatus,
        },
        MintTokensForReimbursedRedeem {
            redeem_id: H256,
            vault_id: DefaultVaultId<T>,
            amount: BalanceOf<T>,
        },
        RedeemPeriodChange {
            period: BlockNumberFor<T>,
        },
        SelfRedeem {
            vault_id: DefaultVaultId<T>,
            amount: BalanceOf<T>,
            fee: BalanceOf<T>,
        },
    }

    #[pallet::error]
    pub enum Error<T> {
        /// Account has insufficient balance.
        AmountExceedsUserBalance,
        /// Unexpected redeem account.
        UnauthorizedRedeemer,
        /// Unexpected vault account.
        UnauthorizedVault,
        /// Redeem request has not expired.
        TimeNotExpired,
        /// Redeem request already cancelled.
        RedeemCancelled,
        /// Redeem request already completed.
        RedeemCompleted,
        /// Redeem request not found.
        RedeemIdNotFound,
        /// Unable to convert value.
        TryIntoIntError,
        /// Redeem amount is too small.
        AmountBelowDustAmount,
    }

    /// The time difference in number of blocks between a redeem request is created and required completion time by a
    /// vault. The redeem period has an upper limit to ensure the user gets their BTC in time and to potentially
    /// punish a vault for inactivity or stealing BTC.
    #[pallet::storage]
    #[pallet::getter(fn redeem_period)]
    pub(super) type RedeemPeriod<T: Config> = StorageValue<_, BlockNumberFor<T>, ValueQuery>;

    /// Users create redeem requests to receive BTC in return for their previously issued tokens.
    /// This mapping provides access from a unique hash redeemId to a Redeem struct.
    #[pallet::storage]
    #[pallet::getter(fn redeem_requests)]
    pub(super) type RedeemRequests<T: Config> =
        StorageMap<_, Blake2_128Concat, H256, DefaultRedeemRequest<T>, OptionQuery>;

    /// The minimum amount of btc that is accepted for redeem requests; any lower values would
    /// risk the bitcoin client to reject the payment
    #[pallet::storage]
    #[pallet::getter(fn redeem_btc_dust_value)]
    pub(super) type RedeemBtcDustValue<T: Config> = StorageValue<_, BalanceOf<T>, ValueQuery>;

    /// the expected size in bytes of the redeem bitcoin transfer
    #[pallet::storage]
    #[pallet::getter(fn redeem_transaction_size)]
    pub(super) type RedeemTransactionSize<T: Config> = StorageValue<_, u32, ValueQuery>;

    #[pallet::type_value]
    pub(super) fn DefaultForStorageVersion() -> Version {
        Version::V0
    }

    /// Build storage at V1 (requires default 0).
    #[pallet::storage]
    #[pallet::getter(fn storage_version)]
    pub(super) type StorageVersion<T: Config> = StorageValue<_, Version, ValueQuery, DefaultForStorageVersion>;

    #[pallet::genesis_config]
    #[derive(frame_support::DefaultNoBound)]
    pub struct GenesisConfig<T: Config> {
        pub redeem_period: BlockNumberFor<T>,
        pub redeem_btc_dust_value: BalanceOf<T>,
        pub redeem_transaction_size: u32,
    }

    #[pallet::genesis_build]
    impl<T: Config> BuildGenesisConfig for GenesisConfig<T> {
        fn build(&self) {
            RedeemPeriod::<T>::put(self.redeem_period);
            RedeemBtcDustValue::<T>::put(self.redeem_btc_dust_value);
            RedeemTransactionSize::<T>::put(self.redeem_transaction_size);
        }
    }

    #[pallet::hooks]
    impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {}

    #[pallet::pallet]
    pub struct Pallet<T>(_);

    // The pallet's dispatchable functions.
    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Initializes a request to burn issued tokens against a Vault with sufficient tokens. It will
        /// also ensure that the Parachain status is RUNNING.
        ///
        /// # Arguments
        ///
        /// * `origin` - sender of the transaction
        /// * `amount` - amount of issued tokens
        /// * `btc_address` - the address to receive BTC
        /// * `vault_id` - address of the vault
        #[pallet::call_index(0)]
        #[pallet::weight(<T as Config>::WeightInfo::request_redeem())]
        #[transactional]
        pub fn request_redeem(
            origin: OriginFor<T>,
            #[pallet::compact] amount_wrapped: BalanceOf<T>,
            btc_address: BtcAddress,
            vault_id: DefaultVaultId<T>,
        ) -> DispatchResultWithPostInfo {
            let redeemer = ensure_signed(origin)?;
            Self::_request_redeem(redeemer, amount_wrapped, btc_address, vault_id)?;
            Ok(().into())
        }

        /// When a Vault is liquidated, its collateral is slashed up to 150% of the liquidated BTC value.
        /// To re-establish the physical 1:1 peg, the bridge allows users to burn issued tokens in return for
        /// collateral at a premium rate.
        ///
        /// # Arguments
        ///
        /// * `origin` - sender of the transaction
        /// * `collateral_currency` - currency to be received
        /// * `wrapped_currency` - currency of the wrapped token to burn
        /// * `amount_wrapped` - amount of issued tokens to burn
        #[pallet::call_index(1)]
        #[pallet::weight(<T as Config>::WeightInfo::liquidation_redeem())]
        #[transactional]
        pub fn liquidation_redeem(
            origin: OriginFor<T>,
            currencies: DefaultVaultCurrencyPair<T>,
            #[pallet::compact] amount_wrapped: BalanceOf<T>,
        ) -> DispatchResultWithPostInfo {
            let redeemer = ensure_signed(origin)?;
            Self::_liquidation_redeem(redeemer, currencies, amount_wrapped)?;
            Ok(().into())
        }

        /// A Vault calls this function after receiving an RequestRedeem event with their public key.
        /// Before calling the function, the Vault transfers the specific amount of BTC to the BTC address
        /// given in the original redeem request. The Vault completes the redeem with this function.
        ///
        /// # Arguments
        ///
        /// * `origin` - anyone executing this redeem request
        /// * `redeem_id` - identifier of redeem request as output from request_redeem
        /// * `tx_id` - transaction hash
        /// * `merkle_proof` - membership proof
        /// * `transaction` - tx containing payment
        #[pallet::call_index(2)]
        #[pallet::weight(weight_for_execute_redeem::<T>(unchecked_transaction))]
        #[transactional]
        pub fn execute_redeem(
            origin: OriginFor<T>,
            redeem_id: H256,
            unchecked_transaction: FullTransactionProof,
        ) -> DispatchResultWithPostInfo {
            let _ = ensure_signed(origin)?;

            Self::_execute_redeem(redeem_id, unchecked_transaction)?;

            // Don't take tx fees on success. If the vault had to pay for this function, it would
            // have been vulnerable to a griefing attack where users would redeem amounts just
            // above the dust value.
            Ok(Pays::No.into())
        }

        /// If a redeem request is not completed on time, the redeem request can be cancelled.
        /// The user that initially requested the redeem process calls this function to obtain
        /// the Vault’s collateral as compensation for not transferring the BTC back to their address.
        ///
        /// # Arguments
        ///
        /// * `origin` - sender of the transaction
        /// * `redeem_id` - identifier of redeem request as output from request_redeem
        /// * `reimburse` - specifying if the user wishes to be reimbursed in collateral
        /// and slash the Vault, or wishes to keep the tokens (and retry
        /// Redeem with another Vault)
        #[pallet::call_index(3)]
        #[pallet::weight(if *reimburse { <T as Config>::WeightInfo::cancel_redeem_reimburse() } else { <T as Config>::WeightInfo::cancel_redeem_retry() })]
        #[transactional]
        pub fn cancel_redeem(origin: OriginFor<T>, redeem_id: H256, reimburse: bool) -> DispatchResultWithPostInfo {
            let redeemer = ensure_signed(origin)?;
            Self::_cancel_redeem(redeemer, redeem_id, reimburse)?;
            Ok(().into())
        }

        /// Set the default redeem period for tx verification.
        ///
        /// # Arguments
        ///
        /// * `origin` - the dispatch origin of this call (must be _Root_)
        /// * `period` - default period for new requests
        ///
        /// # Weight: `O(1)`
        #[pallet::call_index(4)]
        #[pallet::weight(<T as Config>::WeightInfo::set_redeem_period())]
        #[transactional]
        pub fn set_redeem_period(origin: OriginFor<T>, period: BlockNumberFor<T>) -> DispatchResultWithPostInfo {
            ensure_root(origin)?;
            <RedeemPeriod<T>>::set(period);
            Self::deposit_event(Event::RedeemPeriodChange { period });
            Ok(().into())
        }

        /// Mint tokens for a redeem that was cancelled with reimburse=true. This is
        /// only possible if at the time of the cancel_redeem, the vault did not have
        /// sufficient collateral after being slashed to back the tokens that the user
        /// used to hold.
        ///
        /// # Arguments
        ///
        /// * `origin` - the dispatch origin of this call (must be _Root_)
        /// * `redeem_id` - identifier of redeem request as output from request_redeem
        ///
        /// # Weight: `O(1)`
        #[pallet::call_index(5)]
        #[pallet::weight(<T as Config>::WeightInfo::set_redeem_period())]
        #[transactional]
        pub fn mint_tokens_for_reimbursed_redeem(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            redeem_id: H256,
        ) -> DispatchResultWithPostInfo {
            let vault_id = VaultId::new(ensure_signed(origin)?, currency_pair.collateral, currency_pair.wrapped);
            Self::_mint_tokens_for_reimbursed_redeem(vault_id, redeem_id)?;
            Ok(().into())
        }

        #[pallet::call_index(6)]
        #[pallet::weight(<T as Config>::WeightInfo::self_redeem())]
        #[transactional]
        pub fn self_redeem(
            origin: OriginFor<T>,
            currency_pair: DefaultVaultCurrencyPair<T>,
            amount_wrapped: BalanceOf<T>,
        ) -> DispatchResultWithPostInfo {
            let account_id = ensure_signed(origin)?;
            let vault_id = VaultId::new(account_id, currency_pair.collateral, currency_pair.wrapped);
            let amount_wrapped = Amount::new(amount_wrapped, vault_id.wrapped_currency());

            self_redeem::execute::<T>(vault_id, amount_wrapped)?;

            Ok(().into())
        }
    }
}

mod self_redeem {
    use super::*;

    pub(crate) fn execute<T: Config>(vault_id: DefaultVaultId<T>, amount_wrapped: Amount<T>) -> DispatchResult {
        // ensure that vault is not liquidated and not banned
        ext::vault_registry::ensure_not_banned::<T>(&vault_id)?;

        // for self-redeem, dustAmount is effectively 1 satoshi
        ensure!(!amount_wrapped.is_zero(), Error::<T>::AmountBelowDustAmount);

        let (fees, consumed_issued_tokens) = calculate_token_amounts::<T>(&vault_id, &amount_wrapped)?;

        take_user_tokens::<T>(&vault_id.account_id, &consumed_issued_tokens, &fees)?;

        update_vault_tokens::<T>(&vault_id, &consumed_issued_tokens)?;

        Pallet::<T>::deposit_event(Event::<T>::SelfRedeem {
            vault_id,
            amount: consumed_issued_tokens.amount(),
            fee: fees.amount(),
        });

        Ok(())
    }

    /// returns (fees, consumed_issued_tokens)
    fn calculate_token_amounts<T: Config>(
        vault_id: &DefaultVaultId<T>,
        requested_redeem_amount: &Amount<T>,
    ) -> Result<(Amount<T>, Amount<T>), DispatchError> {
        let redeemable_tokens = ext::vault_registry::get_free_redeemable_tokens(&vault_id)?;

        let fees = if redeemable_tokens.eq(&requested_redeem_amount)? {
            Amount::zero(vault_id.wrapped_currency())
        } else {
            ext::fee::get_redeem_fee::<T>(&requested_redeem_amount)?
        };

        let consumed_issued_tokens = requested_redeem_amount.checked_sub(&fees)?;

        Ok((fees, consumed_issued_tokens))
    }

    fn take_user_tokens<T: Config>(
        account_id: &T::AccountId,
        consumed_issued_tokens: &Amount<T>,
        fees: &Amount<T>,
    ) -> DispatchResult {
        // burn the tokens that the vault no longer is backing
        consumed_issued_tokens
            .lock_on(account_id)
            .map_err(|_| Error::<T>::AmountExceedsUserBalance)?;
        consumed_issued_tokens.burn_from(account_id)?;

        // transfer fees to pool
        fees.transfer(account_id, &ext::fee::fee_pool_account_id::<T>())
            .map_err(|_| Error::<T>::AmountExceedsUserBalance)?;
        ext::fee::distribute_rewards::<T>(fees)?;

        Ok(())
    }

    fn update_vault_tokens<T: Config>(
        vault_id: &DefaultVaultId<T>,
        consumed_issued_tokens: &Amount<T>,
    ) -> DispatchResult {
        ext::vault_registry::try_increase_to_be_redeemed_tokens::<T>(vault_id, consumed_issued_tokens)?;
        ext::vault_registry::redeem_tokens::<T>(
            vault_id,
            consumed_issued_tokens,
            &Amount::zero(vault_id.collateral_currency()),
            &vault_id.account_id,
        )?;

        Pallet::<T>::release_replace_collateral(vault_id, consumed_issued_tokens)?;
        Ok(())
    }
}
// "Internal" functions, callable by code.
#[cfg_attr(test, mockable)]
impl<T: Config> Pallet<T> {
    fn _request_redeem(
        redeemer: T::AccountId,
        amount_wrapped: BalanceOf<T>,
        btc_address: BtcAddress,
        vault_id: DefaultVaultId<T>,
    ) -> Result<H256, DispatchError> {
        let amount_wrapped = Amount::new(amount_wrapped, vault_id.wrapped_currency());

        let redeemer_balance = ext::treasury::get_balance::<T>(&redeemer, vault_id.wrapped_currency());
        ensure!(
            amount_wrapped.le(&redeemer_balance)?,
            Error::<T>::AmountExceedsUserBalance
        );

        // We saw a user lose bitcoin when they forgot to enter the address in the polkadot-js ui.
        // Make sure this can't happen again.
        ensure!(!btc_address.is_zero(), btc_relay::Error::<T>::InvalidBtcHash);

        // todo: currently allowed to redeem from one currency to the other for free - decide if this is desirable
        let fee_wrapped = if redeemer == vault_id.account_id {
            Amount::zero(vault_id.wrapped_currency())
        } else {
            ext::fee::get_redeem_fee::<T>(&amount_wrapped)?
        };
        let inclusion_fee = Self::get_current_inclusion_fee(vault_id.wrapped_currency())?;

        let vault_to_be_burned_tokens = amount_wrapped.checked_sub(&fee_wrapped)?;

        // this can overflow for small requested values. As such return AmountBelowDustAmount when this happens
        let user_to_be_received_btc = vault_to_be_burned_tokens
            .checked_sub(&inclusion_fee)
            .map_err(|_| Error::<T>::AmountBelowDustAmount)?;

        ext::vault_registry::ensure_not_banned::<T>(&vault_id)?;

        // only allow requests of amount above above the minimum
        ensure!(
            // this is the amount the vault will send (minus fee)
            user_to_be_received_btc.ge(&Self::get_dust_value(vault_id.wrapped_currency()))?,
            Error::<T>::AmountBelowDustAmount
        );

        let currency_id = vault_id.collateral_currency();

        // Calculate the premium collateral amount based on whether the redemption is below the premium redeem
        // threshold. This should come before increasing the `to_be_redeemed` tokens and locking the amount to
        // ensure accurate premium redeem calculations.
        let premium_collateral = {
            let redeem_amount_wrapped_in_collateral = user_to_be_received_btc.convert_to(currency_id)?;
            let premium_redeem_rate = ext::fee::premium_redeem_reward_rate::<T>();
            let premium_for_redeem_amount =
                redeem_amount_wrapped_in_collateral.checked_rounded_mul(&premium_redeem_rate, Rounding::Down)?;

            let max_premium = ext::vault_registry::get_vault_max_premium_redeem(&vault_id)?;
            max_premium.min(&premium_for_redeem_amount)?
        };

        // vault will get rid of the btc + btc_inclusion_fee
        ext::vault_registry::try_increase_to_be_redeemed_tokens::<T>(&vault_id, &vault_to_be_burned_tokens)?;

        // lock full amount (inc. fee)
        amount_wrapped.lock_on(&redeemer)?;
        let redeem_id = ext::security::get_secure_id::<T>(&redeemer);

        Self::release_replace_collateral(&vault_id, &vault_to_be_burned_tokens)?;

        Self::insert_redeem_request(
            &redeem_id,
            &RedeemRequest {
                vault: vault_id.clone(),
                opentime: ext::security::active_block_number::<T>(),
                fee: fee_wrapped.amount(),
                transfer_fee_btc: inclusion_fee.amount(),
                amount_btc: user_to_be_received_btc.amount(),
                premium: premium_collateral.amount(),
                period: Self::redeem_period(),
                redeemer: redeemer.clone(),
                btc_address,
                btc_height: ext::btc_relay::get_best_block_height::<T>(),
                status: RedeemRequestStatus::Pending,
            },
        );

        Self::deposit_event(Event::<T>::RequestRedeem {
            redeem_id,
            redeemer,
            amount: user_to_be_received_btc.amount(),
            fee: fee_wrapped.amount(),
            premium: premium_collateral.amount(),
            vault_id,
            btc_address,
            transfer_fee: inclusion_fee.amount(),
        });

        Ok(redeem_id)
    }

    fn _liquidation_redeem(
        redeemer: T::AccountId,
        currencies: DefaultVaultCurrencyPair<T>,
        amount_wrapped: BalanceOf<T>,
    ) -> Result<(), DispatchError> {
        let amount_wrapped = Amount::new(amount_wrapped, currencies.wrapped);

        let redeemer_balance = ext::treasury::get_balance::<T>(&redeemer, currencies.wrapped);
        ensure!(
            amount_wrapped.le(&redeemer_balance)?,
            Error::<T>::AmountExceedsUserBalance
        );

        amount_wrapped.lock_on(&redeemer)?;
        amount_wrapped.burn_from(&redeemer)?;
        ext::vault_registry::redeem_tokens_liquidation::<T>(currencies.collateral, &redeemer, &amount_wrapped)?;

        // vault-registry emits `RedeemTokensLiquidation` with collateral amount
        Self::deposit_event(Event::<T>::LiquidationRedeem {
            redeemer,
            amount: amount_wrapped.amount(),
        });

        Ok(())
    }

    fn _execute_redeem(redeem_id: H256, unchecked_transaction: FullTransactionProof) -> Result<(), DispatchError> {
        let redeem = Self::get_open_redeem_request_from_id(&redeem_id)?;

        // check the transaction inclusion and validity
        ext::btc_relay::verify_and_validate_op_return_transaction::<T, _>(
            unchecked_transaction,
            redeem.btc_address,
            redeem.amount_btc,
            redeem_id,
        )?;

        // burn amount (without parachain fee, but including transfer fee)
        let burn_amount = redeem.amount_btc().checked_add(&redeem.transfer_fee_btc())?;
        burn_amount.burn_from(&redeem.redeemer)?;

        // send fees to pool
        let fee = redeem.fee();
        fee.unlock_on(&redeem.redeemer)?;
        fee.transfer(&redeem.redeemer, &ext::fee::fee_pool_account_id::<T>())?;
        ext::fee::distribute_rewards::<T>(&fee)?;

        ext::vault_registry::redeem_tokens::<T>(&redeem.vault, &burn_amount, &redeem.premium()?, &redeem.redeemer)?;

        Self::set_redeem_status(redeem_id, RedeemRequestStatus::Completed);
        Self::deposit_event(Event::<T>::ExecuteRedeem {
            redeem_id,
            redeemer: redeem.redeemer,
            vault_id: redeem.vault,
            amount: redeem.amount_btc,
            fee: redeem.fee,
            transfer_fee: redeem.transfer_fee_btc,
        });
        Ok(())
    }

    fn _cancel_redeem(redeemer: T::AccountId, redeem_id: H256, reimburse: bool) -> DispatchResult {
        let redeem = Self::get_open_redeem_request_from_id(&redeem_id)?;
        ensure!(redeemer == redeem.redeemer, Error::<T>::UnauthorizedRedeemer);

        // only cancellable after the request has expired
        ensure!(
            ext::btc_relay::has_request_expired::<T>(
                redeem.opentime,
                redeem.btc_height,
                Self::redeem_period().max(redeem.period)
            )?,
            Error::<T>::TimeNotExpired
        );

        let vault = ext::vault_registry::get_vault_from_id::<T>(&redeem.vault)?;
        let vault_to_be_redeemed_tokens = Amount::new(vault.to_be_redeemed_tokens, redeem.vault.wrapped_currency());
        let vault_id = redeem.vault.clone();

        let vault_to_be_burned_tokens = redeem.amount_btc().checked_add(&redeem.transfer_fee_btc())?;

        let amount_wrapped_in_collateral = vault_to_be_burned_tokens.convert_to(vault_id.collateral_currency())?;

        // now update the collateral; the logic is different for liquidated vaults.
        let slashed_amount = if vault.is_liquidated() {
            let confiscated_collateral = ext::vault_registry::calculate_collateral::<T>(
                &ext::vault_registry::get_liquidated_collateral::<T>(&redeem.vault)?,
                &vault_to_be_burned_tokens,
                &vault_to_be_redeemed_tokens, // note: this is the value read prior to making changes
            )?;

            let slashing_destination = if reimburse {
                CurrencySource::FreeBalance(redeemer.clone())
            } else {
                CurrencySource::LiquidationVault(vault_id.currencies.clone())
            };
            ext::vault_registry::decrease_liquidated_collateral::<T>(&vault_id, &confiscated_collateral)?;
            ext::vault_registry::transfer_funds::<T>(
                CurrencySource::LiquidatedCollateral(vault_id.clone()),
                slashing_destination,
                &confiscated_collateral,
            )?;

            confiscated_collateral
        } else {
            // not liquidated

            // calculate the punishment fee (e.g. 10%)
            let punishment_fee_in_collateral = ext::fee::get_punishment_fee::<T>(&amount_wrapped_in_collateral)?;

            let amount_to_slash = if reimburse {
                // 100% + punishment fee on reimburse
                amount_wrapped_in_collateral.checked_add(&punishment_fee_in_collateral)?
            } else {
                punishment_fee_in_collateral
            };

            ext::vault_registry::transfer_funds_saturated::<T>(
                CurrencySource::Collateral(vault_id.clone()),
                CurrencySource::FreeBalance(redeemer.clone()),
                &amount_to_slash,
            )?;

            let _ = ext::vault_registry::ban_vault::<T>(&vault_id);

            amount_to_slash
        };

        // first update the issued tokens
        let new_status = if reimburse {
            // Transfer the transaction fee to the pool. Even though the redeem was not
            // successful, the user receives a premium in collateral, so it's OK to take the fee.
            let fee = redeem.fee();
            fee.unlock_on(&redeem.redeemer)?;
            fee.transfer(&redeem.redeemer, &ext::fee::fee_pool_account_id::<T>())?;
            ext::fee::distribute_rewards::<T>(&fee)?;

            if vault.is_liquidated() {
                // In this situation, tokens are burned and the collateral gets transferred
                // to the user. This is similar to what happens in a liquidation_redeem.
                vault_to_be_burned_tokens.burn_from(&redeemer)?;
                ext::vault_registry::decrease_tokens::<T>(&redeem.vault, &redeem.redeemer, &vault_to_be_burned_tokens)?;
                // set to Reimbursed(true) such that the vault can't mint the ibtc/kbtc later on
                Self::set_redeem_status(redeem_id, RedeemRequestStatus::Reimbursed(true))
            } else if ext::vault_registry::is_vault_below_secure_threshold::<T>(&redeem.vault)? {
                // vault can not afford to back the tokens that it would receive, so we burn it
                vault_to_be_burned_tokens.burn_from(&redeemer)?;
                ext::vault_registry::decrease_tokens::<T>(&redeem.vault, &redeem.redeemer, &vault_to_be_burned_tokens)?;
                Self::set_redeem_status(redeem_id, RedeemRequestStatus::Reimbursed(false))
            } else {
                // Transfer the rest of the user's issued tokens (i.e. excluding fee) to the vault
                vault_to_be_burned_tokens.unlock_on(&redeem.redeemer)?;
                vault_to_be_burned_tokens.transfer(&redeem.redeemer, &redeem.vault.account_id)?;
                ext::vault_registry::decrease_to_be_redeemed_tokens::<T>(&vault_id, &vault_to_be_burned_tokens)?;
                Self::set_redeem_status(redeem_id, RedeemRequestStatus::Reimbursed(true))
            }
        } else {
            // unlock user's issued tokens, including fee
            let total_wrapped: Amount<T> = redeem
                .amount_btc()
                .checked_add(&redeem.fee())?
                .checked_add(&redeem.transfer_fee_btc())?;
            total_wrapped.unlock_on(&redeemer)?;
            ext::vault_registry::decrease_to_be_redeemed_tokens::<T>(&vault_id, &vault_to_be_burned_tokens)?;
            Self::set_redeem_status(redeem_id, RedeemRequestStatus::Retried)
        };

        Self::deposit_event(Event::<T>::CancelRedeem {
            redeem_id,
            redeemer,
            vault_id: redeem.vault,
            slashed_amount: slashed_amount.amount(),
            status: new_status,
        });

        Ok(())
    }

    fn _mint_tokens_for_reimbursed_redeem(vault_id: DefaultVaultId<T>, redeem_id: H256) -> DispatchResult {
        let redeem = RedeemRequests::<T>::try_get(&redeem_id).or(Err(Error::<T>::RedeemIdNotFound))?;
        ensure!(
            matches!(redeem.status, RedeemRequestStatus::Reimbursed(false)),
            Error::<T>::RedeemCancelled
        );

        ensure!(redeem.vault == vault_id, Error::<T>::UnauthorizedVault);

        let reimbursed_amount = redeem.amount_btc().checked_add(&redeem.transfer_fee_btc())?;

        ext::vault_registry::try_increase_to_be_issued_tokens::<T>(&vault_id, &reimbursed_amount)?;
        ext::vault_registry::issue_tokens::<T>(&vault_id, &reimbursed_amount)?;
        reimbursed_amount.mint_to(&vault_id.account_id)?;

        Self::set_redeem_status(redeem_id, RedeemRequestStatus::Reimbursed(true));

        Self::deposit_event(Event::<T>::MintTokensForReimbursedRedeem {
            redeem_id,
            vault_id: redeem.vault,
            amount: reimbursed_amount.amount(),
        });

        Ok(())
    }

    fn release_replace_collateral(vault_id: &DefaultVaultId<T>, burned_tokens: &Amount<T>) -> DispatchResult {
        // decrease to-be-replaced tokens - when the vault requests tokens to be replaced, it
        // want to get rid of tokens, and it does not matter whether this is through a redeem,
        // or a replace. As such, we decrease the to-be-replaced tokens here. This call will
        // never fail due to insufficient to-be-replaced tokens
        let (_, griefing_collateral) =
            ext::vault_registry::decrease_to_be_replaced_tokens::<T>(&vault_id, &burned_tokens)?;
        // release the griefing collateral that is locked for the replace request
        if !griefing_collateral.is_zero() {
            ext::vault_registry::transfer_funds(
                CurrencySource::AvailableReplaceCollateral(vault_id.clone()),
                CurrencySource::FreeBalance(vault_id.account_id.clone()),
                &griefing_collateral,
            )?;
        }
        Ok(())
    }

    /// Insert a new redeem request into state.
    ///
    /// # Arguments
    ///
    /// * `key` - 256-bit identifier of the redeem request
    /// * `value` - the redeem request
    fn insert_redeem_request(key: &H256, value: &DefaultRedeemRequest<T>) {
        <RedeemRequests<T>>::insert(key, value)
    }

    fn set_redeem_status(id: H256, status: RedeemRequestStatus) -> RedeemRequestStatus {
        <RedeemRequests<T>>::mutate_exists(id, |request| {
            *request = request.clone().map(|request| DefaultRedeemRequest::<T> {
                status: status.clone(),
                ..request
            });
        });

        status
    }

    /// get current inclusion fee based on the expected number of bytes in the transaction, and
    /// the inclusion fee rate reported by the oracle
    pub fn get_current_inclusion_fee(wrapped_currency: CurrencyId<T>) -> Result<Amount<T>, DispatchError> {
        let size: u32 = Self::redeem_transaction_size();
        ext::vault_registry::calculate_inclusion_fee::<T>(wrapped_currency, size)
    }

    pub fn get_dust_value(currency_id: CurrencyId<T>) -> Amount<T> {
        Amount::new(<RedeemBtcDustValue<T>>::get(), currency_id)
    }
    /// Fetch all redeem requests for the specified account.
    ///
    /// # Arguments
    ///
    /// * `account_id` - user account id
    pub fn get_redeem_requests_for_account(account_id: T::AccountId) -> Vec<H256> {
        <RedeemRequests<T>>::iter()
            .filter(|(_, request)| request.redeemer == account_id)
            .map(|(key, _)| key)
            .collect::<Vec<_>>()
    }

    pub fn get_premium_redeem_vaults() -> Result<Vec<(DefaultVaultId<T>, Amount<T>)>, DispatchError> {
        let size: u32 = Self::redeem_transaction_size();
        ext::vault_registry::get_premium_redeem_vaults::<T>(size)
    }

    /// Fetch all redeem requests for the specified vault.
    ///
    /// # Arguments
    ///
    /// * `vault_id` - vault account id
    pub fn get_redeem_requests_for_vault(vault_id: T::AccountId) -> Vec<H256> {
        <RedeemRequests<T>>::iter()
            .filter(|(_, request)| request.vault.account_id == vault_id)
            .map(|(key, _)| key)
            .collect::<Vec<_>>()
    }

    /// Fetch a pre-existing redeem request or throw. Completed or cancelled
    /// requests are not returned.
    ///
    /// # Arguments
    ///
    /// * `redeem_id` - 256-bit identifier of the redeem request
    pub fn get_open_redeem_request_from_id(redeem_id: &H256) -> Result<DefaultRedeemRequest<T>, DispatchError> {
        let request = RedeemRequests::<T>::try_get(redeem_id).or(Err(Error::<T>::RedeemIdNotFound))?;

        // NOTE: temporary workaround until we delete
        match request.status {
            RedeemRequestStatus::Pending => Ok(request),
            RedeemRequestStatus::Completed => Err(Error::<T>::RedeemCompleted.into()),
            RedeemRequestStatus::Reimbursed(_) | RedeemRequestStatus::Retried => {
                Err(Error::<T>::RedeemCancelled.into())
            }
        }
    }

    /// Fetch a pre-existing open or completed redeem request or throw.
    /// Cancelled requests are not returned.
    ///
    /// # Arguments
    ///
    /// * `redeem_id` - 256-bit identifier of the redeem request
    pub fn get_open_or_completed_redeem_request_from_id(
        redeem_id: &H256,
    ) -> Result<DefaultRedeemRequest<T>, DispatchError> {
        let request = RedeemRequests::<T>::try_get(redeem_id).or(Err(Error::<T>::RedeemIdNotFound))?;

        ensure!(
            matches!(
                request.status,
                RedeemRequestStatus::Pending | RedeemRequestStatus::Completed
            ),
            Error::<T>::RedeemCancelled
        );
        Ok(request)
    }
}