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.
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.
- The endpoint first checks if the user is authenticated using the
auth()
function. - It then retrieves the user's data from the Firebase Admin database.
- If the user has an associated wallet address, it uses the Polygon RPC URL to create an Ethereum provider.
- The provider is used to fetch the current balance of the wallet.
- The balance is formatted from Wei to Ether using
ethers.formatEther()
. - Both the wallet address and formatted balance are returned to the client.
Ensure that the POLYGON_RPC_URL
environment variable is securely stored and not exposed to the client-side code.
- Implement proper error handling in your client-side code to manage potential API errors.
- Consider implementing rate limiting to prevent abuse of this endpoint.
- Cache the balance results for a short period to reduce load on the Polygon RPC endpoint and improve response times.
- Monitor the Polygon RPC endpoint for any issues or downtime that might affect your application.
- This API currently only supports checking balances on the Polygon network.
- The balance is returned in Ether (ETH) and does not include information about other tokens the wallet might hold.
- 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!