1

First of all, sorry about my bad english.

I looked in the forum but I did not find a similar situation, but I apologize if I'm repeating something here.

I need to develop an application that runs on my backend server, without Metamask, and write a hash in the transaction input data (or any other place I can retrieve later through the transaction address).

I'll only use one wallet, which I believe may have your information stored in my backend code. This wallet will only have the purpose of paying the GAS of the transactions.

Is this possible? I barely know where to start. I just know that I should develop this through web3.js and run through node.js, and everything I found tells me to use Metamask.

Can anyone help me?

  • which network are you using? – lekshmi Jun 27 at 12:25
  • I need to do this on the mainnet. Is that possible? – Mario Filho Jun 27 at 13:16
1

What you are trying to achieve is definitely doable using any Ethereum tech stack (Javascript, Python, Go, Java, etc...).

I will try to explain step by step how to do it using nodejs, Truffle (Ethereum development framework) and Ganache (local development blockchain)

Prerequisite:

  • NodeJS, NPM

  • Truffle

$ npm install -g truffle
$ truffle version
Truffle v5.0.24 (core: 5.0.24)
Solidity v0.5.0 (solc-js)
Node v10.15.3
Web3.js v1.0.0-beta.37
  • Ganache
$ npm install -g ganache-cli

$ ganache-cli --version
Ganache CLI v6.4.1 (ganache-core: 2.5.3)

1. Initialise the Truffle project

First step consists to create a new folder for our project and initialise the Truffle project.

$ mkdir blockchain-backend
$ cd blockchain-backend
$ truffle init

2. Put your SmartContract into the contracts/ folder

I imagine from your question that your requirement s to store a hash on the Ethereum Blockchain, the following smart contract should simply do the job:

DocRegistry.sol

pragma solidity ^0.5.6;

contract DocRegistry {

  struct Doc {
      address sender;
      uint date;
      bytes32 hash;
  }

  /**
   *  @dev Storage space used to record all documents
   */
  mapping(bytes32 => Doc) registry;

  /**
   *  @dev Store a document identified by its 32 bytes hash by recording the hash, the sender and date in the registry
   *  @dev Emit an event HashStored in case of success
   *  @param _hash Document hash
   */
  function storeHash(bytes32 _hash) external returns (bool) {
    registry[_hash].sender = msg.sender;
    registry[_hash].date = now;
    registry[_hash].hash = _hash;

    emit HashStored(msg.sender, _hash);

    return true;
  }

  /**
   *  @dev Definition of the event triggered when a document is successfully stored in the registry
   */
  event HashStored(address indexed _sender, bytes32 _hash);
}

Copy the file DocRegistry.sol into the folder contracts/ of the Truffle project

3. Configure the deployment

To deploy a smart contract using Truffle, you need to add/edit two files:

  • Migration Script

First, create a migration script into migrations/2_deploy_contracts.js

migrations/2_deploy_contracts.js

const DocRegistry = artifacts.require("DocRegistry");

module.exports = function(deployer) {
  deployer.deploy(DocRegistry);
};
  • Truffle config

Then edit the file truffle-config.js and add the following code to connect to Ganache (development/testing blockchain)

truffle-config.js

module.exports = {
  networks: {
    development: {
      host: "127.0.0.1",     // Localhost (default: none)
      port: 8545,            // Standard Ethereum port (default: none)
      network_id: "*",       // Any network (default: none)
    }
  }
}

4. Start the Ganache development blockchain

Start Ganache

$ ganache-cli
Ganache CLI v6.4.1 (ganache-core: 2.5.3)
(...)
HD Wallet
==================
Mnemonic:      pelican evolve ask syrup labor demand find weekend detect winner husband buffalo
Base HD Path:  m/44'/60'/0'/0/{account_index}
(...)
Listening on 127.0.0.1:8545

Save the Mnemonic for later

5. Deploy the smart contract

