Avoid using solidity's transfer()/send()? - ethereum

I came across this article dated 2019/9 about avoiding using solidity's transfer()/send(). Here is the reasoning from the article:
It looks like EIP 1884 is headed our way in the Istanbul hard fork. This change increases the gas cost of the SLOAD operation and therefore breaks some existing smart contracts.
Those contracts will break because their fallback functions used to consume less than 2300 gas, and they’ll now consume more. Why is 2300 gas significant? It’s the amount of gas a contract’s fallback function receives if it’s called via Solidity’s transfer() or send() methods. 1
Since its introduction, transfer() has typically been recommended by the security community because it helps guard against reentrancy attacks. This guidance made sense under the assumption that gas costs wouldn’t change, but that assumption turned out to be incorrect. We now recommend that transfer() and send() be avoided.
In remix, there is a warning message about the code below:
(bool success, ) = recipient.call{value:_amount, gas: _gas}("");
Warning:
Low level calls: Use of "call": should be avoided whenever possible. It can lead to unexpected behavior if return value is not handled properly. Please use Direct Calls via specifying the called contract's interface. more
I am not an expert on gas cost over execution of smart contract and security. So I post this article and would appreciate thoughts and comments about it.

First, it's good to know about the fallback function in Solidity:
It has no name, no arguments, no return value, and it can be defined as one per contract, but the most important feature is it is called when a non-existent function is called on the contract such as to send or transfer or call.value()(""). So if you want to send Ether directly to an address which is a contract address, the fallback function of the destination contract will be called.
If the contract's fallback function not marked payable, it will throw an exception if the contract receives plain ether without data.
Now let's look at the reentrancy attack
contract VulnerableContract {
mapping(address => uint) public balances;
function deposit() public payable {
require(msg.value > 1);
balances[msg.sender] += msg.value;
}
function withdraw(uint _amount) public {
require(balances[msg.sender] >= _amount, "Not enough balance!");
msg.sender.call.value(_amount)("");
balances[msg.sender] -= _amount;
}
function getBalance() view public returns(uint) {
return address(this).balance;
}
fallback() payable external {}
}
VuinerableContract has a withdraw function which sends Ether to the calling address. Now the calling address could be a malicious contract such as this :
contract MaliciousContract {
VulnerableContract vulnerableContract = VulnerableContract(0x08970FEd061E7747CD9a38d680A601510CB659FB);
function deposit() public payable {
vulnerableContract.deposit.value(msg.value)();
}
function withdraw() public {
vulnerableContract.withdraw(1 ether);
}
function getBalance() view public returns(uint) {
return address(this).balance;
}
fallback () payable external {
if(address(vulnerableContract).balance > 1 ether) {
vulnerableContract.withdraw(1 ether);
}
}
}
When the malicious contract call the withdraw function, before reducing the balance of the malicious contract, it's fallback function will be called at it can steal more Ether from the vulnerable contract.
So by limiting the gas amount used by the fallback function up to 2300 gas we could prevent this attack. It means we can not put complex and expensive commands in the fallback function anymore.
Look at this for more information: https://swcregistry.io/docs/SWC-107

From Consensys article, they are saying use .call() instead of .transfer() and .send(). Only argument is that all three now sends more gas than 2300. Thus making it possible for reentrancy.
This comes to another conclusion that, regardless of all above, it is important to use checks-effects-interactions pattern to prevent reentracy attack.

Related

solidity smart contract encode function for safety reason

I have one simple question.
So when we deal with smart contract on chain,
why don't we make encode function just in case for safety?
for example,
function encodeFunction(address _callee, bytes calldata _callData, uint256 _value) public returns (bool) {
(bool success, bytes memory returnData) = callee.call{vaule: _value}(_callData);
require(success, "tx failed");
return success;
}
Suppose that we are able to figure out any contract address and calldata, Isn't it much safer to have this kind of function to deal with any situation?
Wouldn't someone just listen to the encodeFunction and its parameters? For example etherscan allows users to see function calls and parameters .That would defeat the whole purpose of your encode function.
Also having this kind of function defeats the whole purpose of transparency of the concept blockchain.

Best plan of attack for digital certificates for proof of completion on EVM

I am looking to explore the option of creating a digital certificate (as in proof) when someone has completed a portion of training, and for this to be issued on an EVM-compatible blockchain using Solidity.
I have prototyped using ERC721 NFTs to encode a "certificate" however, I'd like to prevent recipients from being able to transfer these certificates. To prevent transfer, I attempted to use the Pause.sol functionality from OpenZeppelin, however, this would result in the entire contract being paused, as opposed to a specific tokenId.
Does anyone have any recommendation on an approach? Am I overcomplicating it if I don't want recipients to be able to trade the certificates (i.e. for them to remain static)? Any pointers would be much appreciated!
The simplest and most raw solution is to just set a mapping value.
pragma solidity ^0.8;
contract TrainingResults {
enum Stage {
NONE,
STAGE_1,
STAGE_2,
COMPLETED
}
mapping (address => Stage) public participantStage;
function setParticipantStage(address _graduate, Stage _stage) external {
require(msg.sender == address(0x123), "Not authorized");
participantStage[_graduate] = _stage;
}
}
Or if you want them to be able to see some kind of NFT in their wallet (that supports NFTs), you can modify the ERC-721 contract to disallow transfers.
For example the OpenZeppelin implementation uses a function named _beforeTokenTransfer() (GitHub link) that can be overwritten to disallow transfers altogether.
pragma solidity ^0.8;
import "#openzeppelin/contracts/token/ERC721/ERC721.sol";
contract TrainingResults is ERC721 {
constructor() ERC721("TrainingResults", "TR") {}
function _beforeTokenTransfer(address from,address to, uint256 tokenId) override internal {
// Allow only for the admin
// as this function is called on token mint as well
require(msg.sender == address(0x123), "Cannot transfer tokens");
}
}

Managing gas fees in solidity smart contract

