ink_sandbox/api/
balance_api.rs

1use crate::{
2    AccountIdFor,
3    Sandbox,
4};
5use frame_support::{
6    sp_runtime::DispatchError,
7    traits::fungible::Mutate,
8};
9
10type BalanceOf<R> = <R as pallet_balances::Config>::Balance;
11
12/// Balance API for the sandbox.
13pub trait BalanceAPI<T: Sandbox>
14where
15    T: Sandbox,
16    T::Runtime: pallet_balances::Config,
17{
18    /// Mint tokens to an account.
19    ///
20    /// # Arguments
21    ///
22    /// * `address` - The address of the account to add tokens to.
23    /// * `amount` - The number of tokens to add.
24    fn mint_into(
25        &mut self,
26        address: &AccountIdFor<T::Runtime>,
27        amount: BalanceOf<T::Runtime>,
28    ) -> Result<BalanceOf<T::Runtime>, DispatchError>;
29
30    /// Return the free balance of an account.
31    ///
32    /// # Arguments
33    ///
34    /// * `account` - The account id of the account to query.
35    fn free_balance(
36        &mut self,
37        account_id: &AccountIdFor<T::Runtime>,
38    ) -> BalanceOf<T::Runtime>;
39}
40
41impl<T> BalanceAPI<T> for T
42where
43    T: Sandbox,
44    T::Runtime: pallet_balances::Config,
45{
46    fn mint_into(
47        &mut self,
48        address: &AccountIdFor<T::Runtime>,
49        amount: BalanceOf<T::Runtime>,
50    ) -> Result<BalanceOf<T::Runtime>, DispatchError> {
51        self.execute_with(|| {
52            pallet_balances::Pallet::<T::Runtime>::mint_into(address, amount)
53        })
54    }
55
56    fn free_balance(
57        &mut self,
58        account_id: &AccountIdFor<T::Runtime>,
59    ) -> BalanceOf<T::Runtime> {
60        self.execute_with(|| {
61            pallet_balances::Pallet::<T::Runtime>::free_balance(account_id)
62        })
63    }
64}
65
66#[cfg(test)]
67mod test {
68    use super::*;
69    use crate::DefaultSandbox;
70    #[test]
71    fn mint_works() {
72        let mut sandbox = DefaultSandbox::default();
73        let balance = sandbox.free_balance(&DefaultSandbox::default_actor());
74
75        sandbox
76            .mint_into(&DefaultSandbox::default_actor(), 100)
77            .unwrap();
78
79        assert_eq!(
80            sandbox.free_balance(&DefaultSandbox::default_actor()),
81            balance + 100
82        );
83    }
84}