Tuesday, August 30, 2022

Calling Smart contract from Ropsten using Swarm Ethereum Solidity

 Please refer to the old post that will show you how we had created solidity smartcontract and uploaded it on the Ropsten test server using infura service layer.

Now lets concentrate on following below items

Step 1- we created UI simple html and with the help of web3.js interact with our smart contract exposed on truffle with Ganache ui test server data locally (means not deployed our html on any server localhost direcly opened it on browser and test it for calling smart contract).
Step 2- We exposed our simple ui html on local host using php server and contacted our smart contract deployed/migrated on Truffle using Metamask as wallets
Step 3- Then we installed geth client and made our machine as an ethereum node so that we can upload our contract on ropstan Test ehereum block chain.
Step 4- Finally we deployed our smart contract on test env along with ui on swarm and consumed it using browser.

Lets execute
Step 1- we created UI simple html and with the help of web3.js interact with our smart contract exposed on truffle with Ganache ui test server data locally (means not deployed our html on any server localhost direcly opened it on browser and test it for calling smart contract).

Frist lets depliy our contract using truffle to development env using belwo command.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
C:\truffle-project>truffle compile
C:\truffle-project>truffle migrate development
 
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>truffle compile --all
 
Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SendMoney.sol
> Artifacts written to C:\Ethereum_workspace\siddhuethreuminfuraproject\build\contracts
> Compiled successfully using:
   - solc: 0.8.15+commit.e14f2714.Emscripten.clang
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>truffle migrate development --reset
 
Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SendMoney.sol
> Artifacts written to C:\Ethereum_workspace\siddhuethreuminfuraproject\build\contracts
> Compiled successfully using:
   - solc: 0.8.15+commit.e14f2714.Emscripten.clang
 
 
Starting migrations...
======================
> Network name:    'development'
> Network id:      5777
> Block gas limit: 6721975 (0x6691b7)
 
 
1_initial_migration.js
======================
 
   Replacing 'Migrations'
   ----------------------
   > transaction hash:    0x99e3b291facad3eaa94ed60e8d870a6ac5f7a7c00ce12264f43b019d2308622f
   > Blocks: 0            Seconds: 0
   > contract address:    0xDb942CFdf2FC411c026c62DB871279a3951A32F9
   > block number:        6
   > block timestamp:     1661761212
   > account:             0x337f2C4e80F4f8A44093012550f2e13f26b4a8Cd
   > balance:             99.97557788
   > gas used:            248854 (0x3cc16)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00497708 ETH
 
   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00497708 ETH
 
 
2_SendMoney_migration.js
========================
 
   Replacing 'SendMoney'
   ---------------------
   > transaction hash:    0x55847f93329705807dae539241d97c2c7c0a3ea5493598aa3ffc729d2ac36ce2
   > Blocks: 0            Seconds: 0
   > contract address:    0xB3185814d44ccF7c42826d6B167a36Bb7Baf13b5
   > block number:        8
   > block timestamp:     1661761213
   > account:             0x337f2C4e80F4f8A44093012550f2e13f26b4a8Cd
   > balance:             99.96816606
   > gas used:            328078 (0x5018e)
   > gas price:           20 gwei
   > value sent:          0 ETH
   > total cost:          0.00656156 ETH
 
   > Saving migration to chain.
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00656156 ETH
 
Summary
=======
> Total deployments:   2
> Final cost:          0.01153864 ETH
 
 
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>

As shown below in build folder open SendMoney.json and get the abi from there.

now add this contractAbi.js in our html files.

Now lets check out smart contract using web application.
For that we should write a web files that will be exposed as web application and that will consume our contract.
web3.js is the best component that is used widely to do that. we are going to use the same.
we are using simple bootstrap and jquery for look and feel and actions in our html.

Make a web folder in truffle and add this files to it.

We will have a simple html that will ask for

sender address:- Text field for sender address.
receiver address:- Text field for receiver address.
amount :- Text field for amount to be send from sender to receiver.
Send Amount button:- This button will call our Smart contract that will send amount from sender to reciever.
Get sender balance:- Button that will show the current balance value of the ether on the sender end.
Get recevier balance:- Button that will show the current balance value of the ether on the receiver end.

Please copy the below files in your web folder and also web3.js from https://www.cdnpkg.com/web3/file/web3.min.js/

For that we need to connect to Smart contact and for that we need contarct ABI. This can be taken using following ways

1- Froms site ether scan.
2- From Remix.
3- Best way i prefer from the build folder of truffle.

Lets take the third options.
When you execute the truffle compile and truffle migrate command inside build folder you will be able to see yourfilename.json file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
<script src="contractAbi.js"></script>
 
1- index.html
 
<!doctype html>
<html lang="en">
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
 
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
    <title>Siddhu Dapp Application using Infura</title>
  </head>
  <body>
    <h1>Siddhu dapp used to send money through contract.</h1>
 
     
    <form id="contract-form">
      <div class="form-group">
        <label for="Sender Address">Sender Address</label>
        <input value="0xDD1b4718Ac31cD614a686E5c824c21978412b064" type="text" class="form-control" id="fromAddress"  aria-describedby="fromAddressHelp" placeholder="Enter the Sender address" required="true">
        <small id="fromAddressHelp" class="form-text text-muted">Enter your wallet address. Note: you will need to approve this with your private key.</small>
      </div>
        <div class="form-group">
          <label for="Receiver Address">Receiver  Address</label>
          <input value="0xB63b05b90D69F6667cC316876461c46A861a4300" type="text" class="form-control" id="toAddress" aria-describedby="toAddressHelp" placeholder="Enter the receipient address" required="true">
          <small id="toAddressHelp" class="form-text text-muted">Enter the wallet address of the recipient.</small>
        </div>
        <div class="form-group">
            <label for="Amount">Send Amount</label>
            <input value="1" type="text" class="form-control" id="amount" aria-describedby="amountHelp" placeholder="Amount to send in ETH from Sender Address to Receiver Address" required="true">
            <small id="amountHelp" class="form-text text-muted">How much you want to send in ETH.</small>
          </div>
          
      <button type="submit" class="btn btn-primary">Submit Transection Send Amount</button>
      <div id="deposit-result">Click the Submit button to deposit your ETH to the contract.</div>
    </form>
    <hr>
 
    <h2>Current Sender Balance:</h2>
    <form id="get-sender-balance-form">
      <button type="submit" class="btn btn-primary">Get Sender Balance</button>
      <div id="the-sender-balance">Click Button to get the current Receiver contract balance.</div>
    </form>
    <h2>Current Receiver Balance:</h2>
    <form id="get-receiver-balance-form">
      <button type="submit" class="btn btn-primary">Get Receiver Balance</button>
      <div id="the-receiver-balance">Click Button to get the current Receiver contract balance.</div>
    </form>
 
 
    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="web3.min.js"></script>
    <script src="contractAbi.js"></script>
    <script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
 
    <script>
     //contract address for local html file
    //var contractAddress = '0xedE6c52334d81A1A791f813D5779659Fa29367d2';
    //For Ropsten test env
    var contractAddress = '0x4030a98731397B204460D54fb5C8A3ab67373151';
 
    if ( typeof web3 != 'undefined') {
      //this web3 is for Metamask as it provide by default web3 object/provider to connect
      console.log("Got Metamask Provider:");
      web3 = new Web3(web3.currentProvider);
    } else {
      //this web3 is to connect to directly to our Ganace UI and do the transection from html files.
      console.log("Using Local Provider:");
      web3 = new Web3(new Web3.providers.HttpProvider("http://127.0.0.1:7545"));
    }
 
    var version = web3.version;
    console.log("using web3 version: " + version);
 
    var sendMoney = new web3.eth.Contract(abi, contractAddress);
     
    console.log("sendMoney:"+sendMoney);
 
    $('#contract-form').submit(function() {
      event.preventDefault();
      var fromAddress = $('#fromAddress').val();
      console.log("fromAddress:"+fromAddress);
      var toAddress = $('#toAddress').val();
      console.log("toAddress:"+toAddress);
      var amount = $('#amount').val();
      console.log("amount:"+amount);
      if (web3.utils.isAddress(fromAddress) != true) {
        alert('Enter proper ethereum address for the sender address');
        return;
      }
      if (web3.utils.isAddress(toAddress) != true) {
        alert('Enter proper ethereum address for the recipient address');
        return;
      }
      if (amount <= 0) {
        alert('Amount should be greated than 0 ETH.');
        return;
      }
       //This is for calling deposite funtion
     //sendMoney.methods.sendAmount(toAddress.value, amount).send({from: fromAddress, gas: 1000000, value: web3.utils.toWei(amount,'ether')},
     sendMoney.methods.sendCoin(fromAddress.value, toAddress, amount).send({from: fromAddress, gas: 1000000, value: web3.utils.toWei(amount,'ether')},
       function(error, result) {
          if (error) {
            console.log('error: ' + error);
              $('#deposit-result').html('Error occured in deposite methods: ' + error);
          } else {
            $('#deposit-result').html('Success transection and result of the TX: <b>' + result + '</b>');
          }
        })
    });
     
    $('#get-sender-balance-form').submit(function() {
      event.preventDefault();     
      sendMoney.methods.getSenderAmount(fromAddress.value).send({from: fromAddress.value, gas: 100000},
        function(error, result) {
          if (error) {
            console.log('error: ' + error);
          } else {
            console.log('balance:' + JSON.stringify(result));
            $('#the-sender-balance').html('<b>Current Sender Balance:</b> ' + web3.utils.fromWei(result,'ether'));
          }
        });
    });
 
     
    $('#get-receiver-balance-form').submit(function() {
      event.preventDefault();
       
      sendMoney.methods.getReceiverAmount(toAddress.value).send({from: toAddress.value, gas: 100000},
        function(error, result) {
          if (error) {
            console.log('error: ' + error);
          } else {
            console.log('balance:' + JSON.stringify(result));
            $('#the-receiver-balance').html('<b>Current Receiver Balance:</b> ' + web3.utils.fromWei(result,'ether'));
          }
        });
    });
     
       
    </script>
 
    </body>
