Skip to content

Wormhole adaptor #94

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 9 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,6 @@
path = lib/zk-email-verify
branch = v6.3.2
url = https://github.com/zkemail/zk-email-verify
[submodule "lib/wormhole-solidity-sdk"]
path = lib/wormhole-solidity-sdk
url = https://github.com/wormhole-foundation/wormhole-solidity-sdk
103 changes: 103 additions & 0 deletions contracts/crosschain/wormhole/WormholeGatewayBase.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.27;

import {IWormholeRelayer} from "wormhole-solidity-sdk/interfaces/IWormholeRelayer.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {InteroperableAddress} from "@openzeppelin/contracts/utils/draft-InteroperableAddress.sol";

abstract contract WormholeGatewayBase is Ownable {
using InteroperableAddress for bytes;

IWormholeRelayer internal immutable _wormholeRelayer;
uint16 internal immutable _wormholeChainId;

// Remote gateway.
// `addr` is the isolated address part of ERC-7930. Its not a full ERC-7930 interoperable address.
mapping(bytes2 chainType => mapping(bytes chainReference => bytes32 addr)) private _remoteGateways;

// chain equivalence ERC-7930 (no address) <> Wormhole
mapping(bytes erc7930 => uint24 wormholeId) private _erc7930ToWormhole;
mapping(uint16 wormholeId => bytes erc7930) private _wormholeToErc7930;

/// @dev A remote gateway has been registered for a chain.
event RegisteredRemoteGateway(bytes remote);

/// @dev A chain equivalence has been registered.
event RegisteredChainEquivalence(bytes erc7930binary, uint16 wormholeId);

/// @dev Error emitted when an unsupported chain is queried.
error UnsupportedERC7930Chain(bytes erc7930binary);
error UnsupportedWormholeChain(uint16 wormholeId);
error InvalidChainIdentifier(bytes erc7930binary);
error ChainEquivalenceAlreadyRegistered(bytes erc7930binary, uint16 wormhole);
error RemoteGatewayAlreadyRegistered(bytes2 chainType, bytes chainReference);
error UnauthorizedCaller(address);

modifier onlyWormholeRelayer() {
require(msg.sender == address(_wormholeRelayer), UnauthorizedCaller(msg.sender));
_;
}

constructor(IWormholeRelayer wormholeRelayer, uint16 wormholeChainId) {
_wormholeRelayer = wormholeRelayer;
_wormholeChainId = wormholeChainId;
}

function relayer() public view virtual returns (address) {
return address(_wormholeRelayer);
}

function supportedChain(bytes memory chain) public view virtual returns (bool) {
(bytes2 chainType, bytes memory chainReference, ) = chain.parseV1();
return _erc7930ToWormhole[InteroperableAddress.formatV1(chainType, chainReference, "")] & (1 << 16) != 0;
}

function getWormholeChain(bytes memory chain) public view virtual returns (uint16) {
(bytes2 chainType, bytes memory chainReference, ) = chain.parseV1();
uint24 wormholeId = _erc7930ToWormhole[InteroperableAddress.formatV1(chainType, chainReference, "")];
require(wormholeId & (1 << 16) != 0, UnsupportedERC7930Chain(chain));
return uint16(wormholeId);
}

function getErc7930Chain(uint16 wormholeId) public view virtual returns (bytes memory output) {
output = _wormholeToErc7930[wormholeId];
require(output.length > 0, UnsupportedWormholeChain(wormholeId));
}

/// @dev Returns the address of the remote gateway for a given chainType and chainReference.
function getRemoteGateway(bytes memory chain) public view virtual returns (bytes32) {
(bytes2 chainType, bytes memory chainReference, ) = chain.parseV1();
return getRemoteGateway(chainType, chainReference);
}

function getRemoteGateway(bytes2 chainType, bytes memory chainReference) public view virtual returns (bytes32) {
bytes32 addr = _remoteGateways[chainType][chainReference];
if (addr == 0) revert UnsupportedERC7930Chain(InteroperableAddress.formatV1(chainType, chainReference, ""));
return addr;
}

function registerChainEquivalence(bytes calldata chain, uint16 wormholeId) public virtual onlyOwner {
(, , bytes calldata addr) = chain.parseV1Calldata();
require(addr.length == 0, InvalidChainIdentifier(chain));
require(
_erc7930ToWormhole[chain] == 0 && _wormholeToErc7930[wormholeId].length == 0,
ChainEquivalenceAlreadyRegistered(chain, wormholeId)
);

_erc7930ToWormhole[chain] = wormholeId | (1 << 16);
_wormholeToErc7930[wormholeId] = chain;
emit RegisteredChainEquivalence(chain, wormholeId);
}

function registerRemoteGateway(bytes calldata remote) public virtual onlyOwner {
(bytes2 chainType, bytes calldata chainReference, bytes calldata addr) = remote.parseV1Calldata();
require(
_remoteGateways[chainType][chainReference] == 0,
RemoteGatewayAlreadyRegistered(chainType, chainReference)
);
require(addr.length <= 32); // TODO: error if that is not an valid universal address
_remoteGateways[chainType][chainReference] = bytes32(addr) >> (256 - 8 * addr.length); // align right
emit RegisteredRemoteGateway(remote);
}
}
54 changes: 54 additions & 0 deletions contracts/crosschain/wormhole/WormholeGatewayDestination.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.27;

