27

Web3 JavaScript Functions for Ethereum DApps

 3 years ago
source link: https://medium.com/better-programming/the-top-5-web3-javascript-functions-for-ethereum-dapps-7bc108bfd37
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

The Top 5 Web3 JavaScript Functions for Ethereum DApps

getAccounts, sendTransaction, estimateGas, and more

May 12 ·2min read

ZBjE3m7.jpg!web

Photo by Paul Esch-Laurent on Unsplash .

Web3 bridges the gap between the traditional internet and the Ethereum blockchain. It enables users to interact with your DApp through a browser. When using JavaScript for your front end, knowing the ins and outs of Web3JS is essential.

Here is a list of some of the most useful and commonly used functions in Web3JS.

web3.eth.getAccounts()

Use this function to get all of the available account addresses.

Usage:

let accounts = await web3.eth.getAccounts();
console.log(accounts[0]);

Or:

web3.eth.getAccounts().then(console.log);

web3.eth.sendTransaction()

Use this to send Ether from one account to another or a smart contract address. It requires a few parameters depending on the transaction. Possible parameters include from , to , value , gas , and more .

If you’re using this method as part of your front end, you can catch certain events that occur during submission to the blockchain. These events are transactionHash , receipt , confirmation , and error .

Usage:

web3.eth.estimateGas()

If you’re sending a transaction to a contract, you might have to estimate the gas. Pass the same parameters as web3.eth.sendTransaction() to receive the gas estimate. You can then add the result to the parameters in your web3.eth.sendTransaction() call.

Usage:

new web3.eth.Contract()

Use this function to load your deployed contract into your DApp so you can start interacting with it. Parameters include the ABI and the address the contract was deployed to.

Usage:

let contractInstance = new web3.eth.Contract(
    MyContract.abi,
    deployedAddress
);
await contractInstance.doSomething();

web3.utils.toWei()

Use this function to convert Ether values into Wei, the unit of value used by smart contracts.

Usage:

let weiValue = web3.utils.toWei("1", "ether");
...

Further Reading

If you’re interested in blockchain development, I write tutorials, walkthroughs, hints, and tips on how to get started and build a portfolio.

Check out some of these resources:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK