Developers Home»How-to Guide»Loosely Coupling a Pallet

Loosely Coupling a Pallet

Goal

Learn how to use a function from another pallet.

Use Cases

Reuse a specific type from another pallet.

Overview

Loose coupling is a technique that enables re-using logic from another pallet inside a pallet. In this guide we show the simple pattern of using a type from an outside pallet in our working pallet, by using trait bounds in our pallet's configuration trait. We will loosely couple a pallet to make use of the Currency trait from frame_support.

Steps

1. Configure your workspace

In the Cargo.toml file of the pallet in your working directory, make sure you specify the pallet you want to couple to accordingly:

[dependencies]
frame-support = { default-features = false, git = "https://github.com/paritytech/substrate.git", branch = "polkadot-v0.9.17", version = "4.0.0-dev" }

# -- snip

[features]
default = ['std']
std = [
    'frame-support/std',
# -- snip
]

2. Import the trait

We want to use the Currency trait so that we can give our pallet access to the its methods.

Import the trait in your pallet:

use frame_support::traits::Currency;

3. Create a type for your pallet's Config trait

In your configuration trait, create a type that is bound by the type you want to expose to your pallet
(in this-pallet/src/lib.rs):

pub trait Config: frame_system::Config {
    // --snip--

    /// A type that is accessing our loosely coupled pallet `my-pallet`
    type LocalCurrency: Currency<Self::AccountId>;
}

4. Use the type

Use the method that the type of your loosely coupled pallet provides (in this-pallet/src/lib.rs):

// Use the getter from `my-pallet`
let total_balance = T::LocalCurrency::total_issuance();

In the above snippet, we're using total_issuance that the Currency trait exposes from frame_support.

5. Provide the implementation in runtime configuration

In our runtime configuration, usually runtime/src/lib.rs, we specify the LocalCurrency to be Balances, which is defined inside construct_runtime! macro and has a type of pallet_balances that implements the Currency trait.

impl my_pallet::Config for Runtime {
  type LocalCurrency = Balances;
}

construct_runtime! (
  pub enum Runtime where
  Block = Block,
  NodeBlock = opaque::Block,
  UncheckedExtrinsic = UncheckedExtrinsic
  {
    Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
  }
)

Examples

Resources

Last edit: on

Run into problems?
Let us Know