The idea is to swap tokens between two chains with the help of a Hash Time Lock Contract/Pallet on each chain. The swap must be executed quickly otherwise the transaction will expire and the locked tokens will go back to their ownersโ wallets. This pallet provides a way to perform an atomic swap between assets.
In atomic swaps, participant A creates a secret, gets its hash, and calls lock in the pallet to start the swap (providing: amount, hash, duration, and target). Funds are transferred to the pallet. Participant B can now do the same using the same hash created by Participant A. Participant A can now call unlock to get the tokens, revealing the secret to participant B. Participant B can now unlock their tokens.
Inspiration from: https://github.com/chatch/hashed-timelock-contract-ethereum/blob/master/test/htlcERC20.js
assert_ok!(Aswap::lock(
RuntimeOrigin::signed(ACCOUNT_A),
tx_id,
ACCOUNT_B,
hash,
timelock,
ASSET_A,
asset_amount
));
assert_ok!(Aswap::unlock(RuntimeOrigin::signed(ACCOUNT_B), tx_id, secret.to_vec()));
assert_ok!(Aswap::cancel(RuntimeOrigin::signed(ACCOUNT_A), tx_id));
/// structure for saving all lock details
pub struct LockDetails<AssetBalance, AssetId, AccountId, BlockNumber> {
pub tx_id: [u8; 32],
pub sender: AccountId,
pub recipient: AccountId,
pub asset_id: AssetId,
pub amount: AssetBalance,
pub hashlock: [u8; 32],
pub expiration_block: BlockNumber,
pub is_withdraw: bool,
pub is_refunded: bool,
}
/// type for modeling LockDetails
pub type LockDetailsOf<T> =
LockDetails<AssetBalanceOf<T>, AssetIdOf<T>, AccountIdOf<T>, BlockNumberOf<T>>;
/// Data storage for keeping all lock transactions
pub(super) type LockTransactions<T: Config> =
StorageMap<_, Blake2_128Concat, [u8; 32], LockDetailsOf<T>, OptionQuery>;
/// Data storage for keeping all known secrets
pub(super) type KnownSecrets<T: Config> =
StorageMap<_, Blake2_128Concat, [u8; 32], Vec<u8>, OptionQuery>;
Some helpers where created as part of the pallet code to allow extrinsics to perform certain actions and validations. On the other hand, they were created to reuse logic common to several extrincs and therefore keep extrinsics' code cleanear.
pub trait PalletHelpers: Config {
/// checks if a tx_id exists in the storage
fn lock_details_exists(tx_id: [u8; 32]) -> bool;
/// ensure that tx_id exists in the storage and who equals to recipient or throws error
fn ensure_lock_details_valid_to_unlock(
who: &AccountIdOf<Self>,
tx_id: [u8; 32],
) -> Result<(), Error<Self>>;
/// ensure that tx_id's hash and preimage's hash matches or throws error
fn ensure_hashlock_matches(tx_id: [u8; 32], preimage: Vec<u8>) -> Result<(), Error<Self>>;
/// ensure that tx_id's expiration block is in the past and it's refundable or Error
fn ensure_refundable(tx_id: [u8; 32]) -> Result<(), Error<Self>>;
/// ensure that tx_id's expiration block is valid and withdrawable or Error
fn ensure_withdrawable(tx_id: [u8; 32]) -> Result<(), Error<Self>>;
/// ensures that provided amount is above zero or throws an Error
fn ensure_is_not_zero(amount: AssetBalanceOf<Self>) -> Result<(), Error<Self>>;
/// checks if account has the amount expected to withdraw for the specific asset
fn ensure_has_balance(
who: &AccountIdOf<Self>,
asset_id: AssetIdOf<Self>,
amount: AssetBalanceOf<Self>,
) -> Result<(), Error<Self>>;
/// asset exists or dispatchs an Error
fn ensure_asset_exists(asset_id: AssetIdOf<Self>) -> Result<(), Error<Self>>;
/// checks current block number with the deadline provided. Error if current block number is
/// above
fn ensure_valid_deadline(expiration_block: &Self::BlockNumber) -> Result<(), Error<Self>>;
/// checks current block number with the deadline provided. Error if current block number is
/// above
fn ensure_deadline(expiration_block: &Self::BlockNumber) -> Result<(), Error<Self>>;
/// checks current block number with the deadline provided. Error if block number has not
/// expired
fn ensure_expired(expiration_block: &Self::BlockNumber) -> Result<(), Error<Self>>;
}
Custom errors and especific events where created to handle validations and emit notifications during extrinsics' execution.
/// Notify about new lock transaction
Locked {
tx_id: [u8; 32],
recipient: AccountIdOf<T>,
hashlock: [u8; 32],
expiration_block: BlockNumberOf<T>,
asset_id: AssetIdOf<T>,
asset_amount: AssetBalanceOf<T>,
},
/// Notify about unlock transaction
Unlocked { tx_id: [u8; 32] },
/// Notify about canceled transaction
Canceled { tx_id: [u8; 32] }
/// Token doesn't exist
TokenNotExists,
/// Insufficient funds to perform operation
LowBalance,
/// invalid amount or below minimum
InvalidAmount,
/// Operation not inplemented
NotImplemented,
/// Overflow or Underflow error
OverflowOrUnderflow,
/// deadline block has passed
Expired,
/// Invalid Timelock. Timelock + current block must be in the future
InvalidTimelock,
/// hash does not match
InvalidPreimage,
/// transaction doesn't exists
TransactionNotExists,
/// lock with transaction id already exists
TransactionIdExists,
/// already withdrawn
AlreadyWithdrawn,
/// already refunded
AlreadyRefunded,
/// Invalid receiver to unlock
InvalidReceiver,
/// Timelock has not expired
TimeLockNotExpired
A set of unit tests were created to validate extrinsics' results under happy and unexpected conditions. Mock.rs was created to have a runtime for testing and to include additional logic like creating and funding some accounts and creating some initial tokens to play with, along with some helpers. All mock data like accounts, initial balances, and tokens that are currenty in use as part of the tests can be changed through mock_data.rs.
A fresh FRAME-based Substrate node, ready for hacking ๐
Follow the steps below to get started with the Node Template, or get it up and running right from your browser in just a few clicks using the Substrate Playground ๐ ๏ธ
Install nix and optionally direnv and
lorri for a fully plug and play experience for setting up
the development environment. To get all the correct dependencies activate direnv direnv allow
and
lorri lorri shell
.
First, complete the basic Rust setup instructions.
Use Rust's native cargo
command to build and launch the template node:
cargo run --release -- --dev
The cargo run
command will perform an initial build. Use the following command to build the node
without launching it:
cargo build --release
Once the project has been built, the following command can be used to explore all parameters and subcommands:
./target/release/node-template -h
The provided cargo run
command will launch a temporary node and its state will be discarded after
you terminate the process. After the project has been built, there are other ways to launch the
node.
This command will start the single-node development chain with non-persistent state:
./target/release/node-template --dev
Purge the development chain's state:
./target/release/node-template purge-chain --dev
Start the development chain with detailed logging:
RUST_BACKTRACE=1 ./target/release/node-template -ldebug --dev
Development chain means that the state of our chain will be in a tmp folder while the nodes are running. Also, alice account will be authority and sudo account as declared in the genesis state. At the same time the following accounts will be pre-funded:
- Alice
- Bob
- Alice//stash
- Bob//stash
In case of being interested in maintaining the chain' state between runs a base path must be added so the db can be stored in the provided folder instead of a temporal one. We could use this folder to store different chain databases, as a different folder will be created per different chain that is ran. The following commands shows how to use a newly created folder as our db base path.
// Create a folder to use as the db base path
$ mkdir my-chain-state
// Use of that folder to store the chain state
$ ./target/release/node-template --dev --base-path ./my-chain-state/
// Check the folder structure created inside the base path after running the chain
$ ls ./my-chain-state
chains
$ ls ./my-chain-state/chains/
dev
$ ls ./my-chain-state/chains/dev
db keystore network
Once the node template is running locally, you can connect it with Polkadot-JS Apps front-end to interact with your chain. Click here connecting the Apps to your local node template.
If you want to see the multi-node consensus algorithm in action, refer to our Simulate a network tutorial.
A Substrate project such as this consists of a number of components that are spread across a few directories.
A blockchain node is an application that allows users to participate in a blockchain network. Substrate-based blockchain nodes expose a number of capabilities:
- Networking: Substrate nodes use the
libp2p
networking stack to allow the nodes in the network to communicate with one another. - Consensus: Blockchains must have a way to come to consensus on the state of the network. Substrate makes it possible to supply custom consensus engines and also ships with several consensus mechanisms that have been built on top of Web3 Foundation research.
- RPC Server: A remote procedure call (RPC) server is used to interact with Substrate nodes.
There are several files in the node
directory - take special note of the following:
chain_spec.rs
: A chain specification is a source code file that defines a Substrate chain's initial (genesis) state. Chain specifications are useful for development and testing, and critical when architecting the launch of a production chain. Take note of thedevelopment_config
andtestnet_genesis
functions, which are used to define the genesis state for the local development chain configuration. These functions identify some well-known accounts and use them to configure the blockchain's initial state.service.rs
: This file defines the node implementation. Take note of the libraries that this file imports and the names of the functions it invokes. In particular, there are references to consensus-related topics, such as the block finalization and forks and other consensus mechanisms such as Aura for block authoring and GRANDPA for finality.
After the node has been built, refer to the embedded documentation to learn more about the capabilities and configuration parameters that it exposes:
./target/release/node-template --help
In Substrate, the terms "runtime" and "state transition function" are analogous - they refer to the core logic of the blockchain that is responsible for validating blocks and executing the state changes they define. The Substrate project in this repository uses FRAME to construct a blockchain runtime. FRAME allows runtime developers to declare domain-specific logic in modules called "pallets". At the heart of FRAME is a helpful macro language that makes it easy to create pallets and flexibly compose them to create blockchains that can address a variety of needs.
Review the FRAME runtime implementation included in this template and note the following:
- This file configures several pallets to include in the runtime. Each pallet configuration is
defined by a code block that begins with
impl $PALLET_NAME::Config for Runtime
. - The pallets are composed into a single runtime by way of the
construct_runtime!
macro, which is part of the core FRAME Support system library.
The runtime in this project is constructed using many FRAME pallets that ship with the
core Substrate repository and a
template pallet that is defined in the pallets
directory.
A FRAME pallet is compromised of a number of blockchain primitives:
- Storage: FRAME defines a rich set of powerful storage abstractions that makes it easy to use Substrate's efficient key-value database to manage the evolving state of a blockchain.
- Dispatchables: FRAME pallets define special types of functions that can be invoked (dispatched) from outside of the runtime in order to update its state.
- Events: Substrate uses events and errors to notify users of important changes in the runtime.
- Errors: When a dispatchable fails, it returns an error.
- Config: The
Config
configuration interface is used to define the types and parameters upon which a FRAME pallet depends.
First, install Docker and Docker Compose.
Then run the following command to start a single node development chain.
./scripts/docker_run.sh
This command will firstly compile your code, and then start a local development network. You can
also replace the default command
(cargo build --release && ./target/release/node-template --dev --ws-external
)
by appending your own. A few useful ones are as follow.
# Run Substrate node without re-compiling
./scripts/docker_run.sh ./target/release/node-template --dev --ws-external
# Purge the local dev chain
./scripts/docker_run.sh ./target/release/node-template purge-chain --dev
# Check whether the code is compilable
./scripts/docker_run.sh cargo check