Skip to content
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

feat: add optional call to ERC20Handler and NativeTokenHandler execute #266

Merged
merged 17 commits into from
Sep 20, 2024
Merged
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,6 @@ to ensure a statement and patch release is made in a timely manner.

Please email us a description of the flaw and any related information (e.g. reproduction steps, version) to
[[email protected]](mailto:[email protected]).

## Audits
You can find audit reports inside [`/audits`](./audits/)
Binary file added audits/veridise-24-08-2024.pdf
Binary file not shown.
69 changes: 53 additions & 16 deletions contracts/adapters/nativeTokens/NativeTokenAdapter.sol
Original file line number Diff line number Diff line change
@@ -1,44 +1,76 @@
// SPDX-License-Identifier: BUSL-1.1
pragma solidity ^0.8.11;

import "@openzeppelin/contracts/access/AccessControl.sol";
import "../../interfaces/IBridge.sol";
import "../../interfaces/IFeeHandler.sol";


contract NativeTokenAdapter is AccessControl {
contract NativeTokenAdapter {
IBridge public immutable _bridge;
bytes32 public immutable _resourceID;

event Withdrawal(address recipient, uint amount);

error SenderNotAdmin();
error InsufficientMsgValueAmount(uint256 amount);
error MsgValueLowerThanFee(uint256 amount);
error TokenWithdrawalFailed();
error InsufficientBalance();
error FailedFundsTransfer();

modifier onlyAdmin() {
if (!hasRole(DEFAULT_ADMIN_ROLE, msg.sender)) revert SenderNotAdmin();
_;
}
error ZeroGas();

constructor(address bridge, bytes32 resourceID) {
_bridge = IBridge(bridge);
_resourceID = resourceID;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}

function deposit(uint8 destinationDomainID, string calldata recipientAddress) external payable {
if (msg.value <= 0) revert InsufficientMsgValueAmount(msg.value);
bytes memory depositData = abi.encodePacked(
uint256(bytes(recipientAddress).length),
recipientAddress
);
depositGeneral(destinationDomainID, depositData);
}

function depositToEVM(uint8 destinationDomainID, address recipient) external payable {
bytes memory depositData = abi.encodePacked(
uint256(20),
recipient
);
depositGeneral(destinationDomainID, depositData);
}

/**
@notice Makes a native token deposit with an included message.
@param destinationDomainID ID of destination chain.
@param recipient The destination chain contract address that implements the ISygmaMessageReceiver interface.
If the recipient is set to zero address then it will be replaced on the destination with
the address of the DefaultMessageReceiver which is a generic ISygmaMessageReceiver implementation.
@param gas The amount of gas needed to successfully execute the call to recipient on the destination. Fee amount is
directly affected by this value.
@param message Arbitrary encoded bytes array that will be passed as the third argument in the
ISygmaMessageReceiver(recipient).handleSygmaMessage(_, _, message) call. If you intend to use the
DefaultMessageReceiver, make sure to encode the message to comply with the
DefaultMessageReceiver.handleSygmaMessage() message decoding implementation.
*/
function depositToEVMWithMessage(uint8 destinationDomainID, address recipient, uint256 gas, bytes calldata message) external payable {
MakMuftic marked this conversation as resolved.
Show resolved Hide resolved
if (gas == 0) revert ZeroGas();
bytes memory depositData = abi.encodePacked(
uint256(20),
recipient,
gas,
uint256(message.length),
message
);
depositGeneral(destinationDomainID, depositData);
}

function depositGeneral(uint8 destinationDomainID, bytes memory depositDataAfterAmount) public payable {
if (msg.value == 0) revert InsufficientMsgValueAmount(msg.value);
address feeHandlerRouter = _bridge._feeHandler();
(uint256 fee, ) = IFeeHandler(feeHandlerRouter).calculateFee(
address(this),
_bridge._domainID(),
destinationDomainID,
_resourceID,
"", // depositData - not parsed
abi.encodePacked(msg.value, depositDataAfterAmount),
"" // feeData - not parsed
);

Expand All @@ -47,16 +79,21 @@ contract NativeTokenAdapter is AccessControl {

bytes memory depositData = abi.encodePacked(
transferAmount,
bytes(recipientAddress).length,
recipientAddress
depositDataAfterAmount
);

_bridge.deposit{value: fee}(destinationDomainID, _resourceID, depositData, "");

address nativeHandlerAddress = _bridge._resourceIDToHandlerAddress(_resourceID);
(bool success, ) = nativeHandlerAddress.call{value: transferAmount}("");
if(!success) revert FailedFundsTransfer();
if (!success) revert FailedFundsTransfer();
uint256 leftover = address(this).balance;
if (leftover > 0) {
(success, ) = payable(msg.sender).call{value: leftover}("");
// Do not revert if sender does not want to receive.
}
}

// For an unlikely case when part of the fee is returned.
receive() external payable {}
}
220 changes: 220 additions & 0 deletions contracts/handlers/DefaultMessageReceiver.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,220 @@
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;

import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC721/utils/ERC721Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "../utils/AccessControl.sol";
import "../interfaces/ISygmaMessageReceiver.sol";

contract DefaultMessageReceiver is ISygmaMessageReceiver, AccessControl, ERC721Holder, ERC1155Holder {
bytes32 public constant SYGMA_HANDLER_ROLE = keccak256("SYGMA_HANDLER_ROLE");

address internal constant zeroAddress = address(0);

uint256 public immutable _recoverGas;

struct Action {
uint256 nativeValue;
address callTo;
address approveTo;
address tokenSend;
address tokenReceive;
bytes data;
}

error InsufficientGasLimit();
error InvalidContract();
error InsufficientPermission();
error ActionFailed();
error InsufficientNativeBalance();
error ReturnNativeLeftOverFailed();

event Executed(
bytes32 transactionId,
address tokenSend,
address receiver,
uint256 amount
);

event TransferRecovered(
bytes32 transactionId,
address tokenSend,
address receiver,
uint256 amount
);

/// Constructor ///

/// @param sygmaHandlers The contract addresses with access to message processing.
/// @param recoverGas The amount of gas needed to forward the original amount to receiver.
constructor(address[] memory sygmaHandlers, uint256 recoverGas) {
_recoverGas = recoverGas;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
for (uint i = 0; i < sygmaHandlers.length; i++) {
_setupRole(SYGMA_HANDLER_ROLE, sygmaHandlers[i]);
}
}

/**
@notice Users have to understand the design and limitations behind the Actions processing.
The contract will try to return all the leftover tokens and native token to the
receiver address. This logic is applied to the native token if there was a balance
increase during the message processing, then to the tokenSent which is received from
Sygma proposal and finally to every Action.tokenReceive. In the vast majority of
cases that would be enough, though user can come up with a scenario where an Action
produces results in a receival of more than one token, while only one could be
specified in this particular Action.tokenReceive property. In such a case it is
a users responsibility to either send it all with a transferBalanceAction() Action or to
include an extra action[s] with tokenReceive set to each of the tokens received.
*/
function handleSygmaMessage(
address tokenSent,
uint256 amount,
bytes memory message
) external payable override {
if (!hasRole(SYGMA_HANDLER_ROLE, _msgSender())) revert InsufficientPermission();
(
bytes32 transactionId,
Action[] memory actions,
address receiver
) = abi.decode(message, (bytes32, Action[], address));

_execute(transactionId, actions, tokenSent, payable(receiver), amount);
}

function _execute(
bytes32 transactionId,
Action[] memory actions,
address tokenSent,
address payable receiver,
uint256 amount
) internal {
uint256 cacheGasLeft = gasleft();
if (cacheGasLeft < _recoverGas) revert InsufficientGasLimit();

uint256 startingNativeBalance = address(this).balance - msg.value;
/// We are wrapping the Actions processing in new call in order to be
/// able to recover, ie. send funds to the receiver, in case of fail or
/// running out of gas. Otherwise we can only revert whole execution
/// which would result in the need to manually process proposal resolution
/// to unstuck the assets.
try this.performActions{gas: cacheGasLeft - _recoverGas}(
tokenSent,
receiver,
startingNativeBalance,
actions
) {
emit Executed(
transactionId,
tokenSent,
receiver,
amount
);
} catch {
cacheGasLeft = gasleft();
if (cacheGasLeft < _recoverGas) revert InsufficientGasLimit();
transferBalance(tokenSent, receiver);
if (address(this).balance > startingNativeBalance) {
transferNativeBalance(receiver);
}

emit TransferRecovered(
transactionId,
tokenSent,
receiver,
amount
);
}
}

/// @dev See the comment inside of the _execute() function.
function performActions(
address tokenSent,
address payable receiver,
uint256 startingNativeBalance,
Action[] memory actions
) external {
MakMuftic marked this conversation as resolved.
Show resolved Hide resolved
if (msg.sender != address(this)) revert InsufficientPermission();

uint256 numActions = actions.length;
for (uint256 i = 0; i < numActions; i++) {
// Allow EOA if the data is empty. Could be used to send native currency.
if (!isContract(actions[i].callTo) && actions[i].data.length > 0) revert InvalidContract();
uint256 nativeValue = actions[i].nativeValue;
if (nativeValue > 0 && address(this).balance < nativeValue) {
revert InsufficientNativeBalance();
}
approveERC20(IERC20(actions[i].tokenSend), actions[i].approveTo, type(uint256).max);

(bool success, ) = actions[i].callTo.call{value: nativeValue}(actions[i].data);
if (!success) {
revert ActionFailed();
}
}
if (address(this).balance > startingNativeBalance) {
transferNativeBalance(receiver);
}
transferBalance(tokenSent, receiver);
returnLeftOvers(actions, receiver);
}

function returnLeftOvers(Action[] memory actions, address payable receiver) internal {
for (uint256 i; i < actions.length; i++) {
transferBalance(actions[i].tokenReceive, receiver);
approveERC20(IERC20(actions[i].tokenSend), actions[i].approveTo, 0);
}
}

function transferNativeBalance(address payable receiver) internal {
(bool success, ) = receiver.call{value: address(this).balance}("");
if (!success) {
revert ReturnNativeLeftOverFailed();
}
}

function transferBalance(address token, address receiver) internal {
if (token != zeroAddress) {
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
if (tokenBalance > 0) {
SafeERC20.safeTransfer(IERC20(token), receiver, tokenBalance);
}
}
}

/// @notice Helper function that could be used as an Action to itself to transfer whole
/// @notice balance of a particular token.
function transferBalanceAction(address token, address receiver) external {
if (msg.sender != address(this)) revert InsufficientPermission();
if (token != zeroAddress) {
transferBalance(token, receiver);
} else {
transferNativeBalance(payable(receiver));
}
}

function isContract(address contractAddr) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(contractAddr)
}
return size > 0;
}

function approveERC20(
IERC20 token,
address spender,
uint256 amount
) internal {
if (address(token) != zeroAddress && spender != zeroAddress) {
// Ad-hoc SafeERC20.forceApprove() because OZ lib from dependencies does not have one yet.
(bool success, ) = address(token).call(abi.encodeWithSelector(token.approve.selector, spender, 0));
if (amount > 0) {
(success, ) = address(token).call(abi.encodeWithSelector(token.approve.selector, spender, amount));
}
}
}

receive() external payable {}
}
Loading
Loading