</html>

Now lets try to deploy our contract on the ganache using remix app and we will see a trasection done on the ganache

Note above contact address can be taken from Ganache ui
var contractAddress = ‘0xedE6c52334d81A1A791f813D5779659Fa29367d2’;

Now open our html file in browser and then click on the Get Sender Balance and Get Sender Balance you will get the amount.

Now lets expposed our code on php server and consume it as a localhost and finally configure it with metamask wallet and we will deploy our smartcontract on Truffle using (truffle migrate development)

PHP (our html file ) + Smart contract on Truffle (Truffle Migrate development) + Meta mask as wallet

make sure you have php installed in your functions
go to belwo folder where our all html and abh files are kept and run this command.

1
C:\Ethereum_workspace\siddhuethreuminfuraproject\web>php -S localhost:8000

Now lets connect our localhost:8000 site to our meta mask as shown below.

Now lets add our address as sender and receiver in the metamask.

same way add the receiver account to

Now lets change the name of the Account 4 and Account5 as sender and receiver.

sendMoney.methods.getSenderAmount(fromAddress.value).send({from: fromAddress.value, gas: 100000},

we will get approve info on the meta mask before getting the data on the FE. lets do the same as shown below and you will find the data is retrived in FE.

Check the amount of sender and receiver in ganache before performing the operation

We have sender with 94.97 and receiver with 104 ether.

Now let click on the Send Transection Send Amount button and we will be able to send he amount.

Now lets move our code to the Ropsten test env so that we can test it from our ui.

Use below command sequential

but first migrate your metamask to rospten as shown below.

Sender Account 1

Receiver Account 2

1
2
3
4
5
6
7
8
9
10
11
12
C:\truffle-project>truffle compile --all
 
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>truffle compile --all
 
Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SendMoney.sol
> Artifacts written to C:\Ethereum_workspace\siddhuethreuminfuraproject\build\contracts
> Compiled successfully using:
   - solc: 0.8.15+commit.e14f2714.Emscripten.clang
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
C:\Ethereum_workspace\siddhuethreuminfuraproject>set path=C:\nvm\v16.17.0;.;%PATH%
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>node -v
v16.17.0
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>nvm use 16.17.0
Now using node v16.17.0 (64-bit)
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>truffle migrate -f 2 --to 2 --network ropsten --reset
 
 
Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SendMoney.sol
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>set path=C:\nvm\v16.17.0;.;%PATH%
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>node -v
v16.17.0
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>nvm use 16.17.0
Now using node v16.17.0 (64-bit)
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>truffle migrate -f 2 --to 2 --network ropsten --reset
 
Compiling your contracts...
===========================
> Compiling .\contracts\Migrations.sol
> Compiling .\contracts\SendMoney.sol
> Artifacts written to C:\Ethereum_workspace\siddhuethreuminfuraproject\build\contracts
> Compiled successfully using:
   - solc: 0.8.15+commit.e14f2714.Emscripten.clang
 
 
Starting migrations...
======================
> Network name:    'ropsten'
> Network id:      3
> Block gas limit: 30000000 (0x1c9c380)
 
 
2_SendMoney_migration.js
========================
 
   Replacing 'SendMoney'
   ---------------------
   > transaction hash:    0xa7aee0d7fc8eceac5643a00a6b0e8d789ce2a29493700ef8802706bd73164d61
   > Blocks: 1            Seconds: 12
   > contract address:    0x4030a98731397B204460D54fb5C8A3ab67373151
   > block number:        12888447
   > block timestamp:     1661774640
   > account:             0xDD1b4718Ac31cD614a686E5c824c21978412b064
   > balance:             18.989515117498200881
   > gas used:            328078 (0x5018e)
   > gas price:           10 gwei
   > value sent:          0 ETH
   > total cost:          0.00328078 ETH
 
   Pausing for 2 confirmations...
 
   -------------------------------
   > confirmation number: 1 (block: 12888448)
   > confirmation number: 2 (block: 12888449)
   > Saving artifacts
   -------------------------------------
   > Total cost:          0.00328078 ETH
 
Summary
=======
> Total deployments:   1
> Final cost:          0.00328078 ETH
 
 
 
C:\Ethereum_workspace\siddhuethreuminfuraproject>
 
Now lets move our only 2 migration script to Ropsten using below command.
 
Check the trasection is successful from this site
 

Now lets connect our localhost site with the our Ropsten test site and perform the operation and check it it is woriking fine.
To do that we only need to change the contract address in our html.

//For Ropsten test env
var contractAddress = ‘0x4030a98731397B204460D54fb5C8A3ab67373151’;

now restart our php server with below command.

C:\Ethereum_workspace\siddhuethreuminfuraproject\web>php -S localhost:8000
[Mon Aug 29 17:42:09 2022] PHP 8.1.8 Development Server (http://localhost:8000) started

open our html page on browser and perform all the operations.

change the Sender address in the text field and Click on get Sender Balance button

change the receiver address in the text field and Click on get receiver Balance button

Now lets try to send the ether form accoutn1 to accoutn 2 of robsten test env.

Before sending amount in respective user are as follws

Account 1

Account 2

Now click on Send Trasection Send amount button on the screen.

Now the amount of Accoutn 1 sender and Account 2 receiver are as follows

Sender will be 1 ether less and Receiver will be 1 ether more.

https://ropsten.etherscan.io/tx/0x7210d475f4670569f76416e147f645b6a631a6ff1a4effff49ae599095c4b1fe

Recevier new values is

Now lets move our whole ui code to swarm so that we can access it online. For that we have a site https://gateway.ethswarm.org/ as shown below

https://gateway.ethswarm.org/

https://bah5acgzaddzydnolkudlagy4stlamljpuliqie2kz5qvr34vly5d6ndca7gq.bzz.link/

Now lets connect our metamask robsten user to this site and perform our operation.

Now lets do the operation

1- Get Sender Amount

1- Get Receveiver Amount

Now lets try our main smart contract of transeferring money from sender to reciever

Fist note the amount for sender and recevier

sender

Receiver

As soon as we transfer the amount the sender will be 1 ether less and receiver will be 1 ether more in their respective accounts.

Now lets see if the sender and reciver amount is as what we thought above i.e. sender will be 1 ether less and receiver will be 1 ether more in their respective accounts.

Sender

Receiver

That is we are done with these belwo item in this blog.

Step 1- we created UI simple html and with the help of web3.js interact with our smart contract exposed on truffle with Ganache ui test server data locally (means not deployed our html on any server localhost direcly opened it on browser and test it for calling smart contract).
Step 2- We exposed our simple ui html on local host using php server and contacted our smart contract deployed/migrated on Truffle using Metamask as wallets
Step 3- Then we installed geth client and made our machine as an ethereum node so that we can upload our contract on ropstan Test ehereum block chain.
Step 4- Finally we deployed our smart contract on test env along with ui on swarm and consumed it using browser.

Github Location for above code:-
https://github.com/shdhumale/siddhuinfurasmartcontractwithui.git

No comments: