Wallet Creation API
This API endpoint allows you to create a new wallet for a user or retrieve an existing wallet address. It ensures that each user has a unique wallet associated with their account.
Endpointβ
POST /api/wallet/ensure
Authenticationβ
This endpoint requires authentication. Ensure that the user is logged in and has a valid session.
Request Bodyβ
This endpoint does not require a request body. The user's ID is obtained from the authenticated session.
Responseβ
The API returns a JSON object with the following structure:
{
address: string;
}
Where address
is the Ethereum wallet address associated with the user.
Create or retrieve a wallet for the authenticated user:
const response = await fetch('/api/wallet/ensure', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const data = await response.json();
console.log(data.address); // The user's wallet address
Error Responsesβ
- The endpoint first checks if the user already has a wallet address stored in the database.
- If a wallet exists, it returns the existing address without creating a new one.
- If no wallet exists, it creates a new random wallet using ethers.js.
- The new wallet address and encrypted private key are stored in the user's document in the database.
- The wallet address is then returned to the client.
In the provided implementation, the private key is stored unencrypted for demonstration purposes. In a production environment, you MUST use a secure method to encrypt the private key before storing it in the database.
- Implement proper error handling in your client-side code to manage potential API errors.
- Consider implementing rate limiting to prevent abuse of this endpoint.
- Ensure that your database has appropriate access controls and encryption at rest to protect sensitive wallet information.
- Regularly audit and rotate encryption keys used for securing private keys.
- This API currently creates Ethereum-compatible wallets only.
- The wallet creation process is synchronous and may impact response times for users with slow connections.
Stay tuned for updates and feel free to provide feedback for improvements!