Cross-Chain Staking Mechanisms

Core Components of Cross-Chain Staking (EVM based)

Staking Contracts

Staking contracts are integral components of blockchain ecosystems, enabling users to lock their tokens in a protocol to support network operations like block validation and, in return, earn rewards. In cross-chain environments, such as those facilitated by Wormhole, staking contracts allow users to stake tokens on one blockchain while receiving staking derivatives or rewards on another, enhancing liquidity and interoperability.

Implementing Cross-Chain Staking with Wormhole

Wormhole is a decentralized cross-chain interoperability protocol that connects multiple blockchain networks, including Ethereum, Solana, Binance Smart Chain, and others. It enables seamless transfer of assets and data across these networks, facilitating cross-chain staking mechanisms.

To implement a cross-chain staking contract using Wormhole, developers can utilize Wormhole's Solidity SDK to create cross-chain messaging contracts. This involves deploying smart contracts on the source and destination chains that can send and receive messages via the Wormhole protocol. The process includes:

  1. Sender Contract: Deployed on the source chain, this contract initiates the staking process by sending a message containing staking data to the destination chain.

  2. Receiver Contract: Deployed on the destination chain, this contract receives the staking data and executes the staking operation accordingly.

This setup allows users to stake tokens on one blockchain and have the staking operation executed on another, leveraging the unique features and rewards of different networks.

Example: Cross-Chain Staking Contract Using Wormhole

Below is a simplified example of how such a contract might be structured using Solidity:

// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.13;


import "wormhole-solidity-sdk/interfaces/IWormholeRelayer.sol";
import "wormhole-solidity-sdk/interfaces/IWormholeReceiver.sol";


contract CrossChainStaking is IWormholeReceiver {
    address public owner;
    IWormholeRelayer public wormholeRelayer;


    constructor(address _wormholeRelayer) {
        owner = msg.sender;
        wormholeRelayer = IWormholeRelayer(_wormholeRelayer);
    }


    function stakeTokens(uint256 amount, uint16 targetChain, address targetContract) external payable {
        // Logic to lock tokens on the source chain


        // Prepare the payload with staking information
        bytes memory payload = abi.encode(amount, msg.sender);


        // Send the message to the target chain
        wormholeRelayer.send{value: msg.value}(
            targetChain,
            targetContract,
            payload,
            0, // No receiver value needed
            1000000, // Gas limit for the target chain execution
            msg.sender // Refund address for any excess fees
        );
    }


    function receiveWormholeMessages(bytes memory payload, bytes[] memory, bytes32, uint16, bytes32 sourceAddress) external payable override {
        // Ensure only the Wormhole relayer can call this function
        require(msg.sender == address(wormholeRelayer), "Unauthorized");


        // Decode the payload
        (uint256 amount, address staker) = abi.decode(payload, (uint256, address));


        // Logic to stake tokens on the destination chain on behalf of the staker
    }
}

Explanation:

  • Constructor: Initializes the contract with the Wormhole relayer's address.

  • stakeTokens Function: Locks tokens on the source chain and sends a message to the target chain with staking details.

  • receiveWormholeMessages Function: Executed on the destination chain upon receiving the message; it decodes the payload and performs the staking operation on behalf of the user.

This example demonstrates the fundamental structure of a cross-chain staking contract using Wormhole's cross-chain messaging capabilities. Developers can expand upon this foundation to include additional features such as reward distribution, unstaking mechanisms, and enhanced security measures to suit specific application requirements.

For a more comprehensive guide and additional examples, developers can refer to Wormhole's official documentation and tutorials.

References:

These resources provide in-depth information and practical examples to assist developers in implementing cross-chain staking contracts using Wormhole.

Token Wrapping and Bridging

In blockchain ecosystems, token wrapping and bridging are essential mechanisms that facilitate interoperability between disparate networks. These processes enable assets from one blockchain to be utilized on another, enhancing liquidity and expanding the utility of digital assets across platforms.

Token Wrapping:

Token wrapping involves creating a representation of an asset from one blockchain on another blockchain. This is achieved by locking the original asset in a smart contract on the source chain and minting an equivalent amount of wrapped tokens on the destination chain. These wrapped tokens are pegged to the value of the original asset, allowing them to be used within the ecosystem of the destination blockchain. For example, wrapping Bitcoin (BTC) on the Ethereum network results in Wrapped Bitcoin (WBTC), an ERC-20 token that mirrors BTC's value and can be utilized in Ethereum-based decentralized applications (dApps).

Token Bridging:

Token bridging refers to the process of transferring tokens from one blockchain to another, enabling cross-chain interactions. Bridges utilize smart contracts to lock tokens on the source chain and mint corresponding wrapped tokens on the destination chain. This mechanism ensures that the total supply of the asset remains constant across chains, maintaining economic equilibrium. Bridging enhances the versatility of tokens, allowing them to participate in various dApps, decentralized finance (DeFi) protocols, and other blockchain services beyond their native environments.

