Programming Project - Phase 1

@VictorEth
Amazing work!

You can share your code for review.

1 Like

@Dan_O_Kane

Good work with phase 1.

  1. you have used public and private efficiently.
  2. Great work with wrapping the functions as well.

Regarding this function

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

To get the contract balance, its best to use : address(this).balance which you are already aware of. :slight_smile: You might have some problem with cumulatively adding the contract balance to show the final balance.

For the following two functions:

function random() public view returns (uint) {
        return getnow() % 2;
    }

     function getnow() public view returns (uint) {
        return now;
    }

Its always better to write solidity code in as many less codes as possible. Remember you are paying gas fees for more number of lines of code you write in solidity.

You minimise to:

function random() public view returns (uint) {
        return now() % 2;
    }
1 Like

@Taha

I solved the earlier problem I mentioned. Now, a problem that has arisen is the exact same as @lusivekrane . The solution of adding value to config didnā€™t work for me and resulted in the following:

Error: Can not send value to non-payable contract method or constructor

Iā€™ve made a Github account and uploaded my current workings (youā€™ll notice itā€™s currently incomplete):

The problem is in main.js. Do you know the solution?

EDIT : First issue solved (see replies)

Hello,

Iā€™ve worked on a project to create a smart-contract with a front-end made with React, where a user can deposit funds, and setup other adresses as his heir.

If anything happens to this ā€œparentā€ user, any of his heir can start a claim on the funds.

A countdown will then start (default of 7 days, but can be changed by the parent), during which the parent will still be able to cancel the claim or withdraw his funds, in case any of the heirs try to steal the funds.

Once the countdown is over, each heir can withdraw an equal proportion of the balance of the parent (withdrawableAmount = balance / nbOfHeirs)

You can find the source code of my project here

So iā€™ve programmed the smart contract, wrote unit tests, the unit tests all pass with success, but now iā€™m being stuck when i try to use web3 to interact with the smart contract.

Im trying to interact with a very simple view function from my smart contract (which works in the unit test)

    function getClaimDelay(address parent) public view returns(uint) {
      uint claimDelay = _claimDelay[parent];
      if (claimDelay == 0) return defaultClaimDelay;
      return claimDelay; 
    }

and in my reactApp im trying to interact with the function like this :

const web3 = new Web3(Web3.givenProvider); 
await web3.eth.requestAccounts(); 
const accounts = await web3.eth.getAccounts(); 
const contract = new web3.eth.Contract(ethHeirloomAbi, ethHeirloomAddress); 
const delay = await contract.methods.getClaimDelay(accounts[0]).call(); 
console.log('Delay', delay)

But then in the chrome console i got this error :

    MetaMask - RPC Error: Internal JSON-RPC error.
    
    1.  {code: -32603, message: "Internal JSON-RPC error.", data: {ā€¦}, stack: "Error: Internal JSON-RPC error.ā†µ    at s (chrome-eā€¦beogaeaoehlefnkodbefgpgknn/background.js:60:73437"}
    
    1.  code:  -32603
    2.  data:  {message:  "VM Exception while processing transaction: revert",  code:  -32000,  data:  {ā€¦}}
    3.  message:  "Internal JSON-RPC error."
    4.  stack:  "Error: Internal JSON-RPC error.ā†µ    at s (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:198572)ā†µ    at Object.internal (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:198975)ā†µ    at l (chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:74281)ā†µ    at chrome-extension://nkbihfbeogaeaoehlefnkodbefgpgknn/background.js:60:73437"
    5.  __proto__:  Object

(My metamask is correctly setup on the ganache address, i can transfer ether fine through metamask on my ganache network, so i dont think the issue is related to a config problem of metamask.

So the second think i tried, was to deploy the contract on the Kovan testnet, which leads to my second issue :

Iā€™ve setup my Infura key, my mnemonic, the settings for kovan in my truffle config, but when i try to run the migration, i have this in my logs :

    Ī» truffle migrate --network kovan
      
    
    Compiling your contracts...
    
    ===========================
    
    > Compiling .\contracts\EthHeirloom.sol
    > Compiling .\contracts\Migrations.sol
    > Compiling .\contracts\Ownable.sol
    > Compiling .\contracts\math\SafeMath.sol
    > Compilation warnings encountered:
    
        
    /C/Users/tibog/Documents/repo/eth-heirloom/packages/contract/src/contracts/EthHeirloom.sol:
     Warning: SPDX license identifier not provided in source file. Before 
    publishing, c
    
    onsider adding a comment containing "SPDX-License-Identifier: 
    <SPDX-License>" to each source file. Use "SPDX-License-Identifier:
     UNLICENSED" for non-open-source code. Please see
    
    [https://spdx.org](https://spdx.org) for more information.
    
    ,/C/Users/tibog/Documents/repo/eth-heirloom/packages/contract/src/contracts/Ownable.sol:
     Warning: SPDX license identifier not provided in source file. Before 
    publishing, consider
    
     adding a comment containing "SPDX-License-Identifier: 
    <SPDX-License>" to each source file. Use "SPDX-License-Identifier:
     UNLICENSED" for non-open-source code. Please see https:/
    
    /spdx.org for more information.
    
      
    
    > Artifacts written to C:\Users\tibog\Documents\repo\eth-heirloom\packages\contract\src\build\contracts
    
    > Compiled successfully using:
    
       - solc: 0.6.12+commit.27d51765.Emscripten.clang
    
    Starting migrations...
    
    
    ======================
    
    > Network name:    'kovan'
    > Network id:      42
    > Block gas limit: 0xbebc20
     
    
    1_initial_migration.js
    ======================
    
       Deploying 'Migrations'
    
       ----------------------
       > transaction hash:    0x636eb0acd4b6bbe010f32d5e8eb5faec09992f898dcf98ff2b9741a52f2d21bd
    
       ā ø Blocks: 2            Seconds: 5Error [ERR_UNHANDLED_ERROR]: Unhandled error. ({
    
      code: -32603,
      message: 'ETIMEDOUT',
      data: { originalError: { code: 'ETIMEDOUT', connect: true } },
      stack: 'Error: ETIMEDOUT\n' +
    
        '    at Timeout.<anonymous> 
    (C:\\Users\\tibog\\Documents\\repo\\eth-heirloom\\node_modules\\request\\request.js:848:19)\n'
     +
        '    at listOnTimeout (internal/timers.js:549:17)\n' +
        '    at processTimers (internal/timers.js:492:7)'
    })
        at Web3ProviderEngine.emit (events.js:299:17)
        at C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\@trufflesuite\web3-provider-engine\index.js:57:14
        at afterRequest (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\@trufflesuite\web3-provider-engine\index.js:151:21)
        at C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\@trufflesuite\web3-provider-engine\index.js:176:21
        at C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\@trufflesuite\web3-provider-engine\index.js:238:9
        at C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\async\internal\once.js:12:16
        at replenish (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\async\internal\eachOfLimit.js:61:25)
        at C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\async\internal\eachOfLimit.js:71:9
        at eachLimit (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\async\eachLimit.js:43:36)
        at C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\async\internal\doLimit.js:9:16
        at end (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\@trufflesuite\web3-provider-engine\index.js:217:5)
        at Request._callback 
    (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\@trufflesuite\web3-provider-engine\subproviders\rpc.js:36:21)
        at self.callback (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\request\request.js:185:22)
        at Request.emit (events.js:310:20)
        at Timeout.<anonymous> (C:\Users\tibog\Documents\repo\eth-heirloom\node_modules\request\request.js:851:16)
        at listOnTimeout (internal/timers.js:549:17)
        at processTimers (internal/timers.js:492:7)

If you look at https://kovan.etherscan.io/tx/0x636eb0acd4b6bbe010f32d5e8eb5faec09992f898dcf98ff2b9741a52f2d21bd the migration contract got deployed fine, but it stops there.

Iā€™ve spent quite a while stuck on those 2 issues, tried to find solution online, but havent found anything so far.

Thanks in advance for your help,
Lumyo

Hello,

I have been getting the RPC error quite frequently as well. Re-installing metamask fixed the issue for me. It may not be an issue with your code. I would try reinstalling metamask and see if that works.

Recording of phase 1 of project.

Hello,
Thanks for the tip, I tried reinstalling metamask, but sadly it didnt fixed the issue in my case.

Iā€™ve finally managed to solve my first issue, concerning the JSON-RPC error.
I found out that it worked fine when I tried it on my Linux VM, so iā€™ve ended up updating truffle and ganache on my windows environement, redeployed the contract, and now it works fine.

Iā€™m still having the second issue concerning the deployment on kovan testnet though.

1 Like

Looking for recommendations for screen capturing programs so I can take a video of my Dapp in action. Looking for something easy to use, well established (trusted) with a good track record (no malware, etc). Recommendations would be greatly appreciated from any of you awesome peeps that have experience using anything that ticks the boxes, cheers

@cryptocrom Look at https://www.cockos.com/licecap/ if you wanna quickly record as gif
(Thats open source)

2 Likes

@Uyan
I have made added a commit in your git repo regarding the issue.
You need not add config variable to the send() like

contractInstance.methods.withdrawFunds(balanceToTransfer).send(config)

so I changed it to this:

contractInstance.methods.withdrawFunds(balanceToTransfer).send()

By passing the value to send(), you are passing msg.value where in the function is not accepting any value rather only transferring to the msg.sender.

Withdrawing 1 ETH successfully

1 Like

@Lumyo
Great to see you solve your first error :+1:
In your second error:

  1. first issue: is a warning, so you can ignore warnings. We only need to worry about errors. :slight_smile:

  2. Second issue: seems to be related to your dApp connection to Kovan. To reproduce the error, I will need your complete code. Better share it via Github

Thanks

1 Like

@Rishi_Remesh
Amazing!
Please share your code for review.

2 Likes

Thanks for the help. I see that you can withdraw funds from the function fine. After having made the change of removing config from the code, I get this problem:

Withdraw Funds = 0

How come you can withdraw, but I canā€™t and get 0 when I try? ( getContractBalance and topUpContract work as intended)

Account 9 is the account address of the contract owner. The other address is the contract address.

@Taha Here is the git repo
Iā€™ve thought about a problem with the connection to the infura node, so Iā€™ve tried setting up a local kovan node, but havent been successfull doing so. Iā€™ve left Geth run overnight using :

geth --networkid 42 --datadir="D:/kovan/"

But the sync didnt made any progress
Also, the infura dashboard shows incoming requests, so I dont think Iā€™ve made mistake configuring it.

The value HTML is giving is in Wei. So we have to multiple 10^18 using web3 function.

balanceToTransfer = web3.utils.toWei(balanceToTransfer, "ether");

I have committed a Line in main.js directly in your Github.

1 Like

I added some temporary extra lines to the function to see what is going on:

function withdrawFundsOutput
  //var balanceToTransfer = $("#withdraw_funds_output").val();
  var balanceToTransfer = $("#withdraw_funds_output").val();
  balanceToTransfer = web3.utils.toWei(balanceToTransfer, "ether");
  $("#withdraw_funds_output").text(balanceToTransfer + " Wei");
  console.log(web3.utils.fromWei(balanceToTransfer, 'ether') + " ETH");

  //contractInstance.methods.withdrawFunds(web3.utils.toWei(balanceToTransfer, "ether")).send()
  contractInstance.methods.withdrawFunds(balanceToTransfer).send()
  .on("transactionHash", function(hash){
    console.log(hash);
  })
  .on("confirmation", function(confirmationNr){
    console.log(confirmationNr);
  })
  .on("receipt", function(receipt){
    console.log(receipt);
    alert("Done");
  })
}```

It appears that your commits are helping problems that would arise in the future, so thank you for that, but Iā€™ve still got the persistent problem of withdrawing 0 when I use the function:

Withdraw Funds Error Persists

I was speculating it might be something non-code related - such as mismatching contract addresses or a file directory problem - but Iā€™m really struggling to see what the problem is since you yourself were able to use the function fine as shown by your earlier screenshots. What else have I missed?

@Uyan
The point here is we are not sending msg.value rather transferring ETH using transfer() to transfer from the contract to an address. Hence this is a contract operation and not transfer (or a transaction) operation.

Step 1:

Summary

Step 2: withdrawing 2 ETH

Summary

Step 3: it wonā€™t show in the metamask because it is a contract operation and not a transaction

Summary

Step 4: Checking final balance

Summary

You can proceed with the transaction, your amount will be withdrawn.

2 Likes

Thank you, that is the knowledge I was missing! It does work as you showed. Iā€™ll look into the differences of contract operations and transactions.

Phase 1

The contract is initialized with 5 ETH. Here is a screenshot after a deposit, a withdrawal and a bet is made:

Phase 1 Example 'Before'

After another bet has been made:

Phase 1 Example After

Here is the code: https://github.com/Uy4n/Coinflip_DApp

This project was made with the intention of being the absolute bare bones necessary for a functioning DApp; I didnā€™t add any extra functionality or add any creative twists to the UI. I wanted to save this until phase 2, where I will have a greater wealth of programming knowledge from which to draw ideas.

I learnt a LOT during this phase of the project. During the end of the project, having cleaned up the errors and gaining a greater understanding of how my code works, I realised how I might want to structure my code for Phase 2. For example, a lot of error messages I wrote in my .sol files were written as strings in memory, hence no way to access them from the frontend in .js files. I also thought about using bool functions instead of if equal statements to make it easier for me to implement fetch and display functions for those strings. Iā€™m enjoying the slow process of becoming a full-stack developer. Iā€™m not sure that ā€˜just frontendā€™ or ā€˜just backendā€™ or ā€˜just UIā€™ would be enough to satisfy my appetite for learning!

1 Like