How to make some action in a Solidity contract cost 1 Ether - solidity

I have a contract defined in solidity and I want to make it so that when a specific function is called, the overall cost of the contract increases by 1 ether. I am a little fuzzy on how to use ether in practice. Would I just use a normal int for this? Where does the keyword ether come into play?

As you probably know, 1 ether == 1000000000000000000 (or 10^18) wei.
You can access the transaction value in a global variable msg.value that returns amount of wei sent with the transaction.
So you can make a simple validation that checks whether the transaction calling your function has a value of 1 ETH.
function myFunc() external payable {
require(msg.value == 1 ether, 'Need to send 1 ETH');
}
It's the same as comparing to 10^18 wei
function myFunc() external payable {
require(msg.value == 1000000000000000000, 'Need to send 1 ETH');
}
function myFunc() external payable {
require(msg.value == 1e18, 'Need to send 1 ETH');
}
There's also a short paragraph on the Solidity docs that shows more examples: https://docs.soliditylang.org/en/v0.8.2/units-and-global-variables.html#ether-units

Related

Reentrancy attack with withdraw amount

I've been working on different ways to perform reentrancy attacks and there is one case which I have still not seen any working example on the internet. In the book Mastering Ethereum, the reentrancy attack is explained with a contract where the function withdraw(uint amount) takes the input amount. The version on Solidity has been updated a lot since then and whenever I try to perform a similar attack, it does not work. It works whenever the function withdraw() takes no arguments and it also works when using older versions.
Could anyone provide an example of a reentrancy attack where the target contract takes the withdraw amount as input?
Thank you!
Let's say you have 1 ether in the contract, and the contract has a total of 10 ether. You're trying to steal all 10 ether with re-entrancy, but that necessarily means the variable tracking your balance must underflow to the equivalent of uint256(-9) ether -- you're trying to withdraw 1 ether 10 times.. This will cause a revert in Solidity 0.8.0 or higher, since it has built in under/overflow protection. If you want it to work in 0.8.0, you have to wrap the balance reduction line with unchecked.
This code is still vulnerable to re-entrancy in 0.8.0, but only because it sets the balance to zero, and can't underflow
mapping(address => uint256) public balance;
function deposit() external payable {
balance[msg.sender] += msg.value;
}
function withdraw() external {
msg.sender.call{value: balance[msg.sender]}(""); // re-entrancy
balance[msg.sender] == 0; // cannot underflow
}
function withdrawV2(uint256 value) external {
require(value <= balance[msg.sender], "you don't have that much"); // not that this does anything...
msg.sender.call{value: balance[msg.sender]}("");
unchecked { // now it can underflow
balance[msg.sender] -= value;
}
}

Ethereum lottery smart contract reverts due to insufficient funds. Where does my code consumes that much gas?

I am experimenting with solidity and I faced an issue for what I could not find a solution.
The program should let addresses buy ticket at a preset price, and the owner can start the "roll the dice" function which randomly selects the winner and transfer the funds to that address.
I beleive that this program would be easier with mapping instead of array, but getting experience with array was the main purpose of this program.
The error happens when the user calls buyTicket function. Based on the response I beleive the contract comsumes too much gas. Can someone tell me why it doesnt work? I appreciate any other helping comment regarding the rest of the code:)
Thanks in advance!
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
contract Lottery {
constructor () {
owner = msg.sender;
}
address[] public Players;
address private owner;
uint public ticketPrice;
uint public price;
uint public nonce;
uint public variations;
address payable winner;
bool hasTicketAnswer;
event Winner(address _winner);
event PriceSet(uint _setPrice);
event TicketBought();
function setTicketPrice(uint _ticketPrice) public {
require(msg.sender == owner, "Only Owner...");
ticketPrice = _ticketPrice;
emit PriceSet(_ticketPrice);
}
function hasTicket(address _sender) private returns(bool) {
hasTicketAnswer = false;
for (uint i = 0; i < Players.length; i++) {
if (Players[i] == _sender) hasTicketAnswer = true;
}
return hasTicketAnswer;
}
function buyTicket() external payable {
require(ticketPrice > 0, "Price did not set, be patient...");
require(hasTicket(msg.sender) == false, "You cannot have two tickets...");
require(msg.sender.balance <= ticketPrice, "Insufficient funds...");
payable(address(this)).transfer(ticketPrice);
Players.push(address(msg.sender));
price += msg.value;
emit TicketBought();
}
function checkBalance() public view returns(uint) {
return address(this).balance;
}
function rollTheDice() public payable {
variations = Players.length;
winner = payable(Players[uint(keccak256(abi.encodePacked(msg.sender, nonce, block.timestamp))) % variations]);
winner.transfer(price);
emit Winner(winner);
}
receive () external payable {
}
}
Besides probably finding the problem, I've read some things that I'd like to comment on.
Your problem
The reason why you're getting the "Insufficient funds" error is because the condition is returning false. You're asking the msg.sender balance to be less than or equal (<=) to ticketPrice, when it should be more than or equal (>=).
Let's say Alice has a balance of 0.05 ETH and interacts with the contract whose ticket price is 0.001 ETH...
require(0.05 ETH <= 0.001 ETH) // Reverting...
Observations
I'm curious if you're intentionally coding the buyTicket function in that way. What it actually does is checking if the msg.sender has enough ETH to buy a ticket in its wallet, which doesn't mean that the user is effectively sending ETH in the transaction (the amount of wei sent in the transaction can be checked with msg.value, you can read more about it here).
My last observation is the payable(address(this)).transfer(ticketPrice) line of code, because it's not necessary to do so, once a payable function receives ETH, it is saved into the contract... In that line you're just making the Bob's contract to send ETH to the Bob's contract, which just wastes gas without reason
I hope I've helped with you and if I wasn't completely clear in any thing I've said don't doubt in asking me

How can I set the tx ETH amount?

I know a user can send ETH to the contract/function manually, but is there way to request a specific amount directly in the code so that it is added to the gas fee, for example, the way dxsale.app does it when creating a presale (see screenshot below) - it adds the 0.1 ETH cost of presale to the 0.0072 gas fee for a total of 0.1072.
Can this be done in an ERC20 contract? I know I can receive ETH in a payable function, e.g.
function deposit() payable public {
require(msg.value > 0, "You need to send some Ether");
}
but can I specify the amount I want to receive (for a flat fee), so that it is added to the tx cost?
Thank you
TLDR: The contract function is executed after the transaction has been sent. So it's not possible to to set the transaction params from the contract.
is there way to request a specific amount directly in the code
Not in the Solidity code. You can only throw an exception if the sent amount is not an expected value.
function deposit() payable public {
require(msg.value == 0.1 ether, "You need to send 0.1 Ether");
}
You can specify the amount when you're creating the transaction request. For example MetaMask uses the Ethereum Provider API, so you can predefine the amount that MetaMask will show.
const params = [
{
from: '0xb60e8dd61c5d32be8058bb8eb970870f07233155',
to: '0xd46e8dd67c5d32be8058bb8eb970870f07244567',
value: '0x9184e72a', // 2441406250
},
];
ethereum
.request({
method: 'eth_sendTransaction',
params,
});
But the user can override this option in their wallet, or they can always submit a transaction using a different way (not requested with the custom value).
The value (both in the params JS object and the Solidity msg.value global variable) always excludes the gas fees.
So if you're sending 0.1 ETH, the gas fees are added on top of that and the total cost might be 0.10012345. The params.value will contain 0.1 ETH (hex number in wei), as well as the msg.value will contain 0.1 ETH (decimal number in wei).

The called function should be payable error in withdraw function

I have such function to transfer tokens from contract and i get error where shoudl i add payable and i dont really understand if withdraw will withdraw ethers or tokens?
function withdrawBalances() public nonReentrant {
uint share = _Balances[msg.sender];
_Balances[msg.sender] = 0;
msg.sender.transfer(share);
}
.withdrawBalances errored: VM error: revert. revert The transaction has been reverted to the initial state. Note: The called function should be payable if you send value and the value you send should be less than your current balance. Debug the transaction to get more information.
This error occurs when you try to send some Ether when calling a function that isn't payable. Set Ether value to 0 to avoid this. You can also allow a function to accept Ether by using the payable keyword.
function withdrawBalances() public payable {
...
}

Sending ether in solidity smart contract

I'm writing a smart contract in solidity, and I need to send ether from my coinbase (eth.coinbase) to my friend coinbase (address = 0x0123).
If I try to use an address.send(value) the function doesn't decrease my account and doesn't increase my friend coin base.
I only can send ether in geth with "eth.sendTransaction(VALUE, {from:eth.coinbase, to:address})"
so I want to know if its possible to call an eth method in contract or a different way to send ether in smart contract
function withdraw() returns (bool) {
address x = 0x0123;
uint amount = 100 ether;
if (x.send(amount))
return true;
else
return false;
}
address.send does not propagate exception that's why you don't see any issue. Make sure you have enough Eth in your contract.
Have a look on this documentation that will explain how to set up your smart contract: https://developer.ibm.com/clouddataservices/2016/05/19/block-chain-technology-smart-contracts-and-ethereum/
You can use following function. just change variable name with yours.
function Transfer(uint amount,address reciever){
// check sender balance is less than of amount which he wants to send.
if(balance[msg.sender] < amount){
return;
}
// decrease sender's balance.
balance[msg.sender] = balance[msg.sender] - amount;
// increase reciever's balance.
balance[reciever] = balance[reciever] + amount;
// event
// transaction(msg.sender,reciever,amount);
}