Skip to content

Commit

Permalink
Merge pull request #120 from sygmaprotocol/viatrix/fee-handler-substrate
Browse files Browse the repository at this point in the history
feat: add fee handler for substrate
  • Loading branch information
mpetrun5 authored Feb 20, 2023
2 parents 90b209c + f8e341a commit 97bcba1
Show file tree
Hide file tree
Showing 18 changed files with 1,175 additions and 240 deletions.
96 changes: 96 additions & 0 deletions contracts/handlers/fee/DynamicERC20FeeHandlerEVM.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
// The Licensed Work is (c) 2022 Sygma
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;

import "./DynamicFeeHandler.sol";

/**
@title Handles deposit fees on Substrate based on Effective rates provided by Fee oracle.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract DynamicERC20FeeHandlerEVM is DynamicFeeHandler {

/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param feeHandlerRouterAddress Contract address of previously deployed FeeHandlerRouter.
*/
constructor(address bridgeAddress, address feeHandlerRouterAddress) DynamicFeeHandler(bridgeAddress, feeHandlerRouterAddress) {
}

/**
@notice Calculates fee for deposit for Substrate.
This function is almost identical to the _calculateFee function in the base contract.
The differences are: unpacking of the oracle message and the txCost calculation formula.
Oracle will do the calculation of the tx cost and provide the resulting fee to the contract.
The resulting calculation is:
txCost = finalFee * oracleMessage.ter / 1e18
@param sender Sender of the deposit.
@param fromDomainID ID of the source chain.
@param destinationDomainID ID of chain deposit will be bridged to.
@param resourceID ResourceID to be used when making deposits.
@param depositData Additional data about the deposit.
@param feeData Additional data to be passed to the fee handler.
@return fee Returns the fee amount.
@return tokenAddress Returns the address of the token to be used for fee.
*/
function _calculateFee(address sender, uint8 fromDomainID, uint8 destinationDomainID, bytes32 resourceID, bytes calldata depositData, bytes calldata feeData) internal view override returns(uint256 fee, address tokenAddress) {
/**
Message:
ber * 10^18: uint256 (not used)
ter * 10^18: uint256
dstGasPrice: uint256
expiresAt: uint256
fromDomainID: uint8 encoded as uint256
toDomainID: uint8 encoded as uint256
resourceID: bytes32
msgGasLimit: uint256 (not used)
sig: bytes(65 bytes)
total in bytes:
message:
32 * 8 = 256
message + sig:
256 + 65 = 321
amount: uint256 (not used)
total: 353
*/

require(feeData.length == 353, "Incorrect feeData length");

FeeDataType memory feeDataDecoded;
uint256 txCost;

feeDataDecoded.message = bytes(feeData[: 256]);
feeDataDecoded.sig = bytes(feeData[256: 321]);

OracleMessageType memory oracleMessage = abi.decode(feeDataDecoded.message, (OracleMessageType));
require(block.timestamp <= oracleMessage.expiresAt, "Obsolete oracle data");
require((oracleMessage.fromDomainID == fromDomainID)
&& (oracleMessage.toDomainID == destinationDomainID)
&& (oracleMessage.resourceID == resourceID),
"Incorrect deposit params"
);

bytes32 messageHash = keccak256(feeDataDecoded.message);

verifySig(messageHash, feeDataDecoded.sig, _oracleAddress);

address tokenHandler = IBridge(_bridgeAddress)._resourceIDToHandlerAddress(resourceID);
tokenAddress = IERCHandler(tokenHandler)._resourceIDToTokenContractAddress(resourceID);

// txCost = dstGasPrice * _gasUsed * Token Effective Rate (rate of dest base currency to token)
txCost = oracleMessage.dstGasPrice * _gasUsed * oracleMessage.ter / 1e18;

uint256 depositAmount;
(depositAmount) = abi.decode(depositData, (uint256));

fee = depositAmount * _feePercent / 1e4; // 100 for percent and 100 to avoid precision loss

if (fee < txCost) {
fee = txCost;
}
return (fee, tokenAddress);
}
}
109 changes: 109 additions & 0 deletions contracts/handlers/fee/DynamicERC20FeeHandlerSubstrate.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
// The Licensed Work is (c) 2022 Sygma
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.11;

import "./DynamicFeeHandler.sol";

