Loading...
Previously in Introduction to Tronweb smartbook we had discussed about tronweb by doing little transaction on tron network by using it in server side code. So in this smartbook we will do the same interaction with tron network but from the client side code i.e we will use client side browser to send transaction through TronLink wallet.
User will interact with our index.html file which will be our client side webpage and it will be served by a simple nodejs server.
You can visit chrome store and install TronLink extension. Create two accounts for this toutorial.
Shasta is testnetwork for tron blockchain. You can get test trx on shasta network from here , Enter your account address and submit to get the test trx.
> npm init
> npm install --save express
Here index.js will be our server file and index.html will be main working file.
> touch index.js
> mkdir public
> touch public/index.html
Our index.js file will be simple node server serving index.html file,
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var path = require('path');
var port = process.env.PORT || 3000;
app.use(express.static(path.join(__dirname, './public/')));
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
http.listen(port, function () {
console.log('listening on *:' + port);
});
After this start the server with following command :
> node index.js
Client side code will consist of html and script for interaction with blockchain.
As html UI isn't important for this topic, we will simply create a button for triggering send function and an input to take receiver's address.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tronweb</title>
</head>
<body>
<input id="receiver">
<button onclick="send_trx()"> Sent TRX </button>
</body>
</html>
Scipt will consist of two parts,
So for the first part our code will be as follows :
var tronWeb;
var receiver = document.getElementById('receiver')
var obj = setInterval(async () => {
if (window.tronWeb && window.tronWeb.defaultAddress.base58) {
clearInterval(obj)
var tronweb = window.tronWeb
}
}, 100);
We need to use setInterval function to get injected tronweb from tronlink wallet of the browser.
And for second part code is as follows :
async function send_trx() {
await tronWeb.trx.sendTransaction(receiver.value, 10000000);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tronweb</title>
</head>
<body>
<input id="receiver">
<button onclick="send_trx()"> Sent TRX </button>
</body>
<script>
var tronWeb;
var receiver = document.getElementById('receiver')
var obj = setInterval(async () => {
if (window.tronWeb && window.tronWeb.defaultAddress.base58) {
clearInterval(obj)
var tronweb = window.tronWeb
}
}, 100);
async function send_trx() {
await tronWeb.trx.sendTransaction(receiver.value, 10000000);
}
</script>
</html>