I have a ERC20 smart contract with edited transfer function
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
if(_transactionMaxValue > 0){
require(_transactionMaxValue >= amount, "You can not transfer more than 1000000 tokens at once!");
}
transfer(recipient, amount);
}
I have added if statement in transfer function, in case user indicates limit per single transaction before deploying. I was wondering if this would affect gas fees when transferring tokens, in order to decide weather to leave the "universal" ERC20 smart contract template with indictable transaction limit or compose new one, with no if statement, if no transaction limit was indicated.
I was wondering if this would affect gas fees when transferring tokens
Adding the (if and require) conditions increases the total amount of gas used, but the increase is small in the context of gas usage of other operations of the parent transfer() function. It's because in the overriding function, you're performing "just" one more storage read and few other operations in memory.
Execution of your transfer() function costs 54,620 gas (including the parent function; assuming the require() condition doesn't fail). While execution of just the parent transfer() function costs 52,320 gas.
You need to use super.transfer(recipient, amount); if you want to invoke the parent transfer() function. Without the super keyword, you'd lock the script in an infinite recursion, always invoking itself.
Also, in order to correctly override the parent function, you need to state the override modifier (and virtual if you are planning to override this function as well) before the public visibility modifier, and to return the value as declared.
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/ERC20/ERC20.sol";
contract MyToken is ERC20 {
uint256 _transactionMaxValue = 1000000;
constructor() ERC20("MyToken", "MyT") {
_mint(msg.sender, 1000000);
}
// moved the `override virtual` before the `public` modifier
function transfer(address recipient, uint256 amount) override virtual public returns (bool) {
if(_transactionMaxValue > 0){
require(_transactionMaxValue >= amount, "You can not transfer more than 1000000 tokens at once!");
}
// added `return super.`
return super.transfer(recipient, amount);
}
}
Everything #Petr Hejda suggested is correct.
Additional improvement here would be to make a require statement fail reason string smaller and more precise, as it will result in the smaller bytecode, and therefore cheaper deployment.

Solidity smart contract audit

I have a solidity code to audit like this
pragma solidity ^0.8.0;
import "#openzeppelin/contracts/token/ERC20/IERC20.sol";
// Allow to split the balance through complex rules
interface Split{
function getAddressAndAmountToSplit() view external returns(address, uint);
}
// MyBank contract
// This contract allows anyone to store any ERC20 tokens
contract MyBank {
// (token => user => amount)
mapping (address => mapping(address => uint)) public userBalance;
// (address => Split contract)
mapping (address => Split) splits;
// Deposit ERC20 tokens to the contracts
// The user must approve the bank before calling addToBalance
function addToBalance(IERC20 token, uint amount) external {
token.transferFrom(msg.sender, address(this), amount);
userBalance[address(token)][msg.sender] += amount;
}
// Withdraw part of the balance
function withdrawBalance(IERC20 token) external {
token.transfer(msg.sender, userBalance[address(token)][msg.sender]);
userBalance[address(token)][msg.sender] = 0;
}
// Allow to register a split contract
function registerSplit(Split split) external {
splits[msg.sender] = split;
}
// Split the balance into two accounts
// The usage of a Split contract allows to create complex split strategies
function splitBalance(IERC20 token) external {
Split split = splits[msg.sender];
require(split != Split(address(0x0)));
uint balance = userBalance[address(token)][msg.sender];
(address dest, uint amount) = Split(split).getAddressAndAmountToSplit();
userBalance[address(token)][dest] = amount;
userBalance[address(token)][msg.sender] = balance - amount;
}
}
What I found.
function withdrawBalance(IERC20 token) external possible reentrancy attack, because we check balance in the end
function splitBalance(IERC20 token) external - vulnerable business logic, because if amount is greater than balance we get negative value and possible integer overflow
If you have any idea of possible vulnerabilities of code above, please feel free to provide any further assistance
Probably a bit late but if anyone reads this for why I think these aren’t vulnerabilities. First of all, there are no reentrancy attacks possible here, due to the fact that transfer function only forwards 2300 gas, which is quite not enough to execute something meaningful.
Secondly, its possible to add a require check if balance is bigger than the amount. But since contract is using later than or equal to 0.8.0 compiler versions, if amount is indeed bigger than balance, it will automatically revert due to underflow.
I think as a smart contract auditor, you should know these better.

Check if msg.sender is a specific type of contract

As it is now, anyone can call the setMyString function in the FirstContract. I'm trying to restrict access to that function to an instance of SecondContract. But not one specific instance, any contract of type SecondContract should be able to call setMyString.
contract FirstContract{
String public myString;
function setMyString(String memory what) public {
myString=what;
}
}
contract SecondContract{
address owner;
address firstAddress;
FirstContract firstContract;
constructor(address _1st){
owner=msg.sender;
firstAddress=_1st;
firstContract=FirstContract(firstAddress);
}
function callFirst(String memory what){
require(msg.sender==owner);
firstContract.setMyString("hello");
}
}
Solidity currently doesn't have an easy way to validate an address against an interface.
You can check the bytecode, whether it contains the specified signatures (of the public properties and methods). This requires a bit larger scope than a usual StackOverflow answer, so I'm just going to describe the steps instead of writing the code.
First, define the desired list of signatures (1st 4 bytes of keccak256 hash of the name and arguments datatypes) that you're going to be looking for. You can find more info about signatures in my other answers here and here.
An example in the documentation shows how to get any address's (in your case msg.sender) bytecode as bytes (dynamic-length array).
You'll then need to loop through the returned bytes array and search for the 4-byte signatures.
If you find them all, it means that msg.sender "implements the interface". If any of the signatures is missing in the external contract, it means it doesn't implement the interface.
But... I'd really recommend you to rethink your approach to whitelisting. Yes, you'll need to maintain the list and call setIsSecondContract() when a new SecondContract wants to call the setMyString() function for the first time. But it's more gas efficient for all callers of the FirstContract's setMyString() function, as well as easier to write and test the functionality in the first place.
contract FirstContract{
String public myString;
address owner;
mapping (address => bool) isSecondContract;
modifier onlySecondContract {
require(isSecondContract[msg.sender]);
_;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function setIsSecondContract(address _address, bool _value) public onlyOwner {
isSecondContract[_address] = _value;
}
function setMyString(String memory what) public onlySecondContract {
myString=what;
}
}