/**
@title Handles deposit fees on Substrate based on Effective rates provided by Fee oracle.
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract DynamicERC20FeeHandlerSubstrate is DynamicFeeHandler {

struct SubstrateOracleMessageType {
// Base Effective Rate - effective rate between base currencies of source and dest networks (eg. MATIC/ETH)
uint256 ber;
// Token Effective Rate - rate between base currency of destination network and token that is being trasferred (eg. MATIC/USDT)
uint256 ter;
// Final fee - resulting fee calculated by the oracle
uint256 finalFee;
uint256 expiresAt;
uint8 fromDomainID;
uint8 toDomainID;
bytes32 resourceID;
uint256 msgGasLimit;
}

/**
@param bridgeAddress Contract address of previously deployed Bridge.
@param feeHandlerRouterAddress Contract address of previously deployed FeeHandlerRouter.
*/
constructor(address bridgeAddress, address feeHandlerRouterAddress) DynamicFeeHandler(bridgeAddress, feeHandlerRouterAddress) {
}

/**
@notice Calculates fee for deposit for Substrate.
This function is almost identical to the _calculateFee function in the base contract.
The differences are: unpacking of the oracle message and the txCost calculation formula.
Oracle will do the calculation of the tx cost and provide the resulting fee to the contract.
The resulting calculation is:
txCost = finalFee * oracleMessage.ter / 1e18
@param sender Sender of the deposit.
@param fromDomainID ID of the source chain.
@param destinationDomainID ID of chain deposit will be bridged to.
@param resourceID ResourceID to be used when making deposits.
@param depositData Additional data about the deposit.
@param feeData Additional data to be passed to the fee handler.
@return fee Returns the fee amount.
@return tokenAddress Returns the address of the token to be used for fee.
*/
function _calculateFee(address sender, uint8 fromDomainID, uint8 destinationDomainID, bytes32 resourceID, bytes calldata depositData, bytes calldata feeData) internal view override returns(uint256 fee, address tokenAddress) {
/**
Message:
ber * 10^18: uint256 (not used)
ter * 10^18: uint256
finalFee: uint256
expiresAt: uint256
fromDomainID: uint8 encoded as uint256
toDomainID: uint8 encoded as uint256
resourceID: bytes32
msgGasLimit: uint256 (not used)
sig: bytes(65 bytes)
total in bytes:
message:
32 * 8 = 256
message + sig:
256 + 65 = 321
amount: uint256 (not used)
total: 353
*/

require(feeData.length == 353, "Incorrect feeData length");

FeeDataType memory feeDataDecoded;
uint256 txCost;

feeDataDecoded.message = bytes(feeData[: 256]);
feeDataDecoded.sig = bytes(feeData[256: 321]);

SubstrateOracleMessageType memory oracleMessage = abi.decode(feeDataDecoded.message, (SubstrateOracleMessageType));
require(block.timestamp <= oracleMessage.expiresAt, "Obsolete oracle data");
require((oracleMessage.fromDomainID == fromDomainID)
&& (oracleMessage.toDomainID == destinationDomainID)
&& (oracleMessage.resourceID == resourceID),
"Incorrect deposit params"
);

bytes32 messageHash = keccak256(feeDataDecoded.message);

verifySig(messageHash, feeDataDecoded.sig, _oracleAddress);

address tokenHandler = IBridge(_bridgeAddress)._resourceIDToHandlerAddress(resourceID);
tokenAddress = IERCHandler(tokenHandler)._resourceIDToTokenContractAddress(resourceID);

txCost = oracleMessage.finalFee * oracleMessage.ter / 1e18;

uint256 depositAmount;
(depositAmount) = abi.decode(depositData, (uint256));

fee = depositAmount * _feePercent / 1e4; // 100 for percent and 100 to avoid precision loss

if (fee < txCost) {
fee = txCost;
}
return (fee, tokenAddress);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
@author ChainSafe Systems.
@notice This contract is intended to be used with the Bridge contract.
*/
contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
abstract contract DynamicFeeHandler is IFeeHandler, AccessControl, ERC20Safe {
address public immutable _bridgeAddress;
address public immutable _feeHandlerRouterAddress;

Expand All @@ -40,7 +40,7 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
struct FeeDataType {
bytes message;
bytes sig;
uint256 amount;
uint256 amount; // not used
}

modifier onlyAdmin() {
Expand All @@ -64,7 +64,7 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
@param bridgeAddress Contract address of previously deployed Bridge.
@param feeHandlerRouterAddress Contract address of previously deployed FeeHandlerRouter.
*/
constructor(address bridgeAddress, address feeHandlerRouterAddress) public {
constructor(address bridgeAddress, address feeHandlerRouterAddress) {
_bridgeAddress = bridgeAddress;
_feeHandlerRouterAddress = feeHandlerRouterAddress;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
Expand Down Expand Up @@ -95,7 +95,8 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
/**
@notice Sets the fee properties.
@param gasUsed Gas used for transfer.
@param feePercent Added to fee amount. total fee = fee_from_oracle.amount * feePercent / 1e4
@param feePercent Percent of deposited amount taken as a fee.
fee = depositAmount * feePercent / 1e4
*/
function setFeeProperties(uint32 gasUsed, uint16 feePercent) external onlyAdmin {
_gasUsed = gasUsed;
Expand All @@ -108,7 +109,7 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
@param fromDomainID ID of the source chain.
@param destinationDomainID ID of chain deposit will be bridged to.
@param resourceID ResourceID to be used when making deposits.
@param depositData Additional data to be passed to specified handler.
@param depositData Additional data about the deposit.
@param feeData Additional data to be passed to the fee handler.
*/
function collectFee(address sender, uint8 fromDomainID, uint8 destinationDomainID, bytes32 resourceID, bytes calldata depositData, bytes calldata feeData) payable external onlyBridgeOrRouter {
Expand All @@ -124,7 +125,7 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
@param fromDomainID ID of the source chain.
@param destinationDomainID ID of chain deposit will be bridged to.
@param resourceID ResourceID to be used when making deposits.
@param depositData Additional data to be passed to specified handler.
@param depositData Additional data about the deposit.
@param feeData Additional data to be passed to the fee handler.
@return fee Returns the fee amount.
@return tokenAddress Returns the address of the token to be used for fee.
Expand All @@ -133,67 +134,7 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
return _calculateFee(sender, fromDomainID, destinationDomainID, resourceID, depositData, feeData);
}

function _calculateFee(address sender, uint8 fromDomainID, uint8 destinationDomainID, bytes32 resourceID, bytes calldata depositData, bytes calldata feeData) internal view returns(uint256 fee, address tokenAddress) {
/**
Message:
ber * 10^18: uint256
ter * 10^18: uint256
dstGasPrice: uint256
expiresAt: uint256
fromDomainID: uint8 encoded as uint256
toDomainID: uint8 encoded as uint256
resourceID: bytes32
msgGasLimit: uint256
sig: bytes(65 bytes)
total in bytes:
message:
32 * 8 = 256
message + sig:
256 + 65 = 321
amount: uint256
total: 353
*/

require(feeData.length == 353, "Incorrect feeData length");

FeeDataType memory feeDataDecoded;
uint256 txCost;

feeDataDecoded.message = bytes(feeData[: 256]);
feeDataDecoded.sig = bytes(feeData[256: 321]);
feeDataDecoded.amount = abi.decode(feeData[321:], (uint256));

OracleMessageType memory oracleMessage = abi.decode(feeDataDecoded.message, (OracleMessageType));
require(block.timestamp <= oracleMessage.expiresAt, "Obsolete oracle data");
require((oracleMessage.fromDomainID == fromDomainID)
&& (oracleMessage.toDomainID == destinationDomainID)
&& (oracleMessage.resourceID == resourceID),
"Incorrect deposit params"
);

bytes32 messageHash = keccak256(feeDataDecoded.message);

verifySig(messageHash, feeDataDecoded.sig, _oracleAddress);

address tokenHandler = IBridge(_bridgeAddress)._resourceIDToHandlerAddress(resourceID);
address tokenAddress = IERCHandler(tokenHandler)._resourceIDToTokenContractAddress(resourceID);

if(oracleMessage.msgGasLimit > 0) {
// txCost = dstGasPrice * oracleMessage.msgGasLimit * Base Effective Rate (rate between base currencies of source and dest)
txCost = oracleMessage.dstGasPrice * oracleMessage.msgGasLimit * oracleMessage.ber / 1e18;
} else {
// txCost = dstGasPrice * _gasUsed * Token Effective Rate (rate of dest base currency to token)
txCost = oracleMessage.dstGasPrice * _gasUsed * oracleMessage.ter / 1e18;
}

fee = feeDataDecoded.amount * _feePercent / 1e4; // 100 for percent and 100 to avoid precision loss

if (fee < txCost) {
fee = txCost;
}
return (fee, tokenAddress);
function _calculateFee(address sender, uint8 fromDomainID, uint8 destinationDomainID, bytes32 resourceID, bytes calldata depositData, bytes calldata feeData) internal view virtual returns(uint256 fee, address tokenAddress) {
}

/**
Expand All @@ -213,7 +154,7 @@ contract FeeHandlerWithOracle is IFeeHandler, AccessControl, ERC20Safe {
}
}

function verifySig(bytes32 message, bytes memory signature, address signerAddress) internal view {
function verifySig(bytes32 message, bytes memory signature, address signerAddress) internal pure {
address signerAddressRecovered = ECDSA.recover(message, signature);
require(signerAddressRecovered == signerAddress, 'Invalid signature');
}
Expand Down
Loading

0 comments on commit 97bcba1

Please sign in to comment.