Is there a way that I can charge a "fee" in ETH along with ALL transfers of an ERC20 token? Going to a hardcoded wallet, or perhaps a owner changable one...
What I had in mind was something like this (but that did not work):
function transfer(address recipient, uint256 amount) public override returns (bool) {
payable(0x1aE0EA34a72D944a8C7603FfB3eC30a6669E454C).transfer(10000);
_transfer(_msgSender(), recipient, amount);
return true;
}
Making if payable instead of public causes a compiling error
You can have the fee in WETH along with transfers and as it a ERC20 type, you can skip the payable, and then you can convert WETH to ETH separately by the owner.
This only if the user has approved the contract.
Correct, can be managed by the FE, same way the allowance and transfer model works
Then would be easier to charge fee in eth directly if you use a front-end. It will costs less
You don't need to declare it payable
instead of public
.
You need to declare it payable
together with public
:
function transfer(address recipient, uint256 amount) public payable override returns (bool) {
require(msg.value == 10000, "incorrect payment");
payable(0x1aE0EA34a72D944a8C7603FfB3eC30a6669E454C).transfer(10000);
_transfer(_msgSender(), recipient, amount);
return true;
}
You're right, you cannot override a non-payable function with a payable one:
TypeError: Overriding function changes state mutability from "nonpayable" to "payable".
Your option is to charge the fee in the given token, and immediately swap it for ETH on some DEX.
For example, assuming that a pool of the given token and ETH exists on Uniswap, you can execute swapTokensForExactETH
or swapExactTokensForETH
on that pool.
Note that this by itself would cause the Uniswap pool to execute transferFrom
on the token contract, so you'll need to make sure that there's no "loop of two functions calling each other forever".
Alternatively, you can charge the fee in the given token by simply transferring some of it to your own controlled address, and occasionally swap it for ETH on some DEX or CEX.