Watching balance of a smart contract

iam makin a simple lottery app in vuejs, solidity lottery
there i have viewbal function, i want to watch the balance of smart contract, when user invest, it adds to the balance of smart contract, how do i watch it
using wss protocol

I’m still fairly new to programming, so I might not have this right at all or may be misunderstanding you, but 2 suggestions I have, would be:

  1. define the variable with the ‘public’ keyword for the scope as this creates an automatic getter function, e.g.
uint public contractBalance;

then make sure the user investment amount is is being added to the contractBalance (see below where I have the userInvestment function for an example)

  • if it isn’t that simple or you want a function to do this, then you could try the following
  1. define a state variable (‘contractBalance’), then when a user invests, update the contractBalance with the amount the user is investing…then the viewBal function could return contractBalance
    e.g.
uint contractBalance;

modifier costs(uint minimumInvestmentAmount) {
    require(msg.value >= minimumInvestmentAmount, "You do not have enough to invest");
    _;
}

function userInvestment() public payable costs(1 finney) {  //I have just used 1 finney as an example
    contractBalance += msg.value;

function viewBal() public view returns(uint balance) {
       return contractBalance;
}

Obviously this is overly simplified and there would/should be requirements and other statements within each of the functions. The ‘costs’ modifier would probably have different requirement statements based on what sort of investment (a fixed amount or within a certain range, for example). But I think this gives you the general idea of what you could add to your functions to get the viewBal.

Regarding the ‘watch the balance of smart contract’ - I’m not very experienced with jQuery, but I guess you would be able to add an event listener somehow so the viewBal function is automatically called each time the contractBalance is changed…??? again, I have very little experience with jQuery so not sure about that, but if that is what you meant by ‘watching the balance of the smart contract’ then I’m afraid I have probably wasted your time.

If I have misunderstood your question or didn’t provide any help, then I apologise but I hope this does help in someway. Good luck.

2 Likes

Hello sir, have you done any of our Ethereum Programming courses?

If you have any more questions, please let us know so we can help you! :slight_smile:

Carlos Z.

2 Likes