Search code examples
rustsubstrate

Is handling the `Imbalance` type mandatory after withdraw or deposit?


When using any of the functions which mint/burn the base currency (e.g. Currency::withdraw()), you're given an Imbalance return value. Does Substrate expect me to do something with it?


Solution

  • You get back an Imbalance whenever you perform some "one-sided operation" within the Balances module (deposit, slash, withdraw, etc...).

    The both PositiveImbalance and NegativeImbalance implement the Drop trait, which defines a destructor function that gets called when a variable goes out of scope.

    In the case of an Imbalance, the drop function simply updates the total issuance of the balances module to ensure that the sum of all current account balances is equal to the total issuance.

    So by default, no, you do not need to do anything with the imbalance returned to you. You can just place the result of a "one-sided operation" into an unused variable like so:

    let _ = <balances::Module<T> as Currency<_>>::withdraw(...)?;
    

    However, if you want to, you are also given a set of tools to manage imbalances returned to you:

    impl<T: Trait<I>, I: Instance> Imbalance<T::Balance> for NegativeImbalance<T, I> {
        type Opposite = PositiveImbalance<T, I>;
    
        fn zero() -> Self {...}
    
        fn drop_zero(self) -> result::Result<(), Self> {...}
    
        fn split(self, amount: T::Balance) -> (Self, Self) {...}
    
        fn merge(mut self, other: Self) -> Self {...}
    
        fn subsume(&mut self, other: Self) {...}
    
        fn offset(self, other: Self::Opposite) -> result::Result<Self, Self::Opposite> {...}
    
        fn peek(&self) -> T::Balance {...}
    }