Home > Making of a Ethereum (ERC20) Based Token transaction App

Blog

Making of a Ethereum (ERC20) Based Token transaction App

One of the quickest way to implement Ethereum (ERC20) Token payment is web3. For desktop it’s required that the user have web3 compatible wallet (extension) installed in their browser (E.g. MetaMask), and mobile user can use their favorite dApp browser. indiesquare.me provide a lot of tech support for this. Following demo app’s backbone is indiesquare.me’s transaction API.

<div class="container">
    <h1>Demo App</h1>
    <form>
        <div class="form-group">
            <label>Create payment of 1 Token to address 0x….</label>
        </div>
        <button type="button" class="btn btn-primary" onclick="createTokenTransaction()">Create transaction</button>
        <pre id="status"></pre>
    </form>
</div>

Now we need the user’s wallet address for payment.
For getting user address we need to execute following function

web3.eth.getAccounts(callback(error, account){ });

Account object will have user’s address in first index.
After getting user’s address we can send a transaction request indiesquare.me API

var http = new XMLHttpRequest(),
    url = "https://api.indiesquare.me/eth/v1/transactions/send", // api
    params = {
	"from": usersAddress,
	"to": receivingAddress,
	"token": tokenContractAddress,
	"amount": amount
    };
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/json");
http.send(JSON.stringify(params));

This request will return an unsigned transaction as json string. So we need to parse and send the transaction.
This function will return txHash which you can view transaction details on etherscan.io
Eg.

https://etherscan.io/tx/txHash...
web3.eth.sendTransaction(unsignedTransaction,(err, result) => {
    if (err != undefined) {
        console.log("sign error:" + err);
    } else {
        console.log("broadcast transaction...");
        console.log("https://etherscan.io/tx/"+ result);
    }
});

If there is no error then the transaction is successful.
Not putting it all together.

<!DOCTYPE html>
<html>
	<head>
		<title>Demo App</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, initial-scale=1">
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
	</head>
	<body>
		<div class="container">
			<h1>Demo App</h1>
			<form>
				<div class="form-group">
					<label>Create payment of 1 Token to address 0x….</label>
				</div>
				<button type="button" class="btn btn-primary" onclick="createTokenTransaction()">Create transaction</button>
				<pre id="status"></pre>
			</form>
		</div>
		<scirpt type="text/javascript" src="main.js"></script>
	</body>
</html>
var updateStatus =  status => { // Error handling
	document.getElementById("status").innerHTML = status;
}
function createTokenTransaction() {
	try {
		updateStatus("Getting user address...");
		web3.eth.getAccounts( (err, acc) => { //get users address
			if (err != null) {
				updateStatus("error:" + err );
			} else {
				updateStatus("creating transaction...");
				//create sendtransaction using indiesqaure REST api 
				var usersAddress = acc[0];
				var receivingAddress = "0xf...."; // Ethereum Wallet Address for receiving payment
				var tokenContractAddress = "0xe....."; // ERC20 Token Contact Address;
				var amount = 1; // Number of Token to for this payment
				var http = new XMLHttpRequest();
				var url = "https://api.indiesquare.me/eth/v1/transactions/send"; // api
				var params = {
					"from": usersAddress,
					"to": receivingAddress,
					"token": tokenContractAddress,
					"amount": amount
				}
				http.open("POST", url, true);
				http.setRequestHeader("Content-type", "application/json");
				http.onreadystatechange = function() {
					if (http.readyState == 4 && http.status == 200) {
						updateStatus("signing transaction...");
						var unsignedTransaction = JSON.parse(http.responseText);
						//sign and send the transaction
						web3.eth.sendTransaction(unsignedTransaction, (err, result) => {
							if (err != undefined) {
								updateStatus("sign error:" + err);
							} else {
								updateStatus("broadcast transaction...");
								console.log("https://etherscan.io/tx/"+ result);
							}
						});
					} else {
						updateStatus("error creating transaction:" + http.statusText+ " "+http.responseText);
					}
				}
				http.send(JSON.stringify(params));
			}
		});
	} catch (e) {
		// no web3 (no wallet in browser or not in dApp browser)
		alert(e); //web3 not found
	}
}

Now we can test this app from a web server.

Preview of app.html

MetaMask Wallet Preview.

View codes in repository https://bitbucket.org/snippets/samepage/qeg7Be/ethereum-erc-20-based-token-transaction

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to notifications

Click to subscribe to notifications NO THANKS