Account Abstraction for RESTful API with Backend Session
In this guide, we will walk through building a RESTful API app with session management using the Abstraxion Core library, demonstrating how to create a web2 user experience without any web3 interactive behavior in frontend. It also includes the Abstraxion account and gasless transaction experience for users, but all the blockchain related implementation will be handled in the backend.
To better understand Account Abstraction you can visit theIntroduction to Account Abstraction page.
A fully functional demo of this app is also available in the Xion.js repository.
Requirements
Before getting started, ensure you have the following installed:
Node.js (LTS version recommended) – Required for running the development environment and installing dependencies.
pnpm – Package manager for efficient dependency management.
Git – Version control system.
Project Setup
1. Initialize the Project
Create a new Next.js project with TypeScript:
npx create-next-app@latest backend-session-app --typescript --tailwind --eslint --app --src-dir --import-alias "@/*"
cd backend-session-app2. Install Dependencies
Install the required dependencies for the backend session management:
3. Project Structure
You can adjust your project structure like this:
Environment Configuration
1. Environment Variables
Create a .env.local file in your project root:
2. Generate Encryption Key
Create a script to generate a secure encryption key:
Run the script:
Database Setup
1. Prisma Configuration
Create a prisma/schema.prisma file:
2. Initialize Database
AbstraxionBackend Library Implementation
We have implemented a version of the AbstraxionBackend library that you can use in your project.
You can directly copy the backend folder from the xion.js repository (Folder Here). In future, we may move this library to a separate package.
In the following sections, we will use @/lib/xion/backend to refer to the AbstraxionBackend library.
AbstraxionBackend Integration
1. Database Adapter
Create the database adapter that implements the BaseDatabaseAdapter interface from the AbstraxionBackend library:
2. AbstraxionBackend Configuration
Create the main configuration file:
Authentication Configuration
NextAuth Setup
Set up NextAuth for user authentication:
Request Validation
The demo uses Zod for request validation. For detailed validation schemas and implementation, refer to the validation.ts file in the demo repository.
RESTful API Endpoints
API Utilities
Before implementing the API endpoints, it's important to understand the utility functions used throughout the implementation:
createApiWrapper- A wrapper function that encapsulates Next.js API routes with common functionality including request validation, rate limiting, error handling, and response formatting. For detailed implementation, refer to the api-wrapper.ts file in the demo repository.requireAuth- A NextAuth.js middleware function that handles user authentication and session validation for API routes. It ensures that only authenticated users can access protected endpoints. For detailed implementation, refer to the auth-middleware.ts file in the demo repository.
1. Wallet Connection Endpoint
Create the wallet connection API:
2. Wallet Status Endpoint
Create the wallet status check API:
3. Wallet Disconnect Endpoint
Create the wallet disconnect API:
4. XION MetaAccount Authentication Callback Handler
Create the OAuth callback handler:
5. Transaction Endpoint
Create a transaction sending endpoint:
Note: For this example, we are using the
MsgSendmessage to send XION tokens. So please make sure in your treasury permission, you have granted theSend Tokenpermission. Learn more about how to grant permissions.
Testing Your API
Basic API Testing
You can test your API endpoints using curl or any HTTP client:
Deployment
Production Environment Variables
Create production environment variables:
Build and Deploy
API Documentation
Endpoints Summary
POST
/api/wallet/connect
Initiate wallet connection
Required
GET
/api/wallet/status
Check wallet status
Required
DELETE
/api/wallet/disconnect
Disconnect wallet
Required
POST
/api/wallet/transaction/send
Send transaction
Required
GET
/api/callback/grant_session
OAuth callback handler
None
Response Format
All API responses follow this format:
Security Considerations
Encryption
All sensitive data (private keys) is encrypted using AES-256-CBC
Encryption keys are generated securely and stored in environment variables
Each encryption operation uses a unique IV for security
Session Management
Automatic key rotation before expiry
Configurable refresh threshold
Background monitoring service for expired sessions
Troubleshooting
Common Issues
Database Connection Errors
Ensure
DATABASE_URLis correctly setCheck database server is running
Verify database permissions
Encryption Key Issues
Ensure
ENCRYPTION_KEYis base64 encodedKey must be exactly 32 bytes (256 bits)
Use the provided script to generate keys
XION Network Issues
Verify
XION_NETWORKis correctCheck network connectivity
Ensure treasury address is valid
Session Key Problems
Check
SESSION_KEY_EXPIRY_MSconfigurationVerify
REFRESH_THRESHOLD_MSsettings
Next Steps
Now that you have a fully functional RESTful API with account abstraction and backend session management, you can:
Extend the API with additional endpoints for specific use cases
Add a frontend to interact with your API
Implement additional security features like 2FA or biometric authentication
Scale the application with load balancers and multiple instances
This implementation provides a solid foundation for building Web3 applications with Web2 user experience, leveraging XION's account abstraction capabilities while maintaining security and scalability.
For more detailed implementation examples, comprehensive error handling, advanced features, and complete source code, please refer to the backend-session demo repository.
Last updated
Was this helpful?