Web3js & Truffle Practices
Aug-2022
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: