Function declared as view error in solidity - blockchain

pragma solidity >=0.4.16 <0.9.0;
contract Wallet {
uint balance = 0;
bool a = true;
function deposit(uint dep_amt) public {
balance += dep_amt;
}
function withdraw (uint wdraw_amt) public view returns(string memory error){
if(wdraw_amt<=balance){
balance -= wdraw_amt;
}
else{
error = "Insufficient Balance";
return error;
}
}
function getBalnce() public view returns (uint) {
return balance;
}
}
I'm very new to solidity and I'm trying to code a simple bank system which shows the balance and updates the balance according to the deposits and withdraws. I want to display an error in withdraw function when the amount to be withdrawn is greater than the balance but it shows an error saying:
TypeError: Function declared as view, but this expression (potentially) modifies the state and thus requires non-payable (the default) or payable.
Is there a way to possibly show the error from the same function?
If not, Please let me know an alternative.
Thanks in advance!!.

A view function promises not to modify the contract state - such as not to modify storage variables. See the docs for more info.
But your code modifies the balance variable, which is a storage variable.
function withdraw (uint wdraw_amt) public view returns(string memory error){
if(wdraw_amt<=balance){
balance -= wdraw_amt; // <-- here
}
and updates the balance according to the deposits and withdraws
Since one of your requirements is to actually update the storage variable, you need to remove the view modifier in order to be able to do that.
function withdraw (uint wdraw_amt) public returns(string memory error){
Users will then need to send a transaction (not a call) to execute the withdraw() function.
When you have a function executed by a transaction (and not by a call), you can get the string output in two ways.
Revert reason message
function withdraw(uint wdraw_amt) public {
if (wdraw_amt <= balance) {
balance -= wdraw_amt;
} else {
revert("Insufficient Balance");
}
}
Event log
event Error(string _message);
function withdraw(uint wdraw_amt) public {
if (wdraw_amt <= balance) {
balance -= wdraw_amt;
} else {
emit Error("Insufficient Balance");
}
}

Related

enum and change of state : state of contract in constructor

I am writing a smartcontract which allows to buy an object and to visualize the purchase price with GetTransactionInformation and to visualize the number of purchases made with GetObjectShipped, I am trying to change the state of my smartcontract according to these parameters with my manufacturer so that if I don't buy anything, then my contract is pending, and if I bought my contract then goes shipped, do you have a solution to change these states depending on the items purchased
here my contract
pragma solidity 0.8.7;
contract contracts {
enum shippingStatus1{ shipped, delivered, pending }
constructor (uint shippingStatus1) public {
if (numberShipped == 0)
{state == pending}
else
{state == shipped}
}
struct shippingStatus {
uint buy;
uint numberShipped;
string state;
}
mapping(address => shippingStatus) Sellstatus;
function GetTransactionInformation() public view returns(uint) {
return Sellstatus[msg.sender].buy;
}
function GetOjectshipped() public view returns(uint){
return Sellstatus[msg.sender].numberShipped;
}
receive() external payable{
Sellstatus[msg.sender].buy += msg.value;
// enregistrement du status dans la variable numberShipped
Sellstatus[msg.sender].numberShipped += 1;
}
}

I want to make a time based transaction in smart contract

I am creating smart contract for lottery system and I want to make a time based transaction like a certain amount of players are added into the array then a time stamp should run and on specific time which I will declare should send the amount to the winner,
This is the part where I am stuck, I am trying to enter into the lottery from this this function and when conditions met I want to transfer the amount through the same function cause I want to automate the winner function:
function enter() public payable{
require(msg.value > 1 wei);
players.push(msg.sender);
if(players.length==10){
start = block.timestamp;
}
if(block.timestamp>= start+totalTime){
uint index = random()% players.length;
players[index].transfer(this.balance);
dead[index].transfer((this.balance*2)/100);
winner = players[index];
players = new address[](0);
}
This is my complete code:
pragma solidity ^0.4.26;
contract Lottery{
address public manager;
address[] public players;
address [0x000000000000000000000000000000000000dead] private dead;
address public winner;
uint start;
uint end;
uint totalTime=50;
constructor()public {
manager = msg.sender;
}
function enter() public payable{
require(msg.value > 1 wei);
players.push(msg.sender);
if(players.length==10){
start = block.timestamp;
}
if(block.timestamp>= start+totalTime){
uint index = random()% players.length;
players[index].transfer(this.balance);
dead[index].transfer((this.balance*2)/100);
winner = players[index];
players = new address[](0);
}
}
function random() private view returns (uint){
return uint(keccak256(block.difficulty,now,players));
}
function getBalance() public view returns(uint){
return address(this).balance;
}
function getPlayers() public view returns (address[]){
return players;
}
function getWinner() public view returns (address){
return winner;
}
function getTime() public view returns (uint){
return end-block.timestamp;
}
}
You can't, someone has to call the function and pay the gas fees, what you can do is having an script that listen for events and every time someone "enters" in the lottery and check if already reached the desired amount and then calls the function to get the winner, also you can't have any logic outside a function in solidity, using block difficulty and timestamp as a source of randomness if you are planing to deploy to production is better to use chainlink

Set ETH price in Solidty

I made a basic smart contract:
contract Coursetro {
uint counter = 0;
event SetCounter(uint value);
function setCounter(uint value) public {
counter +=1;
emit SetCounter(value);
}
function getCounter() public view returns (uint) {
return counter;
}
}
but i don't know how to set a fixed ETH price for setCounter function
for exemple how can i set the price of 1 ETH to run setCounter function?
So i could just take the 1 ETH and put it on my wallet, as a sale.
First of all, welcome to the community. I recommend adding your code to your post directly, so that it is easier to read.
You could use the 'payable' modifier to make the function able to receive ether. Then you can simply make a require statement to check if the value sent was enough. Something like this:
function setCounter(uint value) public payable {
require(msg.value >= 1 ether, "Error msg here");
// You can additionally return the surplus ether.
if (msg.value > 1) {
payable(msg.sender).transfer(msg.value - 1 ether);
}
// Now send ether to your wallet.
payable("your wallet address").transfer(1 ether);
// Rest of the logic.
counter +=1;
emit SetCounter(value);
}
Hope it is useful :)

Solidity : Getting error as Member “balance” not found or not visible after argument-dependent lookup

I am trying to write a Decentralization App to buy a concert ticket. For some reason, the part owner.transfer(this.balance) keeps giving me error. Also since solidity has too many version, I can't find a the best for mine. please help me in this. Thank you
Erro Message
Getting error as Member “balance” not found or not visible after argument-dependent lookup. Use address(this).balance to access address owner.transfer(this.balance)
Solidity Code
pragma solidity 0.6.6;
contract Event {
address owner;
uint public tickets;
string public description;
string public website;
uint constant price = 0.01 ether;
mapping (address => uint) public purchasers;
constructor(uint t, string memory _description, string memory _webstite) public {
owner = msg.sender;
description = _description;
website = _webstite;
tickets = t;
}
// function () payable {
// buyTickets(1);
// }
function buyTickets(uint amount) public payable {
if (msg.value != (amount * price) || amount > tickets) {
revert();
}
purchasers[msg.sender] += amount;
tickets -= amount;
if (tickets == 0) {
owner.transfer(this.balance);
}
}
function refund(uint numTickets) public {
if (purchasers[msg.sender] < numTickets) {
revert();
}
msg.sender.transfer(numTickets * price);
purchasers[msg.sender] -= numTickets;
tickets += numTickets;
}
}
After I change it to owner.transfer(address(this).balance);, it gave me another error.
[vm] from: 0x5b3...eddc4to: Event.buyTickets(uint256) 0xd91...39138value: 0 weidata: 0x2f3...00001logs: 0hash: 0x030...bbdf1
status 0x0 Transaction mined but execution failed
transaction hash 0x03045aab3f5d40ebeef4eacedf50ce506edfc2b75c279652839fd74f8e9bbdf1
from 0x5b38da6a701c568545dcfcb03fcb875f56beddc4
to Event.buyTickets(uint256) 0xd9145cce52d386f254917e481eb44e9943f39138
gas 3000000 gas
transaction cost 21760 gas
execution cost 296 gas
hash 0x03045aab3f5d40ebeef4eacedf50ce506edfc2b75c279652839fd74f8e9bbdf1
input 0x2f3...00001
decoded input { "uint256 amount": { "_hex": "0x01" } }
decoded output {}
logs []
value 0 wei
transact to Event.buyTickets 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.
transfer is only able for payable address.
try as follows.
address payable owner;
...
owner.transfer(address(this).balance);

Why am I getting this error ? "Gas estimation errored with the following message (see below). The transaction > execution will likely fail"

Trying to test solidity using Remix IDE. I keep getting the error:
Gas estimation errored with the following message (see below). The transaction > execution will likely fail. Do you want to force sending?
Does anybody have an idea about what might be giving me this error. It I am trying to sell products using the ethereum smart contracts. I have used the Remix IDE to create this contract with value = 0.
I am successfully able to create the contract and add_product but I am unable to Buy. The last line give me the error mentionned above.
The solidity file I am testing againt is the following: As you can see I create a Sell contract which would allow a user to sell products using the blockchain and a buyer to retrieve the product paying the price in ethereum. If anyone has a better solution for me to use for this exact use-case I am opened to suggestions.
pragma solidity ^0.4.0;
contract Sell {
struct Product_Quantity{
string _product_name;
uint256 _product_quantity;
uint256 _price_unity;
bool isValue;
}
struct Seller{
address _id;
mapping(string => Product_Quantity) products;
}
Seller public seller;
mapping (address => Product_Quantity) product_owners;
function Sell(){
seller._id = msg.sender;
}
function add_product(string product_name, uint256 product_quantity, uint256 price_unity) {
if(msg.sender != seller._id) throw;
if(seller.products[product_name].isValue){
seller.products[product_name]._product_quantity += product_quantity;
}
else{
seller.products[product_name] = Product_Quantity(product_name, product_quantity, price_unity, true);
}
}
function Buy( string product_name, uint256 quantity) payable {
if(product_owners[msg.sender].isValue){
product_owners[msg.sender]._product_quantity += quantity;
}
else{
product_owners[msg.sender] = Product_Quantity(product_name, quantity, seller.products[product_name]._price_unity, true);
}
seller.products[product_name]._product_quantity -= quantity;
seller._id.transfer(seller.products[product_name]._price_unity * quantity);
}
}
That's a very generic Remix error message. Fortunately, today I'm seeing new error messages on Remix (nice update guys!), which makes it easier to debug the problem.
When someone tries to buy a product, you should check if the value passed (in wei) is the right amount to buy that product and quantity.
Since you're not checking that, a buyer can buy a product with an amout equals to 0, which means the contract will have no wei to send to the seller at the end of the buy() function. That will throw an exception and the transaction will be reverted.
I updated your code to run on solidity 0.4.23 (latest version), made some code refactoring and add a modifier to the buy() function to check if the amount passed is correct.
pragma solidity ^0.4.23;
contract Sell {
struct Product_Quantity{
string _product_name;
uint256 _product_quantity;
uint256 _price_unity;
bool isValue;
}
mapping (address => Product_Quantity) product_owners;
struct Seller{
address _id;
mapping(string => Product_Quantity) products;
}
Seller public seller;
constructor() public {
seller._id = msg.sender;
}
function add_product (string product_name, uint256 product_quantity, uint256 price_unity) public {
require(msg.sender == seller._id);
if (seller.products[product_name].isValue) {
seller.products[product_name]._product_quantity += product_quantity;
}
else{
seller.products[product_name] = Product_Quantity(product_name, product_quantity, price_unity, true);
}
}
modifier hasEnoughEther (string product_name, uint256 quantity) {
require (seller.products[product_name].isValue); // does the product exists?
uint256 neededEther = seller.products[product_name]._price_unity * quantity;
require (msg.value == neededEther); // did the buyer sent the correct value?
_;
}
function buy (string product_name, uint256 quantity) payable public hasEnoughEther (product_name, quantity) {
if (product_owners[msg.sender].isValue) {
product_owners[msg.sender]._product_quantity += quantity;
} else {
product_owners[msg.sender] = Product_Quantity(product_name, quantity, seller.products[product_name]._price_unity, true);
}
seller.products[product_name]._product_quantity -= quantity;
seller._id.transfer(seller.products[product_name]._price_unity * quantity);
}
}
In my case, I needed to fund my contract so it can perform operations.
In your case you are trying to use a MODIFIER function with arguments but have not passed any parameters to it in the Buy function.
And in my case I was trying to trigger a non-payable function with some ether in the VALUE field of the Deploy and Run Transactions tab.