Example: Cross-Chain Counter
Write a counter that will increment from a source chain to a destination chain.
Contracts and Patterns
pragma solidity 0.8.16;
import {ITelepathyRouter} from "src/amb/interfaces/ITelepathy.sol";
import {TelepathyHandler} from "src/amb/interfaces/TelepathyHandler.sol";
contract SourceCounter {
ITelepathyRouter router;
uint32 destinationChainId;
constructor(address _router, uint32 _destinationChainId) {
router = ITelepathyRouter(_router);
destinationChainId = _destinationChainId;
}
// Increment counter on target chain by given amount
function increment(uint256 _amount, address _destinationCounter) external virtual {
bytes memory msgData = abi.encode(_amount);
router.send(destinationChainId, _destinationCounter, msgData);
}
}
contract TargetCounter is TelepathyHandler {
uint256 public counter = 0;
event Incremented(address incrementer, uint256 value);
constructor(address _router) TelepathyHandler(_router) {}
// Handle messages being sent and decoding
function handleTelepathyImpl(
uint32 _sourceChainId, address _sourceAddress, bytes memory _msgData
) internal override {
(uint256 amount) = abi.decode(_msgData, (uint256));
counter += amount;
emit Incremented(_sourceAddress, counter);
}
}Unit Testing
Last updated