Cross-Chain Development and Bridges
Cross-chain development enables applications to communicate and transfer assets across multiple blockchain networks.
Cross-Chain Architecture
Bridge Development
Lock and Mint Bridge
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
contract LockMintBridge is ReentrancyGuard {
struct LockRequest {
address sender;
address token;
uint256 amount;
uint256 destChainId;
bytes destAddress;
uint256 nonce;
bool executed;
}
mapping(uint256 => LockRequest) public lockRequests;
uint256 public lockNonce;
mapping(address => uint256) public lockedTokens;
mapping(address => mapping(address => uint256)) public allowances;
modifier onlyBridge() {
require(bridgeValidators[msg.sender], "Not a bridge validator");
_;
}
function lockTokens(
address token,
uint256 amount,
uint256 destChainId,
bytes calldata destAddress
) external nonReentrant {
require(amount > 0, "Zero amount");
require(allowances[msg.sender][token] >= amount, "Insufficient allowance");
allowances[msg.sender][token] -= amount;
lockedTokens[token] += amount;
uint256 nonce = lockNonce++;
lockRequests[nonce] = LockRequest({
sender: msg.sender,
token: token,
amount: amount,
destChainId: destChainId,
destAddress: destAddress,
nonce: nonce,
executed: false
});
// Transfer tokens to bridge
IERC20(token).transferFrom(msg.sender, address(this), amount);
emit TokensLocked(nonce, msg.sender, token, amount, destChainId);
}
function mintTokens(
uint256 lockNonce,
address recipient,
address token,
uint256 amount,
bytes calldata signature
) external onlyBridge nonReentrant {
require(!lockRequests[lockNonce].executed, "Already executed");
// Verify signature from source chain
require(
_verifySignature(lockNonce, recipient, token, amount, signature),
"Invalid signature"
);
lockRequests[lockNonce].executed = true;
// Mint tokens on destination chain
IERC20(token).mint(recipient, amount);
emit TokensMinted(lockNonce, recipient, token, amount);
}
}
Atomic Swap
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/cryptography/Hashes.sol";
contract AtomicSwap is ReentrancyGuard {
struct Swap {
address initiator;
address participant;
address initiatorToken;
address participantToken;
uint256 initiatorAmount;
uint256 participantAmount;
bytes32 hashLock;
uint256 timelock;
bool initiatorClaimed;
bool participantClaimed;
}
mapping(bytes32 => Swap) public swaps;
modifier onlyInitiator(bytes32 swapId) {
require(swaps[swapId].initiator == msg.sender, "Not initiator");
_;
}
function initiateSwap(
address participant,
address initiatorToken,
address participantToken,
uint256 initiatorAmount,
uint256 participantAmount,
bytes32 hashLock,
uint256 duration
) external nonReentrant returns (bytes32 swapId) {
swapId = keccak256(
abi.encodePacked(
msg.sender,
participant,
initiatorToken,
participantToken,
block.timestamp
)
);
swaps[swapId] = Swap({
initiator: msg.sender,
participant: participant,
initiatorToken: initiatorToken,
participantToken: participantToken,
initiatorAmount: initiatorAmount,
participantAmount: participantAmount,
hashLock: hashLock,
timelock: block.timestamp + duration,
initiatorClaimed: false,
participantClaimed: false
});
// Transfer initiator tokens to contract
IERC20(initiatorToken).transferFrom(msg.sender, address(this), initiatorAmount);
emit SwapInitiated(swapId, msg.sender, participant, initiatorAmount);
}
function claimSwap(
bytes32 swapId,
bytes32 secret
) external nonReentrant {
Swap storage swap = swaps[swapId];
require(msg.sender == swap.participant, "Not participant");
require(block.timestamp < swap.timelock, "Timelock expired");
require(!swap.initiatorClaimed, "Already claimed");
bytes32 hash = keccak256(abi.encodePacked(secret));
require(hash == swap.hashLock, "Invalid secret");
swap.participantClaimed = true;
// Transfer participant tokens to initiator
IERC20(swap.participantToken).transfer(swap.initiator, swap.participantAmount);
// Release initiator tokens to participant
IERC20(swap.initiatorToken).transfer(msg.sender, swap.initiatorAmount);
emit SwapClaimed(swapId, msg.sender, secret);
}
function refundSwap(bytes32 swapId) external nonReentrant onlyInitiator(swapId) {
Swap storage swap = swaps[swapId];
require(block.timestamp >= swap.timelock, "Timelock not expired");
require(!swap.participantClaimed, "Already claimed");
swap.initiatorClaimed = true;
// Return initiator tokens
IERC20(swap.initiatorToken).transfer(msg.sender, swap.initiatorAmount);
emit SwapRefunded(swapId, msg.sender);
}
}
LayerZero Integration
Cross-Chain Message
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@layerzerolabs/solidity-examples/contracts/lzApp/LzApp.sol";
import "@layerzerolabs/solidity-examples/contracts/lzApp/NonblockingLzApp.sol";
contract CrossChainToken is NonblockingLzApp {
mapping(uint16 => mapping(address => uint256)) public remoteBalances;
constructor(
address _lzEndpoint,
uint16[] memory _remoteChainIds,
address[] memory _remoteAddresses
) LzApp(_lzEndpoint) {
for (uint256 i = 0; i < _remoteChainIds.length; i++) {
trustedRemoteLookup[_remoteChainIds[i]] = _remoteAddresses[i];
}
}
function sendFrom(
uint16 _dstChainId,
address _toAddress,
uint256 _amount,
address _zroPaymentAddress,
bytes memory _adapterParams
) public payable {
_send(_dstChainId, _toAddress, _amount, msg.sender, _zroPaymentAddress, _adapterParams);
}
function _receivePayload(
uint16 _srcChainId,
bytes calldata _srcAddress,
address _dstAddress,
uint64 _nonce,
uint256 _gasLimit,
bytes calldata _payload
) internal override {
require(msg.sender == lzEndpoint, "Invalid endpoint");
(address to, uint256 amount) = abi.decode(_payload, (address, uint256));
// Credit tokens on destination chain
remoteBalances[_srcChainId][_dstAddress] += amount;
emit MessageReceived(_srcChainId, _dstAddress, to, amount);
}
function estimateFees(
uint16 _dstChainId,
address _toAddress,
uint256 _amount,
bool _useZro,
bytes memory _adapterParams
) public view returns (uint256 nativeFee, uint256 zroFee) {
return lzEndpoint.estimateFees(
_dstChainId,
address(this),
abi.encodePacked(_toAddress, _amount),
_useZro,
_adapterParams
);
}
}
Axelar Integration
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@axelar-network/axelar-gmp-solidity/contracts/AxelarExecutable.sol";
contract AxelarBridge is AxelarExecutable {
IAxelarGateway public immutable gateway;
constructor(
address gatewayAddress
) AxelarExecutable(gatewayAddress) {
gateway = IAxelarGateway(gatewayAddress);
}
function sendCrossChainMessage(
string calldata destinationChain,
string calldata destinationAddress,
bytes calldata payload
) external payable {
gateway.callContract(
destinationChain,
destinationAddress,
payload,
msg.value
);
emit MessageSent(destinationChain, destinationAddress, payload);
}
function _execute(
bytes calldata,
bytes calldata payload
) internal override {
(address to, uint256 amount, bytes memory data) = abi.decode(
payload,
(address, uint256, bytes)
);
// Execute cross-chain action
_executeAction(to, amount, data);
}
function _executeAction(
address to,
uint256 amount,
bytes memory data
) internal {
// Custom logic
emit CrossChainActionExecuted(to, amount, data);
}
}
Wormhole Integration
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
import "@wormhole-foundation/wormhole-solidity/contracts/interfaces/Implementation.sol";
contract WormholeBridge {
IWormhole public immutable wormhole;
uint16 public constant SOURCE_CHAIN = 2; // Ethereum
constructor(address wormholeAddress) {
wormhole = IWormhole(wormholeAddress);
}
function sendWormholeMessage(
uint16 targetChain,
address targetAddress,
bytes calldata payload
) external payable returns (uint64 sequence) {
sequence = wormhole.publishMessage{value: msg.value}(
0, // nonce
targetChain,
targetAddress,
abi.encodePacked(payload),
200 // consistency level
);
emit MessageSent(sequence, targetChain, targetAddress);
}
function receiveWormholeMessages(
bytes calldata payload,
bytes[] calldata signatures,
uint64 sourceChain,
uint64 sequence
) external {
// Verify wormhole message
bytes32 hash = wormhole.hashMessage(
sourceChain,
address(this),
sequence,
0,
payload
);
require(
wormhole.verifySignatures(hash, signatures),
"Invalid signature"
);
// Process message
_processMessage(payload, sourceChain, sequence);
}
function _processMessage(
bytes calldata payload,
uint64 sourceChain,
uint64 sequence
) internal {
// Custom logic
emit MessageReceived(sourceChain, sequence, payload);
}
}
Multi-Chain Deployment Patterns
Deterministic Deployment
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract DeterministicDeployer {
address public immutable deployer;
constructor() {
deployer = msg.sender;
}
function computeAddress(
bytes32 salt,
bytes memory bytecode
) public view returns (address) {
return address(uint160(uint256(keccak256(abi.encodePacked(
bytes1(0xff),
address(this),
salt,
keccak256(bytecode)
)))));
}
function deploy(
bytes32 salt,
bytes memory bytecode
) external returns (address) {
require(msg.sender == deployer, "Not deployer");
address deployed;
assembly {
deployed := create2(0, add(bytecode, 0x20), mload(bytecode), salt)
}
require(deployed != address(0), "Deployment failed");
emit ContractDeployed(salt, deployed);
return deployed;
}
}
Cross-Chain Address Mapping
// Cross-chain address mapping
const CHAIN_CONFIGS = {
ethereum: {
chainId: 1,
rpc: process.env.ETHEREUM_RPC,
bridgeAddress: '0x...',
factoryAddress: '0x...'
},
polygon: {
chainId: 137,
rpc: process.env.POLYGON_RPC,
bridgeAddress: '0x...',
factoryAddress: '0x...'
},
arbitrum: {
chainId: 42161,
rpc: process.env.ARBITRUM_RPC,
bridgeAddress: '0x...',
factoryAddress: '0x...'
}
};
async function getDeployedAddress(chain: string, salt: string): Promise<string> {
const config = CHAIN_CONFIGS[chain];
const factory = new ethers.Contract(
config.factoryAddress,
['function computeAddress(bytes32,bytes) view returns (address)'],
new ethers.JsonRpcProvider(config.rpc)
);
const bytecode = await getContractBytecode();
return factory.computeAddress(salt, bytecode);
}
Trade-offs
| Bridge Type | Security | Speed | Cost | Complexity |
|---|---|---|---|---|
| Lock/Mint | High | Medium | Medium | Medium |
| Atomic Swap | Very High | Slow | Low | High |
| Liquidity Pool | Medium | Fast | Medium | Medium |
| Optimistic | High | Slow | Low | High |
| zk-Bridge | Very High | Fast | High | Very High |
Real-World Example: Multi-Chain DEX
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.19;
contract MultiChainDEX {
struct Pool {
address token0;
address token1;
uint256 reserve0;
uint256 reserve1;
uint256 totalSupply;
}
mapping(bytes32 => Pool) public pools;
mapping(uint16 => address) public remotePools;
function swap(
bytes32 poolId,
bool zeroForOne,
uint256 amountIn,
uint16 dstChainId
) external {
Pool storage pool = pools[poolId];
// Calculate swap output
uint256 amountOut = _calculateSwap(
pool,
zeroForOne,
amountIn
);
if (dstChainId == block.chainid) {
// Same chain swap
_executeSwap(pool, zeroForOne, amountIn, amountOut);
} else {
// Cross-chain swap
_initiateCrossChainSwap(
poolId,
zeroForOne,
amountIn,
amountOut,
dstChainId
);
}
}
function _initiateCrossChainSwap(
bytes32 poolId,
bool zeroForOne,
uint256 amountIn,
uint256 amountOut,
uint16 dstChainId
) internal {
// Send message via LayerZero
bytes memory payload = abi.encode(
poolId,
zeroForOne,
amountIn,
amountOut,
msg.sender
);
lzEndpoint.send{value: msg.value}(
dstChainId,
abi.encodePacked(remotePools[dstChainId]),
payload,
msg.sender,
address(0),
adapterParams
);
emit CrossChainSwapInitiated(
poolId,
zeroForOne,
amountIn,
amountOut,
dstChainId
);
}
}
Interview Questions
-
Explain the security trade-offs between different bridge architectures. Which approach provides the strongest security guarantees?
-
How does LayerZero ensure message delivery across chains? What happens if a message fails to deliver?
-
Design a multi-chain lending protocol that allows users to borrow on one chain using collateral on another. Consider security, latency, and cost.
Quiz Questions
-
What is the primary security concern with cross-chain bridges?
- A) High gas costs
- B) Centralization risk
- C) Low throughput
- D) Complex user interface
-
Which protocol uses optimistic verification for cross-chain messages?
- A) LayerZero
- B) Axelar
- C) Wormhole
- D) Hyperlane
-
What is an atomic swap?
- A) A type of bridge
- B) A trustless cross-chain exchange
- C) A multi-sig wallet
- D) A type of oracle