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
// Copyright 2021 Axiom-Team
//
// This file is part of Duniter-v2S.
//
// Duniter-v2S is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, version 3 of the License.
//
// Duniter-v2S 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with Duniter-v2S. If not, see <https://www.gnu.org/licenses/>.

#![cfg_attr(not(feature = "std"), no_std)]

mod benchmarking;
mod check_nonce;
#[cfg(test)]
mod mock;
mod types;
pub mod weights;

pub use check_nonce::CheckNonce;
pub use pallet::*;
pub use types::*;
pub use weights::WeightInfo;

use frame_support::pallet_prelude::*;
use frame_support::traits::{
    Currency, ExistenceRequirement, Imbalance, IsSubType, WithdrawReasons,
};
use frame_system::pallet_prelude::*;
use pallet_transaction_payment::OnChargeTransaction;
use sp_runtime::traits::{DispatchInfoOf, PostDispatchInfoOf, Saturating, StaticLookup, Zero};
use sp_std::convert::TryInto;

#[frame_support::pallet]
pub mod pallet {
    use super::*;

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

    // CONFIG //

    #[pallet::config]
    pub trait Config: frame_system::Config + pallet_transaction_payment::Config {
        type Currency: Currency<Self::AccountId>;
        type InnerOnChargeTransaction: OnChargeTransaction<Self>;
        type RuntimeEvent: From<Event<Self>> + IsType<<Self as frame_system::Config>::RuntimeEvent>;
        /// Type representing the weight of this pallet
        type WeightInfo: WeightInfo;
    }

    // STORAGE //

    #[pallet::storage]
    #[pallet::getter(fn oneshot_account)]
    pub type OneshotAccounts<T: Config> = StorageMap<
        _,
        Blake2_128Concat,
        T::AccountId,
        <T::Currency as Currency<T::AccountId>>::Balance,
        OptionQuery,
    >;

    // EVENTS //

    #[allow(clippy::type_complexity)]
    #[pallet::event]
    #[pallet::generate_deposit(pub(super) fn deposit_event)]
    pub enum Event<T: Config> {
        /// A oneshot account was created.
        OneshotAccountCreated {
            account: T::AccountId,
            balance: <T::Currency as Currency<T::AccountId>>::Balance,
            creator: T::AccountId,
        },
        /// A oneshot account was consumed.
        OneshotAccountConsumed {
            account: T::AccountId,
            dest1: (
                T::AccountId,
                <T::Currency as Currency<T::AccountId>>::Balance,
            ),
            dest2: Option<(
                T::AccountId,
                <T::Currency as Currency<T::AccountId>>::Balance,
            )>,
        },
        /// A withdrawal was executed on a oneshot account.
        Withdraw {
            account: T::AccountId,
            balance: <T::Currency as Currency<T::AccountId>>::Balance,
        },
    }

    // ERRORS //

    #[pallet::error]
    pub enum Error<T> {
        /// Block height is in the future.
        BlockHeightInFuture,
        /// Block height is too old.
        BlockHeightTooOld,
        /// Destination account does not exist.
        DestAccountNotExist,
        /// Destination account has a balance less than the existential deposit.
        ExistentialDeposit,
        /// Source account has insufficient balance.
        InsufficientBalance,
        /// Destination oneshot account already exists.
        OneshotAccountAlreadyCreated,
        /// Source oneshot account does not exist.
        OneshotAccountNotExist,
    }

    // CALLS //
    #[pallet::call]
    impl<T: Config> Pallet<T> {
        /// Create an account that can only be consumed once
        ///
        /// - `dest`: The oneshot account to be created.
        /// - `balance`: The balance to be transfered to this oneshot account.
        ///
        /// Origin account is kept alive.
        #[pallet::call_index(0)]
        #[pallet::weight(T::WeightInfo::create_oneshot_account())]
        pub fn create_oneshot_account(
            origin: OriginFor<T>,
            dest: <T::Lookup as StaticLookup>::Source,
            #[pallet::compact] value: <T::Currency as Currency<T::AccountId>>::Balance,
        ) -> DispatchResult {
            let transactor = ensure_signed(origin)?;
            let dest = T::Lookup::lookup(dest)?;

            ensure!(
                value >= <T::Currency as Currency<T::AccountId>>::minimum_balance(),
                Error::<T>::ExistentialDeposit
            );
            ensure!(
                OneshotAccounts::<T>::get(&dest).is_none(),
                Error::<T>::OneshotAccountAlreadyCreated
            );

            let _ = <T::Currency as Currency<T::AccountId>>::withdraw(
                &transactor,
                value,
                WithdrawReasons::TRANSFER,
                ExistenceRequirement::KeepAlive,
            )?;
            OneshotAccounts::<T>::insert(&dest, value);
            Self::deposit_event(Event::OneshotAccountCreated {
                account: dest,
                balance: value,
                creator: transactor,
            });

            Ok(())
        }

