Web3js & Truffle Practices

Be sure those are ready in the environment

  • NodeJS ^12.x
  • npm-global-install issue fixed if you are on linux

Start truffle project

~> npm i -g truffle
~> mkdir <FOLDER_NAME>; cd <FOLDER_NAME>
~> truffle init
~> npm i --save @truffle/hdwallet-provider

Start infura or Alchemy account

Let’s go with infura for now. Create an account and start a free project and get

  • Infura ID
  • Infura Secret Key
  • Ropsten Endpoint (https://ropsten.infura.io/v3/ … )

Edit truffle-config.js

  • set mnemonic secret from your metamask wallet
  • save it in the .env file

MNEMONIC = "<MNEMONIC_PROVIDED_BY_METAMASK>"

set infura secret key in the .env file and inject them in truffle-config.js

const MNEMONIC = process.env.MNEMONIC
const INFURAID = process.env.INFURAID
const INFURAKY = process.env.INFURAKY
const DEPLOYER = process.eng.DEPLOYER

Uncomment ropsten network settings

networks: {
  ropsten: {
    provider: () => new HDWalletProvider(
       MNEMONIC, `https://ropsten.infura.io/v3/${INFURAID}`
    ),
    network_id: 3,
    gas: 5000000,
    from: DEPLOYER
  },
}

Get into Truffle Developer Mode JVM

~> truffle develop

Compile a contract

~truffle(develop)> compile

Deploy a contract

~truffle(develop)> deploy

Deploying contract is helping us to upload the new modified contract to the same address.

Define deployed contract

~truffle(develop)> let instance = await MyContract.deployed()

Execute a function in contract

~truffle(develop)> instance.balanceOf(accounts[0])

Get Past Events

~truffle(develop)> let eventsLog = MyContract.getPastEvents()

Returns and array of event objects which has address, blockhash, id, return values etc. Return values are the specific information that we would might require from a return of an event we defined in the contract.

Let’s assume that we have a contract event which returns added tokens into a wallet contract with the arguments of user who puts the token, which symbol and which token address for it.

~truffle(develop)> eventsLog[0]

{
    address: '0x00...1',
    blockhHash: '0x00...2',
    blockNumber...
    ...
    returnValues: Result {
        '0': '...',
        '1': '...',
        '2': '...',
        'sender': '0x00...03',
        'symbol': '0x00...04',
        'tokenAddress': '0x00...05'
    },
    event: 'tokenAdded',
    ...
}

 

To get only the tokenAddress

from that event log

~truffle(develop)> getEventsLog[0].tokenAddress
'0x00...05'

Testing

test/ folder contains JavaScript files and last truffle version uses mocha js test framework. Example javascript test code might look like this:

// bring the contract(s)
const Wallet = artifacts.require("Wallet");
// const OtherContract = artifacts.require("...");
// create the contract instance
contract("Wallet"), accounts => {
  // define multiple users
  const owners = [accounts[0], accounts[1], accounts[2]];
  // define the contract
  let wallet;
  // assign the deployed contract instance(s)
  before(async () => {
    wallet = await Wallet.deployed();
    // token: await ...
  });
  // describe test case as params: description, asynchronous function
  describe("we are testing some functions", async () => {
    // definitions in through tests
    const toAddress = "0x00..0A";
    const fromAddress = "0x00...0B";
    const amount = (1*10)**18;
    const balance = Wallet.web3.eth.getBalance(fromAddress);
    let logTokenSent;
    // define what's gonna happen before the test result with params: description, async. function
    before("reading event, run the tx", async () => {
      // run the example before-staged function or anything required in flow chain
      logTokenSent = await wallet.transferFrom(toAddress, amount);
    });
    // assertion occurs
    it("should pass only when balance is greater than the amount", async () => {
      assert.greaterThan(balance, amount);
    });
  });
}

Iinitializer Batch Script in Testing Environment

const TokenContract  = artifacts.require("TokenContract")

const operator = accounts[0];
const buyer = accounts[2];

module.exports = async function(callback) {
    const token = await TokenContract.deployed()
    console.log(token.address)
}

Start the Discussion!Leave a Reply