Rise In Logo

Build on Algorand

Integrating Wallet Connection via @perawallet/connect

Integrating wallet connection via @perawallet/connect

Interacting with Algorand Networks

When developing an Algorand-based application, simply connecting a wallet is not enough. To ensure your application works consistently across different environments (development, testing, and production), it's essential to be able to switch between networks effectively.


Prompt: // Create a React component that demonstrates switching between LocalNet, TestNet, and MainNet using AlgoKit’s network configuration.


AI Output (Example React Component):

This component allows users to switch between different Algorand networks and perform simple on-chain operations such as sending a test transaction or fetching account info.

import { useWallet } from '@txnlab/use-wallet'
import { useState, useEffect } from 'react'
import algosdk from 'algosdk'

const networks = {
 localnet: {
  name: 'LocalNet',
  server: 'http://localhost',
  port: 4001,
  token: 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa',
  explorer: 'http://localhost:8980'
 },
 testnet: {
  name: 'TestNet',
  server: 'https://testnet-api.algonode.cloud',
  port: '',
  token: '',
  explorer: 'https://testnet.algoexplorer.io'
 },
 mainnet: {
  name: 'MainNet',
  server: 'https://mainnet-api.algonode.cloud',
  port: '',
  token: '',
  explorer: 'https://algoexplorer.io'
 }
}

function NetworkSwitcher() {
 const { activeAccount, signTransactions } = useWallet()
 const [selectedNetwork, setSelectedNetwork] = useState('localnet')
 const [algodClient, setAlgodClient] = useState(null)
 const [accountInfo, setAccountInfo] = useState(null)

 useEffect(() => {
  const network = networks[selectedNetwork]
  const client = new algosdk.Algodv2(network.token, network.server, network.port)
  setAlgodClient(client)
 }, [selectedNetwork])

 const fetchAccountInfo = async () => {
  if (!algodClient || !activeAccount) return
  try {
   const info = await algodClient.accountInformation(activeAccount.address).do()
   setAccountInfo(info)
  } catch (err) {
   console.error('Failed to fetch account info:', err)
  }
 }

 const sendTransaction = async () => {
  if (!algodClient || !activeAccount) return
  try {
   const suggestedParams = await algodClient.getTransactionParams().do()
   const txn = algosdk.makePaymentTxnWithSuggestedParamsFromObject({
    from: activeAccount.address,
    to: activeAccount.address,
    amount: 1000,
    suggestedParams
   })

   const signedTxns = await signTransactions([txn])
   const { txId } = await algodClient.sendRawTransaction(signedTxns[0]).do()
   console.log('Transaction sent with ID:', txId)
  } catch (err) {
   console.error('Transaction failed:', err)
  }
 }

 return (
  <div>
   <h4>Select Network</h4>
   <div>
    {Object.entries(networks).map(([key, network]) => (
     <button
      key={key}
      onClick={() => setSelectedNetwork(key)}
      style={{
       backgroundColor: selectedNetwork === key ? '#007bff' : '#e0e0e0',
       margin: '4px',
       padding: '8px 16px'
      }}
     >
      {network.name}
     </button>
    ))}
   </div>

   <p>Active Network: {networks[selectedNetwork].name}</p>

   {activeAccount && (
    <div>
     <p>Connected Wallet: {activeAccount.address}</p>
     <button onClick={fetchAccountInfo}>Check Account Info</button>
     <button onClick={sendTransaction}>Send Test Transaction</button>

     {accountInfo && (
      <div>
       <p>Balance: {accountInfo.amount / 1_000_000} ALGO</p>
       <p>Min Balance: {accountInfo['min-balance'] / 1_000_000} ALGO</p>
      </div>
     )}
    </div>
   )}
  </div>
 )
}

export default NetworkSwitcher



Network Environments Overview

AlgoKit supports development across three main Algorand networks:

  • Localnet: A local development environment for fast prototyping and testing. No real ALGO is needed. Ideal for debugging and iterative smart contract development.
  • Testnet: A public test environment that simulates real network behavior. Useful for integration testing and validating application logic under more realistic conditions. Requires test tokens, which can be claimed via a dispenser.
  • Mainnet: The live Algorand blockchain where real assets are involved. Used for deploying production-ready applications. Transactions here carry real value, so proper security, monitoring, and testing practices are essential.

Best Practices

  • Start with LocalNet for rapid development
  • Validate functionality on Testnet
  • Deploy cautiously to Mainnet after thorough testing
  • Use consistent configuration strategies across environments
  • Implement robust error handling and fallback logic per network


Comments

You need to enroll in the course to be able to comment!

Stay in the know

Never miss updates on new programs and opportunities.

Rise In Logo

Rise together in web3!

Disclaimer: The information, programs, and events provided on https://risein.com is strictly for upskilling and networking purposes related to the technical infrastructure of blockchain platforms. We do not provide financial or investment advice, nor do we make any representations regarding the value, profitability, or future price of any blockchain or cryptocurrency. Users are encouraged to conduct their own research and consult with licensed financial professionals before engaging in any investment activities. https://risein.com disclaims any responsibility for financial decisions made by users based on the information provided here.