        /// Consume a oneshot account and transfer its balance to an account
        ///
        /// - `block_height`: Must be a recent block number. The limit is `BlockHashCount` in the past. (this is to prevent replay attacks)
        /// - `dest`: The destination account.
        /// - `dest_is_oneshot`: If set to `true`, then a oneshot account is created at `dest`. Else, `dest` has to be an existing account.
        #[pallet::call_index(1)]
        #[pallet::weight(T::WeightInfo::consume_oneshot_account())]
        pub fn consume_oneshot_account(
            origin: OriginFor<T>,
            block_height: BlockNumberFor<T>,
            dest: Account<<T::Lookup as StaticLookup>::Source>,
        ) -> DispatchResult {
            let transactor = ensure_signed(origin)?;

            let (dest, dest_is_oneshot) = match dest {
                Account::Normal(account) => (account, false),
                Account::Oneshot(account) => (account, true),
            };
            let dest = T::Lookup::lookup(dest)?;

            let value = OneshotAccounts::<T>::take(&transactor)
                .ok_or(Error::<T>::OneshotAccountNotExist)?;

            ensure!(
                block_height <= frame_system::Pallet::<T>::block_number(),
                Error::<T>::BlockHeightInFuture
            );
            ensure!(
                frame_system::pallet::BlockHash::<T>::contains_key(block_height),
                Error::<T>::BlockHeightTooOld
            );
            if dest_is_oneshot {
                ensure!(
                    OneshotAccounts::<T>::get(&dest).is_none(),
                    Error::<T>::OneshotAccountAlreadyCreated
                );
                OneshotAccounts::<T>::insert(&dest, value);
                Self::deposit_event(Event::OneshotAccountCreated {
                    account: dest.clone(),
                    balance: value,
                    creator: transactor.clone(),
                });
            } else {
                let _ =
                    <T::Currency as Currency<T::AccountId>>::deposit_into_existing(&dest, value)?;
            }
            OneshotAccounts::<T>::remove(&transactor);
            Self::deposit_event(Event::OneshotAccountConsumed {
                account: transactor,
                dest1: (dest, value),
                dest2: None,
            });

            Ok(())
        }

