Search code examples
substrate

Substrate pallet loosely coupling example between 2 custom pallets


This official docs is about custom pallet using an substrate's pallets.

https://docs.substrate.io/how-to-guides/v3/pallet-design/loose-coupling/#2-import-the-trait

I don't know exactly how to do this with 2 custom pallets?


Solution

  • Here how I dit it:

    For example: pallet BoTrading need to call get_suitable_lp on pallet BoLiquidity

    pallets/BoLiquidity/src/lib.rs

        /// Internal helpers fn
        impl<T: Config> Pallet<T> {
            fn pick_a_suitable_lp() -> Option<u32> {
                Some(99999)
            }
        }
    
        pub trait BoLiquidityInterface{
            fn get_suitable_lp()->Option<u32>;
        }
    
        impl<T: Config> BoLiquidityInterface for Pallet<T> {
            fn get_suitable_lp()->Option<u32>{
                Self::pick_a_suitable_lp()
            }
        }
    

    pallets/BoTrading/src/lib.rs

    pub mod pallet {
        ...
        use pallet_bo_liquidity::BoLiquidityInterface;
    
        #[pallet::config]
        pub trait Config: frame_system::Config {
            ...
            type BoLiquidity: BoLiquidityInterface;
        }
    
        ...
        // call other pallet some where inside this pallet:
        let lp = T::BoLiquidity::get_suitable_lp();
        ...
    }
    

    pallets/BoTrading/Cargo.toml

    [dependencies.pallet-bo-liquidity]
    default-features = false
    path = '../BoLiquidity'
    version = '0.0.1-dev'
    

    Remember to include pallets in cargo toml of the node runtime, this code bellow focus on important thing only:

    runtime/src/lib.rs

    impl pallet_bo_trading::Config for Runtime {
        ...
        type BoLiquidity = BoLiquidityModule;
    }
    
    construct_runtime!(
        pub enum Runtime where
            Block = Block,
            NodeBlock = opaque::Block,
            UncheckedExtrinsic = UncheckedExtrinsic
        {
            ...
            BoLiquidityModule: pallet_bo_liquidity,
        }
    );