import {IWormholeReceiver} from "wormhole-solidity-sdk/interfaces/IWormholeReceiver.sol";
import {BitMaps} from "@openzeppelin/contracts/utils/structs/BitMaps.sol";
import {InteroperableAddress} from "@openzeppelin/contracts/utils/draft-InteroperableAddress.sol";
import {IERC7786Receiver} from "../../interfaces/IERC7786.sol";
import {WormholeGatewayBase} from "./WormholeGatewayBase.sol";

abstract contract WormholeGatewayDestination is WormholeGatewayBase, IWormholeReceiver {
using BitMaps for BitMaps.BitMap;
using InteroperableAddress for bytes;

BitMaps.BitMap private _executed;

error InvalidOriginGateway(uint16 wormholeSourceChain, bytes32 wormholeSourceAddress);
error MessageAlreadyExecuted(bytes32 outboxId);
error ReceiverExecutionFailed();
error AdditionalMessagesNotSupported();

function receiveWormholeMessages(
bytes memory adapterPayload,
bytes[] memory additionalMessages,
bytes32 wormholeSourceAddress,
uint16 wormholeSourceChain,
bytes32 deliveryHash
) public payable virtual onlyWormholeRelayer {
require(additionalMessages.length == 0, AdditionalMessagesNotSupported());

(
bytes32 outboxId,
bytes memory sender,
bytes memory recipient,
bytes memory payload,
bytes[] memory attributes
) = abi.decode(adapterPayload, (bytes32, bytes, bytes, bytes, bytes[]));

// Axelar to ERC-7930 translation
bytes32 addr = getRemoteGateway(getErc7930Chain(wormholeSourceChain));

// check message validity
// - `axelarSourceAddress` is the remote gateway on the origin chain.
require(addr == wormholeSourceAddress, InvalidOriginGateway(wormholeSourceChain, wormholeSourceAddress));

// prevent replay - deliveryHash might not be unique if a message is relayed multiple time
require(!_executed.get(uint256(outboxId)), MessageAlreadyExecuted(outboxId));
_executed.set(uint256(outboxId));

(, address target) = recipient.parseEvmV1();
bytes4 result = IERC7786Receiver(target).executeMessage(deliveryHash, sender, payload, attributes);
require(result == IERC7786Receiver.executeMessage.selector, ReceiverExecutionFailed());
}
}
22 changes: 22 additions & 0 deletions contracts/crosschain/wormhole/WormholeGatewayDuplex.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.27;

import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {WormholeGatewayBase, IWormholeRelayer} from "./WormholeGatewayBase.sol";
import {WormholeGatewayDestination} from "./WormholeGatewayDestination.sol";
import {WormholeGatewaySource} from "./WormholeGatewaySource.sol";

/**
* @dev A contract that combines the functionality of both the source and destination gateway
* adapters for the Wormhole Network. Allowing to either send or receive messages across chains.
*/
// slither-disable-next-line locked-ether
contract WormholeGatewayDuplex is WormholeGatewaySource, WormholeGatewayDestination {
/// @dev Initializes the contract with the Wormhole gateway and the initial owner.
constructor(
IWormholeRelayer wormholeRelayer,
uint16 wormholeChainId,
address initialOwner
) Ownable(initialOwner) WormholeGatewayBase(wormholeRelayer, wormholeChainId) {}
}
114 changes: 114 additions & 0 deletions contracts/crosschain/wormhole/WormholeGatewaySource.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.27;

import {VaaKey} from "wormhole-solidity-sdk/interfaces/IWormholeRelayer.sol";
import {toUniversalAddress, fromUniversalAddress} from "wormhole-solidity-sdk/utils/UniversalAddress.sol";
import {InteroperableAddress} from "@openzeppelin/contracts/utils/draft-InteroperableAddress.sol";
import {Strings} from "@openzeppelin/contracts/utils/Strings.sol";
import {WormholeGatewayBase} from "./WormholeGatewayBase.sol";
import {IERC7786GatewaySource} from "../../interfaces/IERC7786.sol";

