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?
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:
(3) Then use the following script to establish a connection to the RPC endpoint using
ethers.providers.JsonRpcProvider, and queryeth_blockNumberwith it: