Skip to main content

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.

Usage Example

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​

Implementation Details
  1. The endpoint first checks if the user already has a wallet address stored in the database.
  2. If a wallet exists, it returns the existing address without creating a new one.
  3. If no wallet exists, it creates a new random wallet using ethers.js.
  4. The new wallet address and encrypted private key are stored in the user's document in the database.
  5. The wallet address is then returned to the client.
Security Note

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.

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. Ensure that your database has appropriate access controls and encryption at rest to protect sensitive wallet information.
  4. Regularly audit and rotate encryption keys used for securing private keys.
Limitations
  1. This API currently creates Ethereum-compatible wallets only.
  2. 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!