Skip to main content

Wallet Balance API

This API endpoint allows authenticated users to retrieve the balance of their associated Ethereum wallet on the Polygon network.

Endpoint​

GET /api/wallet/balance

Authentication​

This endpoint requires authentication. Ensure that the user is logged in and has a valid session.

Request​

This endpoint does not require any parameters in the request body or query string. The user's information is obtained from the authenticated session.

Response​

The API returns a JSON object with the following structure:

{
address: string;
balance: string;
}

Where:

  • address is the Ethereum wallet address associated with the user.
  • balance is the current balance of the wallet in Ether (ETH), formatted as a string.
Usage Example

Retrieve the wallet balance for the authenticated user:

const response = await fetch('/api/wallet/balance', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
console.log(data.address); // The user's wallet address
console.log(data.balance); // The current balance in ETH

Error Responses​

The API may return the following error responses:

  • 401 Unauthorized: If the user is not authenticated.
  • 404 Not Found: If the authenticated user does not have an associated wallet.
  • 500 Internal Server Error: If there's an error fetching the balance from the Polygon network.
Implementation Details
  1. The endpoint first checks if the user is authenticated using the auth() function.
  2. It then retrieves the user's data from the Firebase Admin database.
  3. If the user has an associated wallet address, it uses the Polygon RPC URL to create an Ethereum provider.
  4. The provider is used to fetch the current balance of the wallet.
  5. The balance is formatted from Wei to Ether using ethers.formatEther().
  6. Both the wallet address and formatted balance are returned to the client.
Security Note

Ensure that the POLYGON_RPC_URL environment variable is securely stored and not exposed to the client-side code.

Best Practices
  1. Implement proper error handling in your client-side code to manage potential API errors.
  2. Consider implementing rate limiting to prevent abuse of this endpoint.
  3. Cache the balance results for a short period to reduce load on the Polygon RPC endpoint and improve response times.
  4. Monitor the Polygon RPC endpoint for any issues or downtime that might affect your application.
Limitations
  1. This API currently only supports checking balances on the Polygon network.
  2. The balance is returned in Ether (ETH) and does not include information about other tokens the wallet might hold.
  3. The accuracy of the balance depends on the responsiveness and current state of the Polygon network.

Stay tuned for updates and feel free to provide feedback for improvements!