Wormhole's Role in Token Wrapping and Bridging:

Wormhole is a decentralized cross-chain interoperability protocol that facilitates token wrapping and bridging between multiple blockchains, including Ethereum, Solana, Binance Smart Chain, and others. By leveraging Wormhole's Token Bridge, users can transfer assets seamlessly across supported networks. The process involves locking the original tokens in a smart contract on the source chain and minting equivalent wrapped tokens on the destination chain, enabling cross-chain liquidity and interaction.

Bridging using wormhole

  1. Initialize the Wormhole SDK: Set up the Wormhole SDK with the desired network configurations.

  2. Attest the Token: Before transferring tokens, you need to attest them on the source chain. This process registers the token on the Wormhole network, enabling its transfer to other chains.

  3. Transfer the Token: Once attested, you can initiate a transfer to the destination chain. This involves creating a wrapped version of the token on the target chain.

Code:

import { wormhole, TokenId, TokenTransfer, getSigner, amount, isTokenId, waitLog } from '@certusone/wormhole-sdk';

(async () => {
  // Initialize Wormhole SDK for Testnet with EVM and Solana support
  const wh = await wormhole('Testnet', ['evm', 'solana']);

  // Get chain contexts for source and destination chains
  const sendChain = wh.getChain('Avalanche');
  const rcvChain = wh.getChain('Solana');

  // Define the token to transfer (e.g., native token on source chain)
  const token = TokenId(sendChain.chain, 'native');

  // Define the amount to transfer
  const amt = '0.05';

  // Set automatic transfer flag
  const automatic = false;

  // Get signers for source and destination chains
  const source = await getSigner(sendChain);
  const destination = await getSigner(rcvChain);

  // Get token decimals
  const decimals = isTokenId(token)
    ? Number(await wh.getDecimals(token.chain, token.address))
    : sendChain.config.nativeTokenDecimals;

  // Perform the token transfer
  const xfer = await TokenTransfer.tokenTransfer(
    wh,
    {
      token,
      amount: amount.units(amount.parse(amt, decimals)),
      source,
      destination,
      delivery: {
        automatic,
      },
    }
  );

  // Wait for the transfer to complete and log the receipt
  const receipt = await waitLog(wh, xfer);
  console.log(receipt);
})();

This example provides a foundational structure for implementing cross-chain staking using Wormhole's interoperability features. Developers can expand upon this by adding functionalities such as reward distribution, unstaking mechanisms, and security measures to suit specific application requirements.

References:

Validator Roles Across Chains

In the Wormhole ecosystem, validators, known as "Guardians," play a pivotal role in facilitating secure and decentralized cross-chain communication. These Guardians are responsible for observing and verifying messages across various blockchains, ensuring the integrity and authenticity of cross-chain transactions.

Guardian Network Composition:

The Guardian network comprises 19 validator nodes operated by reputable entities, including Certus One, Everstake, Staked, and Chorus One. This decentralized set of validators monitors the state of each supported blockchain within the Wormhole network. When a cross-chain message is emitted from a core bridge contract, Guardians independently observe and sign the message. A message is considered authentic only if it secures signatures from more than two-thirds of the Guardians, ensuring a high threshold for consensus and security.

Li.fi Blog

Roles and Responsibilities:

  • Observation and Verification: Guardians continuously monitor multiple blockchains for events and messages pertinent to Wormhole. Upon detecting a message, they verify its validity and, if deemed legitimate, provide their cryptographic signature.

  • Consensus Building: A message requires approval from at least two-thirds of the Guardians to be considered valid. This consensus mechanism ensures that no single entity can unilaterally approve a cross-chain transaction, thereby enhancing security.

  • Message Relay Facilitation: Once a message achieves the necessary consensus, it is packaged into a Verifiable Action Approval (VAA). Relayers, which can be independent service providers or entities within the Wormhole ecosystem, are then responsible for delivering these VAAs to the destination blockchain. It's important to note that while relayers facilitate message delivery, they do not have the capacity to tamper with the outcome, as the security is upheld by the Guardian signatures. GitHub

Staking Tokens on Source Chain

The cross-chain staking process begins with users staking their tokens on the source blockchain. This initial step involves locking the user's assets in a staking contract, ensuring their commitment to the staking process. The contract records the user's address, the amount staked, and relevant metadata.

Key Points of the Staking Process on the Source Chain:

  1. Token Deposit: Users transfer their tokens to the staking contract, locking the assets within the source blockchain's ecosystem.

  2. User Verification: The contract verifies the user's identity or wallet address to ensure authenticity and avoid fraudulent staking attempts.

  3. Reward Initialization: The system starts tracking the user's staking duration, which contributes to the calculation of rewards.

  4. Cross-Chain Notification: Once the staking is complete, the contract prepares a payload containing the staking details. This payload is crucial for cross-chain communication, enabling the destination chain to process and mirror the stake.

