How to get Ethereum encoded function signatures

  • Function signatures are needed when writing a code to call smart contract’s functions in a primitive way or calling contract functions from multisig wallets.
  • To get function signature, you need to hash prototype string of function like functionName(type1,type2,...) with Keccak256. Then extract the first 4 bytes.
  • For example, if you want to get encoded function signature of the function sendMessage(string message, address to) , hash prototype string of the function sendMessage(string,address) with Keccak256. Then extract the first 4bytes “0xc48d6d5e”.

Get encoded function signatures with Web3.js

With Web3.js 1.0.0, encoded function signatures can be obtained by a utility function.

let encodedFunctionSignature = web3.eth.abi.encodeFunctionSignature('sendMessage(string,address)');
console.log(encodedFunctionSignature);
// => 0xc48d6d5e

Working demo

Related article

Reference

  • In this article, Web3.js version 0.20.6 is used.

Prepare ABI to interact with ERC20 Token Smart Contracts

  • ABI is an interface which represents what functions/state variables a smart contract has.
  • To interact with smart contracts with Web3.js, ABI is needed to call its functions and state variables.
  • In general, ABI contains all of functions/state variables which a smart contract…

Share your ideas with millions of readers.

Up to Solidity 0.4.21

  • Up to Solidity 0.4.21, constructor can be defined by the same name of its contract name.
  • However, this can possibly cause unintended bugs when contracts are renamed and their constructors are not renamed.
  • In Solidity, “contract” is almost the same as “class” in ordinal programming language.
  • A constructor name should…

  • MetaMask can manage multiple accounts (address).
  • This article might be useful if you want to know when a user changes account (address) in MetaMask.

Example code

web3 = new Web3(web3.currentProvider);
var account = '';
var accountInterval = setInterval(function() {
if (web3.eth.accounts[0] !== account) {
// MetaMask account is changed
account = web3.eth.accounts[0];
}
}, 300);

Working demo

  • You can utilize the web3’s eth.getGasPrice method to get median gas price of last few blocks.

Example code

var web3 = new Web3(new Web3.providers.HttpProvider('https://mainnet.infura.io'));
web3.eth.getGasPrice(function(error, result) {
console.log(result.toString(10));
var gasPriceInGwei = web3.fromWei(result, 'gwei');
console.log(gasPriceInGwei);
});

Working demo

https://piyolab.github.io/playground/ethereum/getCurrentGasPrice/

In this article, Web3.js 1.0.0 is used.

Install Web3.js

$ npm install web3 --save

Example code

let Web3 = require('Web3');

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