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?
(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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With