Example Workflow:

  • A user stakes 100 SOL tokens on Solana's source chain using the staking contract.

  • The staking contract locks the SOL tokens and records the transaction.

  • A message containing staking details (user address, amount staked, etc.) is sent to the Wormhole network to facilitate communication with the destination chain.

This step is critical as it establishes the foundation for cross-chain interactions, ensuring secure and transparent operations before tokens are bridged or mirrored on the target blockchain.

Wrapping and Transferring Assets via Wormhole

In a cross-chain staking process, after users stake their tokens on the source chain, the next critical step involves wrapping and transferring these assets to the destination chain using Wormhole. This process ensures that the staked assets can participate in staking mechanisms on a different blockchain, thereby enhancing interoperability and liquidity.

Process Overview:

  1. Token Wrapping: The original tokens staked on the source chain are locked in a smart contract. In return, an equivalent representation of these tokens, known as wrapped tokens, is minted on the destination chain. This mechanism ensures that the total supply of tokens remains consistent across chains.

  2. Cross-Chain Transfer via Wormhole: Wormhole facilitates the secure transfer of wrapped tokens between blockchains. It employs a decentralized network of guardians that observe and verify token lockups on the source chain and subsequently mint corresponding wrapped tokens on the destination chain.

Implementation Example:

Below is a simplified example of how to implement the wrapping and transferring of assets using Wormhole's Token Bridge in Solidity:

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;


import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "wormhole/ethereum/contracts/bridge/interfaces/IWormhole.sol";


contract CrossChainStaking is Ownable {
    IWormhole public wormhole;
    IERC20 public stakingToken;
    mapping(address => uint256) public stakedBalances;


    event Staked(address indexed user, uint256 amount, uint16 targetChain);


    constructor(address _wormhole, address _stakingToken) {
        wormhole = IWormhole(_wormhole);
        stakingToken = IERC20(_stakingToken);
    }


    function stakeTokens(uint256 amount, uint16 targetChain) external {
        require(amount > 0, "Amount must be greater than 0");
        require(stakingToken.transferFrom(msg.sender, address(this), amount), "Transfer failed");


        stakedBalances[msg.sender] += amount;


        // Prepare the payload for cross-chain message
        bytes memory payload = abi.encode(msg.sender, amount);


        // Send the message to the target chain via Wormhole
        wormhole.publishMessage(targetChain, payload, 1);


        emit Staked(msg.sender, amount, targetChain);
    }


    // Function to handle incoming messages from Wormhole
    function receiveMessage(bytes memory payload) external {
        // Decode the payload and perform necessary actions
        (address user, uint256 amount) = abi.decode(payload, (address, uint256));
        // Implement logic to handle staking on the target chain
    }
}

Explanation:

  • Contract Initialization: The contract is initialized with the addresses of the Wormhole core contract and the staking token.

  • Staking Function: Users can stake tokens by calling the stakeTokens function, specifying the amount and the target chain ID. The function transfers the specified amount of tokens from the user's address to the contract, updates the staked balance, prepares a payload with the staking information, and sends a cross-chain message via Wormhole to the target chain.

  • Message Handling: The receiveMessage function is designed to handle incoming messages from Wormhole. It decodes the payload and implements the necessary logic to process staking on the target chain.

Redeeming Tokens on Target Chain

The final step in the cross-chain staking process is redeeming tokens on the target blockchain. This step allows users to access the wrapped tokens, which represent their staked assets on the source chain, enabling participation in staking or other decentralized finance (DeFi) activities on the target chain.

Key Steps in Redeeming Tokens on the Target Chain:

Message Validation:

  • The Wormhole network verifies the integrity and authenticity of the message sent from the source chain.

  • Guardians on the Wormhole network validate the lockup event and ensure that the wrapped token minting is legitimate.

Minting Wrapped Tokens:

  • After successful validation, the equivalent amount of wrapped tokens is minted on the target blockchain.

  • These tokens are sent to the user's wallet address, enabling them to utilize the assets.

User Access to Funds:

  • Once the wrapped tokens are minted, users can use them for staking, liquidity provision, or other DeFi activities on the target chain.

  • Users also retain the option to redeem the wrapped tokens back to the source chain if needed.

Example Workflow:

  • A user stakes 100 SOL on Solana, which is locked in the staking contract.

  • Through Wormhole, wrapped SOL (wSOL) tokens are minted on Ethereum and credited to the user's wallet.

  • The user can now stake the wSOL tokens on an Ethereum-based protocol or use them in other DeFi platforms.

Benefits of the Process:

  • Liquidity Enhancement: Users can leverage their staked assets on multiple blockchains.

  • DeFi Opportunities: Redeemed tokens on the target chain open up access to a wider array of DeFi protocols.

  • Interoperability: By enabling seamless movement of assets, this step strengthens cross-chain interoperability and user engagement.

This seamless token redemption ensures that users can efficiently interact with decentralized applications across multiple blockchain ecosystems, maximizing the utility of their assets.

Last updated