To deploy the SmartContract on to Ganache (connection configured into truffle-config.js, run the following command.

$ truffle migrate
(...)
Summary
=======
> Total deployments:   2
> Final cost:          0.00837372 ETH

6. Create a NodeJS script to interact with the SmartContract deployed previously

Now the important piece you are looking for is the way to interact with the Blockchain from a backend NodeJS.

  • Initialise a NPM project
$ npm init
  • Install dependencies
$ npm install truffle-contract truffle-hdwallet-provider --save

o truffle-contract: JS Ethereum contract abstraction

o truffle-hdwallet-provider: HD Wallet-enabled Web3 provider. Use it to sign transactions for addresses derived from a 12-word mnemonic.

  • Create the NodeJS script

The wallet used will be the one created by Ganache by default and formatted as a mnemonic, but any funded wallet could work.

Using truffle-contract, we can load the Truffle Artefact (JSON build file) which contains all the information about the smart contract and its deployment (address, , network, etc...)


  // Connect to the Blockchain and unlock the wallet to send transaction
  const HDWalletProvider = require("truffle-hdwallet-provider");
  const mnemonic = "leisure chat amazing bleak erode olympic obscure chaos pull inquiry tunnel day"; // Wallet: 12 words mnemonic 
  const provider = new HDWalletProvider(mnemonic, "http://localhost:8545");

  // Load the Truffle artefact
  const truffleContract = require("truffle-contract");
  const DocRegistryJSON = require('./build/contracts/DocRegistry.json');
  const DocRegistry = truffleContract(DocRegistryJSON)
  DocRegistry.setProvider(provider);

  const docRegistryInstance = await DocRegistry.deployed();

  // Send transaction
  const hash = "0x644bcc7e564373040999aac89e7622f3ca71fba1d972fd94a31c3bfbf24e3938";
  var result = await docRegistryInstance.storeHash(hash, {from: "0x09b99dc4c7f7a1f6feffade28500e8f163e96d97"});

  console.log(result)
})();


Result

As a result, we get a transaction receipt

{ tx:
   '0x3a83e299d758c97a366e80d2887a66841f39320c2db685877caa1fc22fecdc23',
  receipt:
   { transactionHash:
      '0x3a83e299d758c97a366e80d2887a66841f39320c2db685877caa1fc22fecdc23',
     transactionIndex: 0,
     blockHash:
      '0x9556f8ac9736a6b6acffec39eb161486acd4525df308ebf152d9d6484b5af2f2',
     blockNumber: 9,
     from: '0x09b99dc4c7f7a1f6feffade28500e8f163e96d97',
     to: '0x17141b0c3b45b70f753d7c483558758bffdf6af4',
     gasUsed: 85727,
     cumulativeGasUsed: 85727,
     contractAddress: null,
     logs: [ [Object] ],
     status: true,
     logsBloom:
      '0x00000000000000000000000000080000000000000000000000000000000000000000000000000000000001000800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000100000000000000000000000000000000000000000000000000000100000000000000000000000000000400001000000000000000000000000000000000000000000000000',
     v: '0x1b',
     r:
      '0xc8cd182b1a0b376e88bc4a6b4ea1d3c0571276e4027f20ec5ded420c5c60fe03',
     s:
      '0x0fc0d343f2782e13355ed2806352a1046e03eeb4eeb45ea53875614e01dc0a75',
     rawLogs: [ [Object] ] },
  logs:
   [ { logIndex: 0,
       transactionIndex: 0,
       transactionHash:
        '0x3a83e299d758c97a366e80d2887a66841f39320c2db685877caa1fc22fecdc23',
       blockHash:
        '0x9556f8ac9736a6b6acffec39eb161486acd4525df308ebf152d9d6484b5af2f2',
       blockNumber: 9,
       address: '0x17141b0C3B45b70f753d7c483558758BFFdf6aF4',
       type: 'mined',
       id: 'log_8a20c769',
       event: 'HashStored',
       args: [Result] } ] }

Summary

This a very simple example how to leverage Truffle to deploy a SmartContract and feed a NodeJS in order to execute calls, send transactions or listen events !

This example uses Ganache as a testing Ethereum Blockchain but could simply be replaced by any Ethereum nodes on any network (see infura for simple access to Ethereum networks: mainnet, ropsten, rinkeby, etc.).

  • Thanks, @greg-jeanmart! I read it and it makes a lot of sense. I'll try it and I'm going back here to give feedback. – Mario Filho Jun 28 at 12:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.