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
// Copyright 2019-2020 Parity Technologies (UK) Ltd.
// This file is part of tetcore-subxt.
//
// subxt 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.
//
// subxt 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 tetcore-subxt.  If not, see <http://www.gnu.org/licenses/>.

//! Implements support for the noble_balances module.

use crate::fabric::system::{
    System,
    SystemEventsDecoder,
};
use codec::{
    Decode,
    Encode,
};
use core::marker::PhantomData;
use fabric_support::{
    traits::LockIdentifier,
    Parameter,
};
use tp_runtime::traits::{
    AtLeast32Bit,
    MaybeSerialize,
    Member,
};
use std::fmt::Debug;

/// The subset of the `noble_balances::Trait` that a client must implement.
#[module]
pub trait Balances: System {
    /// The balance of an account.
    type Balance: Parameter
        + Member
        + AtLeast32Bit
        + codec::Codec
        + Default
        + Copy
        + MaybeSerialize
        + Debug
        + From<<Self as System>::BlockNumber>;
}

/// All balance information for an account.
#[derive(Clone, Debug, Eq, PartialEq, Default, Decode, Encode)]
pub struct AccountData<Balance> {
    /// Non-reserved part of the balance. There may still be restrictions on this, but it is the
    /// total pool what may in principle be transferred, reserved and used for tipping.
    ///
    /// This is the only balance that matters in terms of most operations on tokens. It
    /// alone is used to determine the balance when in the contract execution environment.
    pub free: Balance,
    /// Balance which is reserved and may not be used at all.
    ///
    /// This can still get slashed, but gets slashed last of all.
    ///
    /// This balance is a 'reserve' balance that other subsystems use in order to set aside tokens
    /// that are still 'owned' by the account holder, but which are suspendable.
    pub reserved: Balance,
    /// The amount that `free` may not drop below when withdrawing for *anything except transaction
    /// fee payment*.
    pub misc_frozen: Balance,
    /// The amount that `free` may not drop below when withdrawing specifically for transaction
    /// fee payment.
    pub fee_frozen: Balance,
}

/// The total issuance of the balances module.
#[derive(Clone, Debug, Eq, PartialEq, Store, Encode)]
pub struct TotalIssuanceStore<T: Balances> {
    #[store(returns = T::Balance)]
    /// Runtime marker.
    pub _runtime: PhantomData<T>,
}

/// The locks of the balances module.
#[derive(Clone, Debug, Eq, PartialEq, Store, Encode, Decode)]
pub struct LocksStore<'a, T: Balances> {
    #[store(returns = Vec<BalanceLock<T::Balance>>)]
    /// Account to retrieve the balance locks for.
    pub account_id: &'a T::AccountId,
}

/// A single lock on a balance. There can be many of these on an account and they "overlap", so the
/// same balance is frozen by multiple locks.
#[derive(Clone, PartialEq, Eq, Encode, Decode)]
pub struct BalanceLock<Balance> {
    /// An identifier for this lock. Only one lock may be in existence for each identifier.
    pub id: LockIdentifier,
    /// The amount which the free balance may not drop below when this lock is in effect.
    pub amount: Balance,
    /// If true, then the lock remains in effect even for payment of transaction fees.
    pub reasons: Reasons,
}

impl<Balance: Debug> Debug for BalanceLock<Balance> {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        f.debug_struct("BalanceLock")
            .field("id", &String::from_utf8_lossy(&self.id))
            .field("amount", &self.amount)
            .field("reasons", &self.reasons)
            .finish()
    }
}

/// Simplified reasons for withdrawing balance.
#[derive(Encode, Decode, Clone, Copy, PartialEq, Eq, Debug)]
pub enum Reasons {
    /// Paying system transaction fees.
    Fee,
    /// Any reason other than paying system transaction fees.
    Misc,
    /// Any reason at all.
    All,
}

/// Transfer some liquid free balance to another account.
///
/// `transfer` will set the `FreeBalance` of the sender and receiver.
/// It will decrease the total issuance of the system by the `TransferFee`.
/// If the sender's account is below the existential deposit as a result
/// of the transfer, the account will be reaped.
#[derive(Clone, Debug, PartialEq, Call, Encode)]
pub struct TransferCall<'a, T: Balances> {
    /// Destination of the transfer.
    pub to: &'a <T as System>::Address,
    /// Amount to transfer.
    #[codec(compact)]
    pub amount: T::Balance,
}

/// Transfer event.
#[derive(Clone, Debug, Eq, PartialEq, Event, Decode)]
pub struct TransferEvent<T: Balances> {
    /// Account balance was transfered from.
    pub from: <T as System>::AccountId,
    /// Account balance was transfered to.
    pub to: <T as System>::AccountId,
    /// Amount of balance that was transfered.
    pub amount: T::Balance,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        error::{
            Error,
            ModuleError,
            RuntimeError,
        },
        events::EventsDecoder,
        extrinsic::{
            PairSigner,
            Signer,
        },
        subscription::EventSubscription,
        system::AccountStoreExt,
        tests::{
            test_client,
            TestRuntime,
        },
    };
    use tet_core::{
        sr25519::Pair,
        Pair as _,
    };
    use tp_keyring::AccountKeyring;

    #[async_std::test]
    async fn test_basic_transfer() {
        env_logger::try_init().ok();
        let alice = PairSigner::<TestRuntime, _>::new(AccountKeyring::Alice.pair());
        let bob = PairSigner::<TestRuntime, _>::new(AccountKeyring::Bob.pair());
        let (client, _) = test_client().await;

        let alice_pre = client.account(alice.account_id(), None).await.unwrap();
        let bob_pre = client.account(bob.account_id(), None).await.unwrap();

        let event = client
            .transfer_and_watch(&alice, &bob.account_id(), 10_000)
            .await
            .expect("sending an xt works")
            .transfer()
            .unwrap()
            .unwrap();
        let expected_event = TransferEvent {
            from: alice.account_id().clone(),
            to: bob.account_id().clone(),
            amount: 10_000,
        };
        assert_eq!(event, expected_event);

        let alice_post = client.account(alice.account_id(), None).await.unwrap();
        let bob_post = client.account(bob.account_id(), None).await.unwrap();

        assert!(alice_pre.data.free - 10_000 >= alice_post.data.free);
        assert_eq!(bob_pre.data.free + 10_000, bob_post.data.free);
    }

    #[async_std::test]
    async fn test_state_total_issuance() {
        env_logger::try_init().ok();
        let (client, _) = test_client().await;
        let total_issuance = client.total_issuance(None).await.unwrap();
        assert_ne!(total_issuance, 0);
    }

    #[async_std::test]
    async fn test_state_read_free_balance() {
        env_logger::try_init().ok();
        let (client, _) = test_client().await;
        let account = AccountKeyring::Alice.to_account_id();
        let info = client.account(&account, None).await.unwrap();
        assert_ne!(info.data.free, 0);
    }

    #[async_std::test]
    #[cfg(feature = "integration-tests")]
    async fn test_state_balance_lock() -> Result<(), crate::Error> {
        use crate::{
            fabric::staking::{
                BondCallExt,
                RewardDestination,
            },
            runtimes::KusamaRuntime as RT,
            ClientBuilder,
        };

        env_logger::try_init().ok();
        let bob = PairSigner::<RT, _>::new(AccountKeyring::Bob.pair());
        let client = ClientBuilder::<RT>::new().build().await?;

        client
            .bond_and_watch(
                &bob,
                AccountKeyring::Charlie.to_account_id(),
                100_000_000_000,
                RewardDestination::Stash,
            )
            .await?;

        let locks = client
            .locks(&AccountKeyring::Bob.to_account_id(), None)
            .await?;

        assert_eq!(
            locks,
            vec![BalanceLock {
                id: *b"staking ",
                amount: 100_000_000_000,
                reasons: Reasons::All,
            }]
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_transfer_error() {
        env_logger::try_init().ok();
        let alice = PairSigner::new(AccountKeyring::Alice.pair());
        let hans = PairSigner::new(Pair::generate().0);
        let (client, _) = test_client().await;
        client
            .transfer_and_watch(&alice, hans.account_id(), 100_000_000_000)
            .await
            .unwrap();
        let res = client
            .transfer_and_watch(&hans, alice.account_id(), 100_000_000_000)
            .await;
        if let Err(Error::Runtime(RuntimeError::Module(error))) = res {
            let error2 = ModuleError {
                module: "Balances".into(),
                error: "InsufficientBalance".into(),
            };
            assert_eq!(error, error2);
        } else {
            panic!("expected an error");
        }
    }

    #[async_std::test]
    async fn test_transfer_subscription() {
        env_logger::try_init().ok();
        let alice = PairSigner::new(AccountKeyring::Alice.pair());
        let bob = AccountKeyring::Bob.to_account_id();
        let (client, _) = test_client().await;
        let sub = client.subscribe_events().await.unwrap();
        let mut decoder = EventsDecoder::<TestRuntime>::new(client.metadata().clone());
        decoder.with_balances();
        let mut sub = EventSubscription::<TestRuntime>::new(sub, decoder);
        sub.filter_event::<TransferEvent<_>>();
        client.transfer(&alice, &bob, 10_000).await.unwrap();
        let raw = sub.next().await.unwrap().unwrap();
        let event = TransferEvent::<TestRuntime>::decode(&mut &raw.data[..]).unwrap();
        assert_eq!(
            event,
            TransferEvent {
                from: alice.account_id().clone(),
                to: bob.clone(),
                amount: 10_000,
            }
        );
    }
}