// TODO: allow non-evm destination chains via non-evm-specific finalize/retry variants
abstract contract WormholeGatewaySource is IERC7786GatewaySource, WormholeGatewayBase {
using InteroperableAddress for bytes;
// using Strings for *;

struct PendingMessage {
uint64 sequence;
address sender;
bytes recipient;
bytes payload;
bytes[] attributes;
}

uint256 private _sendId;
mapping(bytes32 => PendingMessage) private _pending;

event MessagePushed(bytes32 outboxId);
error CannotFinalizeMessage(bytes32 outboxId);
error CannotRetryMessage(bytes32 outboxId);
error UnsupportedNativeTransfer();

/// @inheritdoc IERC7786GatewaySource
function supportsAttribute(bytes4 /*selector*/) public pure returns (bool) {
return false;
}

/// @inheritdoc IERC7786GatewaySource
function sendMessage(
bytes calldata recipient, // Binary Interoperable Address
bytes calldata payload,
bytes[] calldata attributes
) external payable returns (bytes32 sendId) {
require(msg.value == 0, UnsupportedNativeTransfer());
// Use of `if () revert` syntax to avoid accessing attributes[0] if it's empty
if (attributes.length > 0)
revert UnsupportedAttribute(attributes[0].length < 0x04 ? bytes4(0) : bytes4(attributes[0][0:4]));

require(supportedChain(recipient), UnsupportedERC7930Chain(recipient));

sendId = bytes32(++_sendId);
_pending[sendId] = PendingMessage(0, msg.sender, recipient, payload, attributes);

emit MessageSent(
sendId,
InteroperableAddress.formatEvmV1(block.chainid, msg.sender),
recipient,
payload,
0,
attributes
);
}

function quoteEvmMessage(bytes memory destinationChain, uint256 gasLimit) public view returns (uint256) {
(uint256 cost, ) = _wormholeRelayer.quoteEVMDeliveryPrice(getWormholeChain(destinationChain), 0, gasLimit);
return cost;
}

function quoteEvmMessage(bytes32 outboxId, uint256 gasLimit) external view returns (uint256) {
return quoteEvmMessage(_pending[outboxId].recipient, gasLimit);
}

function finalizeEvmMessage(bytes32 outboxId, uint256 gasLimit) external payable {
PendingMessage storage pmsg = _pending[outboxId];

require(pmsg.sender != address(0), CannotFinalizeMessage(outboxId));

bytes memory adapterPayload = abi.encode(
outboxId,
InteroperableAddress.formatEvmV1(block.chainid, pmsg.sender),
pmsg.recipient,
pmsg.payload,
pmsg.attributes
);

// TODO: potentially delete part/all of the message

pmsg.sequence = _wormholeRelayer.sendPayloadToEvm{value: msg.value}(
getWormholeChain(pmsg.recipient),
fromUniversalAddress(getRemoteGateway(pmsg.recipient)),
adapterPayload,
0,
gasLimit
);

emit MessagePushed(outboxId);
}

// Is this necessary ? How does that work since we are not providing any additional payment ?
// Is re-calling finalizeEvmMessage an alternative ?
function retryEvmMessage(bytes32 outboxId, uint256 gasLimit, address newDeliveryProvider) external {
PendingMessage storage pmsg = _pending[outboxId];

require(pmsg.sequence != 0, CannotRetryMessage(outboxId));

pmsg.sequence = _wormholeRelayer.resendToEvm(
VaaKey(_wormholeChainId, toUniversalAddress(address(this)), pmsg.sequence),
getWormholeChain(pmsg.recipient),
0,
gasLimit,
newDeliveryProvider
);
}
}
32 changes: 32 additions & 0 deletions contracts/mocks/crosschain/wormhole/WormholeRelayerMock.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// SPDX-License-Identifier: MIT

pragma solidity ^0.8.27;

import {IWormholeRelayer} from "wormhole-solidity-sdk/interfaces/IWormholeRelayer.sol";
import {IWormholeReceiver} from "wormhole-solidity-sdk/interfaces/IWormholeReceiver.sol";
import {toUniversalAddress} from "wormhole-solidity-sdk/utils/UniversalAddress.sol";

contract WormholeRelayerMock {
uint64 private _seq;

function sendPayloadToEvm(
uint16 targetChain,
address targetAddress,
bytes memory payload,
uint256 receiverValue,
uint256 gasLimit
) external payable returns (uint64) {
// TODO: check that destination chain is local

uint64 seq = _seq++;
IWormholeReceiver(targetAddress).receiveWormholeMessages{value: receiverValue, gas: gasLimit}(
payload,
new bytes[](0),
toUniversalAddress(msg.sender),
targetChain,
keccak256(abi.encode(seq))
);

return seq;
}
}
1 change: 1 addition & 0 deletions lib/wormhole-solidity-sdk
Submodule wormhole-solidity-sdk added at 575181
1 change: 1 addition & 0 deletions remappings.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@
@axelar-network/axelar-gmp-sdk-solidity/=lib/axelar-gmp-sdk-solidity/
@zk-email/email-tx-builder/=lib/email-tx-builder/packages/contracts/
@zk-email/contracts/=lib/zk-email-verify/packages/contracts/
wormhole-solidity-sdk/=lib/wormhole-solidity-sdk/src/
Loading