Connect a Frontend

Developers can use any popular Ethereum based libraries to interact with the blockchain network. Listed below are code samples using some of the most commonly used libraries.

Each example shows how to read the latest block number of the CrossFI Chain. You can find the link to the documenation to each library to find other methods such as signing transactions and interacting with smart contracts.

EthersJS

Ethers.js is a compact Javascript library used for interacting with the Ethereum blockchain and other EVM compatible chains.

const { ethers } = require("ethers");

// URL of the RPC for the CrossFi Testnet 
const providerUrl = "https://rpc.testnet.ms";

// Creating a provider to interact with the blockchain

const provider = new ethers.JsonRpcProvider(providerUrl);
async function main() {
	// Getting the current block number as a test of the connection
	const blockNumber = await provider.getBlockNumber();
	console.log(`Current block number: ${blockNumber}`);
}

main().catch((error) => {
	console.error("Error connecting to the blockchain:", error);
});

Viem

Viem is a TypeScript library that offers type-safe modules for interacting with the Ethereum and other EVM compatible chains.

import { defineChain, createPublicClient, http } from 'viem';

export const crossfi = defineChain({
  id: 4157,
  name: 'CrossFi Testnet',
  nativeCurrency: {
    decimals: 18,
    name: 'XFI',
    symbol: 'XFI',
  },
  rpcUrls: {
    default: {
      http: ['https://rpc.testnet.ms'],
    },
  },
  blockExplorers: {
    default: { name: 'Explorer', url: 'https://scan.testnet.ms' },
  },
});

const client = createPublicClient({
  chain: crossfi,
  transport: http(),
});

const blockNumber = await client.getBlockNumber();

export default `Block number: ${blockNumber}`;

ThirdWeb

Thirdweb is a developer platform that offers a suite of tools including wallets, contract deployment and libraries to interact with any EVM chain.

Here is a code example using their TypeScript SDK to read the balance of a wallet address:

import { CrossfiTestnet } from "@thirdweb-dev/chains";
import { ThirdwebSDK } from "@thirdweb-dev/sdk";

const sdk = new ThirdwebSDK(CrossfiTestnet, {
  clientId: "YOUR_clientId",
});

const getWalletBalance = async () => {
    const walletBalance = await sdk.getBalance("YOUR_WALLET_ADDRESS");
    console.log(walletBalance);
};

getWalletBalance();

Last updated