1

​ I would like to interact with the Hedera Testnet using web3.js or ethers.js. How can I do this? ​ I have previously interacted with Hedera Testnet using hedera-sdk-js, for example using the following code: ​

import {
    AccountBalanceQuery, 
    Client
} from "@hashgraph/sdk";
​
const client = new Client({
    network: "testnet"
});
​
const accountId = '0.0.3996280';
const balance = await new AccountBalanceQuery()
    .setAccountId(accountId)
    .execute(client);
    
console.log(
    `Balance of ${accountId} in Tinybars:`,
    balance.hbars.toTinybars().toString(10)
);
​

​ How can I do the equivalent of the above in web3.js/ ethers.js?

Defi Girl
  • 186
  • 4

3 Answers3

3

To connect using ethers.js

(1) First, obtain an RPC endpoint URL, which is detailed over at How can I connect to Hedera Testnet over RPC?. ​ Once you have gotten that, substitute ${RPC_URL} in the code examples below with that value.

(2)​ Install ethers.js: ​

npm install ethers@v5

(3)​ Then use the following script to establish a connection to the RPC endpoint using ethers.providers.JsonRpcProvider, and query eth_blockNumber with it: ​

import { ethers } from 'ethers';
​
const web3Provider = new ethers.providers.JsonRpcProvider({
    url: '${RPC_URL}',
    headers: {
        'Access-Control-Allow-Origin': '*',
    },
});
​
async function main() {
    web3Provider.getBlockNumber()
        .then((blockNumber) => {
            console.log('block number', blockNumber);
        })
        .catch(console.error);
​
    web3Provider.getBalance(
        '0x00000000000000000000000000000000003cfa78')
        .then((balance) => {
            console.log('balance', balance.toBigInt());
        })
        .catch(console.error);
}
​
main();
​

bguiz
  • 27,371
  • 47
  • 154
  • 243
2

@bguiz answer should do it. There is also this tutorial that shows how you can do this with ethers.js along with a wallet like MetaMask.

https://youtu.be/mhqQToUEMBs?t=274

Here's a link to the code from the video, which is a function that you can reuse to connect a Hedera network (testnet/mainnet/previewnet) using Ethers. https://github.com/ed-marquez/hedera-example-metamask-counter-dapp/blob/master/src/components/hedera/walletConnect.js

The code is also shown below.

  1. You start by creating a new ethers provider

  2. Then defined the chainId of the network you want to connect to (testnet/mainnet/previewnet). If you're using a wallet like MetaMask, you can optionally switch to a Hedera network programatically, and then you can specify the JSON-RPC and network explorer URLs

  3. Obtain the selected account

    import { ethers } from "ethers";
     const network = "testnet";
    
     async function walletConnectFcn() {
         console.log(`\n=======================================`);
    
     // ETHERS PROVIDER
     const provider = new ethers.providers.Web3Provider(window.ethereum, "any");
    
     // SWITCH TO HEDERA TEST NETWORK
     console.log(`- Switching network to the Hedera ${network}...`);
     let chainId;
     if (network === "testnet") {
         chainId = "0x128";
     } else if (network === "previewnet") {
         chainId = "0x129";
     } else {
         chainId = "0x127";
     }
    
     await window.ethereum.request({
         method: "wallet_addEthereumChain",
         params: [
             {
                 chainName: `Hedera ${network}`,
                 chainId: chainId,
                 nativeCurrency: { name: "HBAR", symbol: "ℏℏ", decimals: 18 },
                 rpcUrls: [`https://${network}.hashio.io/api`],
                 blockExplorerUrls: [`https://hashscan.io/${network}/`],
             },
         ],
     });
     console.log("- Switched ✅");
    
     // CONNECT TO ACCOUNT
     console.log("- Connecting wallet...");
     let selectedAccount;
     await provider
         .send("eth_requestAccounts", [])
         .then((accounts) => {
             selectedAccount = accounts[0];
             console.log(`- Selected account: ${selectedAccount} ✅`);
         })
         .catch((connectError) => {
             console.log(`- ${connectError.message.toString()}`);
             return;
         });
    
     return [selectedAccount, provider, network]; 
    

    }

    export default walletConnectFcn;

Ed Marquez
  • 488
  • 1
  • 10
0

To connect using web3.js

(1) First, obtain an RPC endpoint URL, which is detailed over at How can I connect to Hedera Testnet over RPC?. ​ Once you have gotten that, substitute ${RPC_URL} in the code examples below with that value.

(2) Install web3.js: ​

npm install web3

​ (3) Then use the following script to establish a connection to the RPC endpoint using Web3.providers.HttpProvider, and query eth_blockNumber with it: ​

import Web3 from 'web3';
​
const web3Provider = new Web3(new Web3.providers.HttpProvider('${RPC_URL}'), {
    headers: [{
        name: 'Access-Control-Allow-Origin', value: '*'
    }],
    keepalive: true,
    withCredentials: false,
});
​
async function main() {
    web3Provider.eth.getBlockNumber()
        .then((blockNumber) => {
            console.log('block number', blockNumber);
        })
        .catch(console.error);
​
    web3Provider.eth.getBalance(
        '0x00000000000000000000000000000000003cfa78')
        .then((balance) => {
            console.log('balance', balance);
        })
        .catch(console.error);
}
​
main();
​
bguiz
  • 27,371
  • 47
  • 154
  • 243