Try out Ethereum using only nodejs and npm!

CodeTract
CodeTract
Feb 4, 2017 · 5 min read
Image for post
Image for post
Image modified from https://www.ethereum.org/

Ethereum is a decentralized smart contract platform. In this tutorial we will go through deploying and interacting with a smart contract using only nodejs and npm. This will bring you through many useful tools created by other developers.

First, install the dependencies.

$ npm install web3@0.19 ethereumjs-util@4.4 ethereumjs-tx@1.3 eth-lightwallet@2.5

Next, obtain an address and its private key using MyEtherWallet. First, type in a password to encrypt your wallet file and download your wallet file. Then upload your wallet file to view your private keys.

Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post
Image for post

Next, obtain some Ether so that transactions can be sent. We will be using the Rinkeby testnet and their Ether can be obtained for free at this faucet. Follow the instructions and with your address obtained above, use that at the faucet for free Ether.

Image for post
Image for post

Next, check the balance of your account at Etherscan.

Image for post
Image for post

After the transaction is confirmed, you now have some Ether that can be used to pay for transaction fees.

Now, we can start coding, first, we create a new file and require all our dependencies.

var Web3 = require('web3');
var util = require('ethereumjs-util');
var tx = require('ethereumjs-tx');
var lightwallet = require('eth-lightwallet');
var txutils = lightwallet.txutils;

As we are not running a local Ethereum node, we can connect to a remote node provided by Infura to enable us to communicate with the Ethereum network.

var web3 = new Web3(
new Web3.providers.HttpProvider('https://rinkeby.infura.io/')
);

Next, we note down our address and private key from a previous step.

var address = '0x8D68583e625CAaE969fA9249502E105a21435EbF';
var key = '1ce642301e680f60227b9d8ffecad474f15155b6d8f8a2cb6bde8e85c8a4809a';

In this tutorial, we will deploy a simple ballot smart contract, vote on one of the proposals and check which proposal has been voted on. An example smart contract written in Solidity can be obtained at Remix.

Image for post
Image for post

The ballot smart contract code can also be found here in case it is not loaded automatically. The solidity code is compiled into for execution in the Ethereum virtual machine. The provides the mapping for a higher language to interact with the smart contract. Note them down.

var bytecode = '6060604052 ...';
var interface = [{ "constant": false, "inputs": ...;

Next, we create a function that signs transaction with our private key and sends them to the Ethereum network.

function sendRaw(rawTx) {
var privateKey = new Buffer(key, 'hex');
var transaction = new tx(rawTx);
transaction.sign(privateKey);
var serializedTx = transaction.serialize().toString('hex');
web3.eth.sendRawTransaction(
'0x' + serializedTx, function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result);
}
});
}

We can now deploy the ballot smart contract by constructing the following transaction.

var rawTx = {
nonce: web3.toHex(web3.eth.getTransactionCount(address)),
gasLimit: web3.toHex(800000),
gasPrice: web3.toHex(20000000000),
data: '0x' + bytecode + '0000000000000000000000000000000000000000000000000000000000000005'
};

is a sequential integer that keeps track of the number of outgoing transactions and should be 0 since this is the first transaction we are sending. But here we obtain the nonce from the network to make the code more general.

is the maximum amount of gas we are willing to pay for this transaction.

is the price we are willing to pay for the gas used for this transaction. will be the amount of transaction fee that we pay in ether.

is the added instructions for the transaction. Here, we include the to instruct the creation of our ballot smart contract. The zero padded 5 is an argument to the smart contract, meaning the ballot has 5 proposals.

Looking back to the solidity code, will be the argument for the constructor .

function Ballot(uint8 _numProposals) {
chairperson = msg.sender;
voters[chairperson].weight = 1;
proposals.length = _numProposals;
}

Now, send the transaction by calling the function

sendRaw(rawTx);

and running the script.

$ node tryEthereum.js

Using Etherscan again, we should see a pending contract creation.

Image for post
Image for post
Wait for the transaction to confirm and click into it, the address of the contract should be displayed.
Image for post
Image for post
We have successfully deployed a smart contract! Note down the address.

Back to our code, we will now construct a transaction to vote on proposal 4.

var contractAddress = '0x3ea36fad89cafdc84bc0ce82e0d98c6c0a796b19';
var txOptions = {
nonce: web3.toHex(web3.eth.getTransactionCount(address)),
gasLimit: web3.toHex(800000),
gasPrice: web3.toHex(20000000000),
to: contractAddress
}
var rawTx = txutils.functionTx(interface, 'vote', [4], txOptions);
sendRaw(rawTx);

Send the transaction

$ node tryEthereum.js

Wait for the transaction to confirm and then we can check the proposal that was voted on by querying the smart contract with the following code.

var contract = web3.eth.contract(interface);
var instance = contract.at(contractAddress);
instance.winningProposal.call(function(err, result) {
if(err) {
console.log(err);
} else {
console.log(result.toNumber());
}
});

Send the query and it should return 4.

$ node tryEthereum.js

We have successfully voted and verified the vote! That is all for now and since we still have some left over ether, we can send back to the faucet.

var rawTx = {
nonce: web3.toHex(web3.eth.getTransactionCount(address)),
gasLimit: web3.toHex(21000),
gasPrice: web3.toHex(20000000000),
to: '0x31B98D14007bDEe637298086988A0bBd31184523',
value: web3.toHex(web3.toBigNumber(web3.eth.getBalance(address))
.minus(web3.toBigNumber(21000).times(20000000000)))
};
sendRaw(rawTx);
$ node tryEthereum.js

To recap, we have deployed a smart contract, interacted with it and verified our interaction. The code used can also be found here. I hope you are feeling the potential of Ethereum and already thinking how smart contracts can disrupt many industries. There are many resources online and you can find a few below to start your journey on exploring Ethereum!

Ethereum main site https://www.ethereum.org/
Mist, one of Ethereum’s client https://github.com/ethereum/mist/releases
Solidity http://solidity.readthedocs.io/en/latest/
Web3 api https://github.com/ethereum/wiki/wiki/JavaScript-API
Community discussions https://www.reddit.com/r/ethereum/

Do note that this tutorial is only meant for a quick first experience with Ethereum. If you are starting to develop on it, it is recommended to use a client so that you can take advantage of libraries and frameworks that have better abstractions for creating transactions.

Follow us on Twitter and Medium for more updates!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store