Skip to content

Commit

Permalink
support tokens with transfer fees
Browse files Browse the repository at this point in the history
Change-Id: Ib6ef2f1680ac845ef0f05c51047846c2633b0d4b
  • Loading branch information
valentin authored and Leopold Schabel committed Oct 29, 2021
1 parent 7415fda commit 1226f85
Show file tree
Hide file tree
Showing 6 changed files with 739 additions and 36 deletions.
87 changes: 52 additions & 35 deletions ethereum/contracts/bridge/Bridge.sol
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ contract Bridge is BridgeGovernance {
bytes32 symbol;
bytes32 name;
assembly {
// first 32 bytes hold string length
// first 32 bytes hold string length
symbol := mload(add(symbolString, 32))
name := mload(add(nameString, 32))
}
Expand All @@ -56,7 +56,7 @@ contract Bridge is BridgeGovernance {
bytes memory encoded = encodeAssetMeta(meta);

sequence = wormhole().publishMessage{
value : msg.value
value : msg.value
}(nonce, encoded, 15);
}

Expand All @@ -69,18 +69,18 @@ contract Bridge is BridgeGovernance {

require(arbiterFee <= amount, "fee is bigger than amount minus wormhole fee");

uint normalizedAmount = amount / (10 ** 10);
uint normalizedArbiterFee = arbiterFee / (10 ** 10);
uint normalizedAmount = normalizeAmount(amount, 18);
uint normalizedArbiterFee = normalizeAmount(arbiterFee, 18);

// refund dust
uint dust = amount - (normalizedAmount * (10 ** 10));
uint dust = amount - deNormalizeAmount(normalizedAmount, 18);
if (dust > 0) {
payable(msg.sender).transfer(dust);
}

// deposit into WETH
WETH().deposit{
value : amount - dust
value : amount - dust
}();

// track and check outstanding token amounts
Expand All @@ -106,50 +106,72 @@ contract Bridge is BridgeGovernance {
(,bytes memory queriedDecimals) = token.staticcall(abi.encodeWithSignature("decimals()"));
uint8 decimals = abi.decode(queriedDecimals, (uint8));

// adjust decimals
uint256 normalizedAmount = amount;
uint256 normalizedArbiterFee = arbiterFee;
if (decimals > 8) {
uint multiplier = 10 ** (decimals - 8);

normalizedAmount /= multiplier;
normalizedArbiterFee /= multiplier;

// don't deposit dust that can not be bridged due to the decimal shift
amount = normalizedAmount * multiplier;
}
// don't deposit dust that can not be bridged due to the decimal shift
amount = deNormalizeAmount(normalizeAmount(amount, decimals), decimals);

if (tokenChain == chainId()) {
// query own token balance before transfer
(,bytes memory queriedBalanceBefore) = token.staticcall(abi.encodeWithSelector(IERC20.balanceOf.selector, address(this)));
uint256 balanceBefore = abi.decode(queriedBalanceBefore, (uint256));

// transfer tokens
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);

// track and check outstanding token amounts
bridgeOut(token, normalizedAmount);
// query own token balance after transfer
(,bytes memory queriedBalanceAfter) = token.staticcall(abi.encodeWithSelector(IERC20.balanceOf.selector, address(this)));
uint256 balanceAfter = abi.decode(queriedBalanceAfter, (uint256));

// correct amount for potential transfer fees
amount = balanceAfter - balanceBefore;
} else {
SafeERC20.safeTransferFrom(IERC20(token), msg.sender, address(this), amount);

TokenImplementation(token).burn(address(this), amount);
}

// normalize amounts decimals
uint256 normalizedAmount = normalizeAmount(amount, decimals);
uint256 normalizedArbiterFee = normalizeAmount(arbiterFee, decimals);

// track and check outstanding token amounts
if (tokenChain == chainId()) {
bridgeOut(token, normalizedAmount);
}

sequence = logTransfer(tokenChain, tokenAddress, normalizedAmount, recipientChain, recipient, normalizedArbiterFee, msg.value, nonce);
}

function normalizeAmount(uint256 amount, uint8 decimals) internal pure returns(uint256){
if (decimals > 8) {
amount /= 10 ** (decimals - 8);
}
return amount;
}

function deNormalizeAmount(uint256 amount, uint8 decimals) internal pure returns(uint256){
if (decimals > 8) {
amount *= 10 ** (decimals - 8);
}
return amount;
}

function logTransfer(uint16 tokenChain, bytes32 tokenAddress, uint256 amount, uint16 recipientChain, bytes32 recipient, uint256 fee, uint256 callValue, uint32 nonce) internal returns (uint64 sequence) {
require(fee <= amount, "fee exceeds amount");

BridgeStructs.Transfer memory transfer = BridgeStructs.Transfer({
payloadID : 1,
amount : amount,
tokenAddress : tokenAddress,
tokenChain : tokenChain,
to : recipient,
toChain : recipientChain,
fee : fee
payloadID : 1,
amount : amount,
tokenAddress : tokenAddress,
tokenChain : tokenChain,
to : recipient,
toChain : recipientChain,
fee : fee
});

bytes memory encoded = encodeTransfer(transfer);

sequence = wormhole().publishMessage{
value : callValue
value : callValue
}(nonce, encoded, 15);
}

Expand Down Expand Up @@ -263,13 +285,8 @@ contract Bridge is BridgeGovernance {
uint8 decimals = abi.decode(queriedDecimals, (uint8));

// adjust decimals
uint256 nativeAmount = transfer.amount;
uint256 nativeFee = transfer.fee;
if (decimals > 8) {
uint multiplier = 10 ** (decimals - 8);
nativeAmount *= multiplier;
nativeFee *= multiplier;
}
uint256 nativeAmount = deNormalizeAmount(transfer.amount, decimals);
uint256 nativeFee = deNormalizeAmount(transfer.fee, decimals);

// transfer fee to arbiter
if (nativeFee > 0) {
Expand Down
4 changes: 4 additions & 0 deletions ethereum/contracts/bridge/BridgeImplementation.sol
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ contract BridgeImplementation is Bridge {
return tokenImplementation();
}

function initialize() initializer public virtual {
// this function needs to be exposed for an upgrade to pass
}

modifier initializer() {
address impl = ERC1967Upgrade._getImplementation();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pragma solidity ^0.8.0;
import "../BridgeImplementation.sol";

contract MockBridgeImplementation is BridgeImplementation {
function initialize() initializer public {
function initialize() initializer public override {
// this function needs to be exposed for an upgrade to pass
}

Expand Down
177 changes: 177 additions & 0 deletions ethereum/contracts/bridge/mock/MockFeeToken.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
// contracts/TokenImplementation.sol
// SPDX-License-Identifier: Apache 2

pragma solidity ^0.8.0;

import "../token/TokenState.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import "@openzeppelin/contracts/proxy/beacon/BeaconProxy.sol";

// Based on the OpenZepplin ERC20 implementation, licensed under MIT
contract FeeToken is TokenState, Context {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);

function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
uint64 sequence_,

address owner_,

uint16 chainId_,
bytes32 nativeContract_
) initializer public {
_state.name = name_;
_state.symbol = symbol_;
_state.decimals = decimals_;
_state.metaLastUpdatedSequence = sequence_;

_state.owner = owner_;

_state.chainId = chainId_;
_state.nativeContract = nativeContract_;
}

function name() public view returns (string memory) {
return string(abi.encodePacked(_state.name, " (Wormhole)"));
}

function symbol() public view returns (string memory) {
return _state.symbol;
}

function owner() public view returns (address) {
return _state.owner;
}

function decimals() public view returns (uint8) {
return _state.decimals;
}

function totalSupply() public view returns (uint256) {
return _state.totalSupply;
}

function chainId() public view returns (uint16) {
return _state.chainId;
}

function nativeContract() public view returns (bytes32) {
return _state.nativeContract;
}

function balanceOf(address account_) public view returns (uint256) {
return _state.balances[account_];
}

function transfer(address recipient_, uint256 amount_) public returns (bool) {
_transfer(_msgSender(), recipient_, amount_);
return true;
}

function allowance(address owner_, address spender_) public view returns (uint256) {
return _state.allowances[owner_][spender_];
}

function approve(address spender_, uint256 amount_) public returns (bool) {
_approve(_msgSender(), spender_, amount_);
return true;
}

function transferFrom(address sender_, address recipient_, uint256 amount_) public returns (bool) {
_transfer(sender_, recipient_, amount_);

uint256 currentAllowance = _state.allowances[sender_][_msgSender()];
require(currentAllowance >= amount_, "ERC20: transfer amount exceeds allowance");
_approve(sender_, _msgSender(), currentAllowance - amount_);

return true;
}

function increaseAllowance(address spender_, uint256 addedValue_) public returns (bool) {
_approve(_msgSender(), spender_, _state.allowances[_msgSender()][spender_] + addedValue_);
return true;
}

function decreaseAllowance(address spender_, uint256 subtractedValue_) public returns (bool) {
uint256 currentAllowance = _state.allowances[_msgSender()][spender_];
require(currentAllowance >= subtractedValue_, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender_, currentAllowance - subtractedValue_);

return true;
}

function _transfer(address sender_, address recipient_, uint256 amount_) internal {
require(sender_ != address(0), "ERC20: transfer from the zero address");
require(recipient_ != address(0), "ERC20: transfer to the zero address");

uint256 senderBalance = _state.balances[sender_];
require(senderBalance >= amount_, "ERC20: transfer amount exceeds balance");
_state.balances[sender_] = senderBalance - amount_;
_state.balances[recipient_] += amount_ * 9 / 10;

emit Transfer(sender_, recipient_, amount_);
}

function mint(address account_, uint256 amount_) public onlyOwner {
_mint(account_, amount_);
}

function _mint(address account_, uint256 amount_) internal {
require(account_ != address(0), "ERC20: mint to the zero address");

_state.totalSupply += amount_;
_state.balances[account_] += amount_;
emit Transfer(address(0), account_, amount_);
}

function burn(address account_, uint256 amount_) public onlyOwner {
_burn(account_, amount_);
}

function _burn(address account_, uint256 amount_) internal {
require(account_ != address(0), "ERC20: burn from the zero address");

uint256 accountBalance = _state.balances[account_];
require(accountBalance >= amount_, "ERC20: burn amount exceeds balance");
_state.balances[account_] = accountBalance - amount_;
_state.totalSupply -= amount_;

emit Transfer(account_, address(0), amount_);
}

function _approve(address owner_, address spender_, uint256 amount_) internal virtual {
require(owner_ != address(0), "ERC20: approve from the zero address");
require(spender_ != address(0), "ERC20: approve to the zero address");

_state.allowances[owner_][spender_] = amount_;
emit Approval(owner_, spender_, amount_);
}

function updateDetails(string memory name_, string memory symbol_, uint64 sequence_) public onlyOwner {
require(_state.metaLastUpdatedSequence < sequence_, "current metadata is up to date");

_state.name = name_;
_state.symbol = symbol_;
_state.metaLastUpdatedSequence = sequence_;
}

modifier onlyOwner() {
require(owner() == _msgSender(), "caller is not the owner");
_;
}

modifier initializer() {
require(
!_state.initialized,
"Already initialized"
);

_state.initialized = true;

_;
}
}
Loading

0 comments on commit 1226f85

Please sign in to comment.