        /// Consume a oneshot account then transfer some amount to an account,
        /// and the remaining amount to another account.
        ///
        /// - `block_height`: Must be a recent block number.
        ///   The limit is `BlockHashCount` in the past. (this is to prevent replay attacks)
        /// - `dest`: The destination account.
        /// - `dest_is_oneshot`: If set to `true`, then a oneshot account is created at `dest`. Else, `dest` has to be an existing account.
        /// - `dest2`: The second destination account.
        /// - `dest2_is_oneshot`: If set to `true`, then a oneshot account is created at `dest2`. Else, `dest2` has to be an existing account.
        /// - `balance1`: The amount transfered to `dest`, the leftover being transfered to `dest2`.
        #[pallet::call_index(2)]
        #[pallet::weight(T::WeightInfo::consume_oneshot_account_with_remaining())]
        pub fn consume_oneshot_account_with_remaining(
            origin: OriginFor<T>,
            block_height: BlockNumberFor<T>,
            dest: Account<<T::Lookup as StaticLookup>::Source>,
            remaining_to: Account<<T::Lookup as StaticLookup>::Source>,
            #[pallet::compact] balance: <T::Currency as Currency<T::AccountId>>::Balance,
        ) -> DispatchResult {
            let transactor = ensure_signed(origin)?;

            let (dest1, dest1_is_oneshot) = match dest {
                Account::Normal(account) => (account, false),
                Account::Oneshot(account) => (account, true),
            };
            let dest1 = T::Lookup::lookup(dest1)?;
            let (dest2, dest2_is_oneshot) = match remaining_to {
                Account::Normal(account) => (account, false),
                Account::Oneshot(account) => (account, true),
            };
            let dest2 = T::Lookup::lookup(dest2)?;

            let value = OneshotAccounts::<T>::take(&transactor)
                .ok_or(Error::<T>::OneshotAccountNotExist)?;

            let balance1 = balance;
            ensure!(value > balance1, Error::<T>::InsufficientBalance);
            let balance2 = value.saturating_sub(balance1);
            ensure!(
                block_height <= frame_system::Pallet::<T>::block_number(),
                Error::<T>::BlockHeightInFuture
            );
            ensure!(
                frame_system::pallet::BlockHash::<T>::contains_key(block_height),
                Error::<T>::BlockHeightTooOld
            );
            if dest1_is_oneshot {
                ensure!(
                    OneshotAccounts::<T>::get(&dest1).is_none(),
                    Error::<T>::OneshotAccountAlreadyCreated
                );
                ensure!(
                    balance1 >= <T::Currency as Currency<T::AccountId>>::minimum_balance(),
                    Error::<T>::ExistentialDeposit
                );
            } else {
                ensure!(
                    !<T::Currency as Currency<T::AccountId>>::free_balance(&dest1).is_zero(),
                    Error::<T>::DestAccountNotExist
                );
            }
            if dest2_is_oneshot {
                ensure!(
                    OneshotAccounts::<T>::get(&dest2).is_none(),
                    Error::<T>::OneshotAccountAlreadyCreated
                );
                ensure!(
                    balance2 >= <T::Currency as Currency<T::AccountId>>::minimum_balance(),
                    Error::<T>::ExistentialDeposit
                );
                OneshotAccounts::<T>::insert(&dest2, balance2);
                Self::deposit_event(Event::OneshotAccountCreated {
                    account: dest2.clone(),
                    balance: balance2,
                    creator: transactor.clone(),
                });
            } else {
                let _ = <T::Currency as Currency<T::AccountId>>::deposit_into_existing(
                    &dest2, balance2,
                )?;
            }
            if dest1_is_oneshot {
                OneshotAccounts::<T>::insert(&dest1, balance1);
                Self::deposit_event(Event::OneshotAccountCreated {
                    account: dest1.clone(),
                    balance: balance1,
                    creator: transactor.clone(),
                });
            } else {
                let _ = <T::Currency as Currency<T::AccountId>>::deposit_into_existing(
                    &dest1, balance1,
                )?;
            }
            OneshotAccounts::<T>::remove(&transactor);
            Self::deposit_event(Event::OneshotAccountConsumed {
                account: transactor,
                dest1: (dest1, balance1),
                dest2: Some((dest2, balance2)),
            });

            Ok(())
        }
    }
}

impl<T: Config> OnChargeTransaction<T> for Pallet<T>
where
    T::RuntimeCall: IsSubType<Call<T>>,
    T::InnerOnChargeTransaction: OnChargeTransaction<
        T,
        Balance = <T::Currency as Currency<T::AccountId>>::Balance,
        LiquidityInfo = Option<<T::Currency as Currency<T::AccountId>>::NegativeImbalance>,
    >,
{
    type Balance = <T::Currency as Currency<T::AccountId>>::Balance;
    type LiquidityInfo = Option<<T::Currency as Currency<T::AccountId>>::NegativeImbalance>;

    fn withdraw_fee(
        who: &T::AccountId,
        call: &T::RuntimeCall,
        dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
        fee: Self::Balance,
        tip: Self::Balance,
    ) -> Result<Self::LiquidityInfo, TransactionValidityError> {
        if let Some(
            Call::consume_oneshot_account { .. }
            | Call::consume_oneshot_account_with_remaining { .. },
        ) = call.is_sub_type()
        {
            if fee.is_zero() {
                return Ok(None);
            }

            if let Some(balance) = OneshotAccounts::<T>::get(who) {
                if balance >= fee {
                    OneshotAccounts::<T>::insert(who, balance.saturating_sub(fee));
                    Self::deposit_event(Event::Withdraw {
                        account: who.clone(),
                        balance: fee,
                    });
                    // TODO
                    return Ok(Some(
                        <T::Currency as Currency<T::AccountId>>::NegativeImbalance::zero(),
                    ));
                }
            }
            Err(TransactionValidityError::Invalid(
                InvalidTransaction::Payment,
            ))
        } else {
            T::InnerOnChargeTransaction::withdraw_fee(who, call, dispatch_info, fee, tip)
        }
    }

    fn correct_and_deposit_fee(
        who: &T::AccountId,
        dispatch_info: &DispatchInfoOf<T::RuntimeCall>,
        post_info: &PostDispatchInfoOf<T::RuntimeCall>,
        corrected_fee: Self::Balance,
        tip: Self::Balance,
        already_withdrawn: Self::LiquidityInfo,
    ) -> Result<(), TransactionValidityError> {
        T::InnerOnChargeTransaction::correct_and_deposit_fee(
            who,
            dispatch_info,
            post_info,
            corrected_fee,
            tip,
            already_withdrawn,
        )
    }
}