Search code examples
javascriptethereumweb3js

How to create a public key and private key using web3js?


I am learning to use web3js in this case to create an ethereum address and a private key to make a simple dapp.

Can anyone tell me to use this web3js?

My achievement recently studied to see the balance of ethereum and token ERC20.


Solution

  • <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script>
    
    <script>
      if (typeof web3 !== 'undefined') {
        web3 = new Web3(web3.currentProvider)
      } else {
        // Set the provider you want from Web3.providers
        web3 = new Web3(new Web3.providers.HttpProvider("https://mainnet.infura.io"))
      }
    
      console.log(web3.eth.accounts.create())
    </script>
    

    You'll get

    {
        address: "0xb8CE9ab6943e0eCED004cDe8e3bBed6568B2Fa01",
        privateKey: "0x348ce564d427a3311b6536bbcff9390d69395b06ed6c486954e971d960fe8709",
        signTransaction: function(tx){...},
        sign: function(data){...},
        encrypt: function(password){...}
    }