“Note: I am using Web3JS version 1.0 in this tutorial”

Hello, I’ll explain how to send a transaction from the NodeJS back end. I will use Rinkeby Testnet and will create a router, add some node modules and use the Infura HTTP interface to complete the tutorial.

We need web3JS, Express and EthereumJS-TX modules to perform transactions. Then you need to enter your own API key from Infura to log in to Infura.

start

First, you need to create an empty folder for this project to make it easier to access. Once you have created the folder, you need to open the command shell in that folder. I assume you have NPM installed on your computer. NPM is distributed by NodeJS, so if you have nodeJS installed, you will also get NPM. If you haven’t downloaded nodeJS containing NPM from this site. After installing NPM, you need to call it.

npm init
Copy the code

If you want to leave the default Settings (including the default name, which is the folder name), you can skip all lines by typing Enter. At the end of this process, you will have a package.json file.

After starting the project, you need to create a JS file in the folder containing the name you want, which will be our back end.

Acquisition module

In my code, you can see that there are module requirements that we just need to include in the project via an NPM download. Their NPM calls:

npm install web3 --save
npm install express --save
npm install ethereumjs-tx --save
Copy the code

You need to call these lines separately from the command line to install them into the project. After completing the installation process, you can see that there is a folder named Node Modules, which is the folder where the modules were downloaded.

INFURA

After downloading the module. You need an Infura API key. The Api key is a key part of completing this tutorial. You can get it by logging into Infura. Once you have the Infura API key, you need to change line 7 (YOUR_API_KEY) with the API key.

Infura is a great interface, by the way. You can also access IPFS via the Infura API, which is a blockchain storage service. You can get more information about IPFS from their website.

By obtaining the Infura API key, we complete the pre-request of the code. We can start coding. From now on, I’ll explain the code line by line.

In the first three lines, I add the module to the JS file.

  • Web3 is the module that will interact with Ethereum.
  • Express is required to create a router.
  • Ethereumjs-tx is required to create exchanges.

In line 5, I use the Express module to create my application.

After creating the application, we need to write the last line of the file:

app.listen(3000, () => console.log('Example app listening on port 3000! '))Copy the code

In line 8, I create a Web3JS object using httpProvider, which is infura on the nodeJS backend. If you searched for Ethereum backend development before seeing this tutorial, you can see that many of them are encoded by ReactJS, and they use Metamask as an interface service. The NodeJS back end cannot access browser resources, so the NodeJS back end cannot use Metamask as the service interface program, which I have processed and used Infura as the interface service provider.

In some web3 functionality, web3’s WebSocket provider is required, so you need to change line 8 when you use it.

web3js = new web3(new web3.providers.WebsocketProvider('wss://mainnet.infura.io/_ws'));
Copy the code

In line 10, I create my router, which is a GET, but it needs to be published logically. I created this tutorial only to show how to complete the send transaction, so it doesn’t matter.

Inside the router I need my rinkeby ethereum address (myAddress), I will send my transaction address (toAddress), contractAddress (contractAddress) and contractABI (contractABI). You can search for the contract ABI through your Ethereum wallet or EtherScan. I deployed this tutorial contract from ethereum Wallet, you do not need to deploy any contract. You can simply use an existing one.

The last thing we need is my privateKey. This is not a safe way to do it, but since we don’t have any wallets on the front end (because we don’t have a front end :)) we do it manually at this point. You can’t access your private key through an Ethereum wallet, so you’ll need to import your Rinkeby Ethereum account into a site like MyEtherWallet.

In the router with the variables defined, we create the original transaction and then sign it with our private key. Once the transaction is signed, we send it to Rinkeby Testnet via Web3JS.

After coding, we need to test it. Open the command shell in the same folder and start the back end. My file name is backend.js so I started it from code.

node backend.js
Copy the code

This means you can start the back end with code:

node <filename with extension>
Copy the code

Start after the back-end, need to open a browser, and need to write http://localhost:3000/sendtx into the address line.

That’s all. We created our very small back end for Ethereum. The code is as follows:

const web3 = require('web3'); const express = require('express'); const Tx = require('ethereumjs-tx'); const app = express(); //Infura HttpProvider Endpoint web3js = new web3(new web3.providers.HttpProvider("https://rinkeby.infura.io/YOUR_API_KEY")); app.get('/sendtx',function(req,res){ var myAddress = 'ADDRESS_THAT_SENDS_TRANSACTION'; var privateKey = Buffer.from('YOUR_PRIVATE_KEY', 'hex') var toAddress = 'ADRESS_TO_SEND_TRANSACTION'; //contract abi is the array that you can get from the ethereum wallet or etherscan var contractABI =YOUR_CONTRACT_ABI; var contractAddress ="YOUR_CONTRACT_ADDRESS"; //creating contract object var contract = new web3js.eth.Contract(contractABI,contractAddress); var count; // get transaction count, later will used as nonce web3js.eth.getTransactionCount(myAddress).then(function(v){ console.log("Count: "+v); count = v; var amount = web3js.utils.toHex(1e16); //creating raw tranaction var rawTransaction = {"from":myAddress, "gasPrice":web3js.utils.toHex(20* 1e9),"gasLimit":web3js.utils.toHex(210000),"to":contractAddress,"value":"0x0","data":contract.methods.transfer(toAddress , amount).encodeABI(),"nonce":web3js.utils.toHex(count)} console.log(rawTransaction); //creating tranaction via ethereumjs-tx var transaction = new Tx(rawTransaction); //signing transaction with private key transaction.sign(privateKey); //sending transacton via web3js module web3js.eth.sendSignedTransaction('0x'+transaction.serialize().toString('hex')) .on('transactionHash',console.log); contract.methods.balanceOf(myAddress).call() .then(function(balance){console.log(balance)}); })}); app.listen(3000, () => console.log('Example app listening on port 3000! '))Copy the code

If you’re looking for a quick start on Ethereum development, check out this tutorial: Getting Started with Ethereum, which focuses on smart contracts and DApp development.

Other blockchain tutorials are as follows:

  • Ethereum development advanced tutorial, mainly introduces the use of Node.js, mongodb, blockchain, IPFS to achieve decentralized e-commerce DApp combat, suitable for advanced.
  • Java Ethereum development tutorial, mainly for Java and Android programmers for blockchain Ethereum development web3J details.
  • Python Ethereum is a detailed explanation of blockchain ethereum development by Python engineers using Web3.py.
  • PHP Ethereum mainly introduces the use of PHP for smart contract development interaction, account creation, transactions, transfers, token development, filters and events and other content.
  • C# ethereum, mainly explains how to use C# based development. Net ethereum applications, including account management, status and transactions, smart contract development and interaction, filters and events, etc.
  • PHP currency development tutorial, this course for beginners, content covers the core concepts of COINS, such as block mechanism, key chain store, decentralized consensus and script, trading and UTXO etc, also explained how to integrated the currency support functions in PHP code, such as creating address wallet, tectonic naked trading, management, This is a rare bitcoin development course for Php engineers.
  • This course will help you quickly get started on the development of EOS blockchain decentralized applications, covering core knowledge points such as EOS tool chain, account and wallet, issuing tokens, development and deployment of smart contracts, using codes to interact with smart contracts, and finally completing the development of a notepad DApp using all knowledge points comprehensively.

Huizhi net original translation, reprint please indicate the source. Here is the original text