Getting in Touch with the Smart Contract

Published by Mario Oettler on

Now, we want to communicate with the smart contract. For this purpose, create another file dapps1_browser04.html.

<!DOCTYPE html>
<html>
    <head>
        <script src='web3.min.js'>
        </script>
        <script>
            var abi = [
	{
		"inputs": [],
		"name": "getMyName",
		"outputs": [
			{
				"internalType": "string",
				"name": "",
				"type": "string"
			}
		],
		"stateMutability": "view",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "string",
				"name": "_name",
				"type": "string"
			}
		],
		"name": "payIn",
		"outputs": [],
		"stateMutability": "payable",
		"type": "function"
	},
	{
		"inputs": [
			{
				"internalType": "address",
				"name": "",
				"type": "address"
			}
		],
		"name": "profiles",
		"outputs": [
			{
				"internalType": "string",
				"name": "name",
				"type": "string"
			},
			{
				"internalType": "uint256",
				"name": "balance",
				"type": "uint256"
			}
		],
		"stateMutability": "view",
		"type": "function"
	}
];
            var address = "0x129e2D5a20b70bE1A352C23c68E01ff586bad4D5";
            window.addEventListener("load", (event)=>{
                if(window.ethereum){
                    ethereum.request({method: 'eth_requestAccounts'}).then(function(res){
                        console.log(res);
                        window.web3 = new Web3(window.ethereum);
						var contract = new web3.eth.Contract(abi, address);
                        document.getElementById("send").addEventListener("click", (event) =>{
                            amount = document.getElementById("amount").value;
                            name = document.getElementById("name").value;
                            console.log("amount: " + amount);
                            console.log("name: " + name);
                            contract.methods.payIn(name).send({
                                "value": amount, //e. g. 10000000000000000,
                                "from" : res[0]
                            }).then(function(result){
								console.log(result);
							});
                        })

						document.getElementById("call").addEventListener("click", (event) => {
							contract.methods.getMyName().call({
								"from" : res[0]
							}).then(function(result){
								console.log(result);
							});
						});
                    })
                }else{
                    return false
                }
            })
        </script>
    </head>
    <body>
        <h1>Contract Interaction</h1>
        <div>
            <input type = "text" id = "name">
            <label for = "recipientAddress">Name</span>
            <input type = "text" id = "amount">
            <label for = "amount">Amount</span>
            <button id = "send">Use PayIn function</button>
			<button id = "call">Use getMyName Function</button>
        </div>
    </body>
</html>

In lines 7 to 58, we copied the ABI. The ABI (Application Binary Interface) is the interface description of a smart contract. It contains all information that is necessary to call functions, send transactions, listen for events, etc. For example, it contains the names of all functions, their parameters, and return values. The ABI is given in JSON format.

In line 59, we store the address of our compiled smart contract.

In lines 60 to 64, we have the boilerplate code that is necessary to connect to MetaMask.

In line 65, we create a contract object. The constructor expects the ABI and address, which we stored earlier on in the variables.

In line 66, we react if the button “Use PayIn function” is clicked. After that, we take the values from the text fields and save them in the variables amount and name.

In line 71, we call the function payIn() of the contract. We submit the value for the function parameter name. Then, we use the method send(). Send() is used if a transaction is made. This means the state of the blockchain will change. The send method expects an options object as a parameter. Here, we add the parameters value and from. From provides the address of the account (given in MetaMask) we use. For simplicity, we chose the account that was active when connecting with MetaMask. Value is the amount of Ether that we want to send to the smart contract.

Once the miners have processed the transaction, the promise is fulfilled and the block details are displayed in the browser console.

In line 80, we read data from the blockchain. For simple read access, we don’t need a transaction. The full node processes such read access without the interference of a miner. That’s why we don’t need to pay any gas. Such read-only accesses are called “call” instead of transaction. The web3.js method is call. It resembles the structure of the send() method.

Change the file name in your javascript file on the server and run it in the browser calling the local host.

Categories: