XRPL Mastra AI Template
A comprehensive Mastra.ai template for building XRP Ledger (XRPL) applications with AI agents, tools, and workflows. This template provides a complete foundation for creating intelligent XRPL applications with automated token issuance, account management, and transaction processing.
Overview
This template demonstrates how to build sophisticated XRPL applications using Mastra.ai's agent, tool, and workflow system. It includes:
- XRPL Client Management: Singleton pattern for efficient client connections
- Comprehensive XRPL Tools: Public methods, transactions, and wallet management
- Token Issuance Workflow: Complete automated token creation and distribution
- AI Agent Integration: Intelligent XRPL agent with detailed tool descriptions
- Type Safety: Full TypeScript support with Zod validation
Setup
-
Copy environment variables:
cp .env.example .env
-
Install dependencies:
npm install
-
Configure your API keys in
.env
(see Environment Variables section) -
Start development server:
npm run dev
Environment Variables
OPENAI_API_KEY
: Your OpenAI API key. Get one at OpenAI Platform
Usage
You can use the XRPL Agent to do several things that the XRP Ledger and xrpl.js SDK allows. For example:
- Creating accounts on mainnet, testnet and devnet
- Funding those accounts using the faucet on test networks
- Quering the XRP Ledger to retrieve any kind of data
- Submitting transactions such as a Payment or minting an NFT
Available Tools
The template includes comprehensive XRPL tools:
Public Methods
account_info
- Get account information and balancesaccount_lines
- Retrieve trust lines for an accountaccount_nfts
- Get NFT tokens owned by an accountaccount_objects
- Retrieve account-specific ledger objectsaccount_offers
- Get open offers for an accountaccount_tx
- Get transaction history for an accountaccount_channels
- Retrieve payment channels for an accountaccount_currencies
- Get currencies an account can send or receivegateway_balances
- Get balances held by gatewaysserver_info
- Get server information and statusfee
- Get current transaction fees
Transactions
AccountSet
- Configure account settings and flagsAMMCreate
- Create Automated Market MakersClawback
- Recover issued currenciesNFTokenMint
- Create new NFT tokensOfferCancel
- Cancel existing offersOfferCreate
- Create exchange offersPayment
- Send XRP or issued currenciesTrustSet
- Create or modify trust lines
Utilities
createWallet
- Generate new XRPL walletsfundWalletWithFaucet
- Fund wallets using testnet faucetscurrencyCodeToHex
- Convert currency codes to hex format
Customization
Adding New Transaction Tools
The template provides a factory pattern for creating new XRPL transaction tools with minimal boilerplate. Here's how to add a new transaction tool:
1. Create Transaction Schema
First, define the Zod schema for your transaction fields:
1// src/mastra/tools/transactions/your-transaction/your-transaction.types.ts
2import { z } from 'zod'
3import { xrplCommonFieldsSchema } from '../shared/common-fields'
4
5export const xrplYourTransactionFieldsSchema = z.object({
6 // Define your transaction-specific fields here
7 Amount: z.string().describe('Amount to transfer'),
8 Destination: z.string().describe('Destination account'),
9 // ... other fields
10})
11
12export const xrplYourTransactionSchema = xrplCommonFieldsSchema
13 .merge(xrplYourTransactionFieldsSchema)
14 .extend({ TransactionType: z.literal('YourTransactionType') })
2. Create the Transaction Tool
Use the factory to create your transaction tool:
1// src/mastra/tools/transactions/your-transaction/your-transaction.ts
2import { YourTransactionType } from 'xrpl'
3import { useTransactionToolFactory } from '../factory'
4import { xrplYourTransactionSchema } from './your-transaction.types'
5
6const { createTransactionTool } = useTransactionToolFactory({
7 inputSchema: xrplYourTransactionSchema,
8})
9
10export const submitYourTransactionTool = createTransactionTool({
11 toolId: 'submit-your-transaction',
12 description: `Submit a YourTransactionType transaction to the XRPL network.
13
14 ## Important Notes:
15 - Explain what this transaction does
16 - List any special requirements or limitations
17 - Include relevant XRPL documentation links`,
18 buildTransaction: params => {
19 const builtTransaction: YourTransactionType = {
20 TransactionType: 'YourTransactionType',
21 ...params,
22 }
23 return builtTransaction
24 },
25 validateTransaction: params => {
26 // Add any custom validation logic
27 if (!params.Amount) {
28 throw new Error('Amount is required')
29 }
30 },
31})
3. Example: Payment Transaction
Here's a real example from the template:
1// src/mastra/tools/transactions/payment/payment.ts
2import { Payment } from 'xrpl'
3import { useTransactionToolFactory } from '../factory'
4import { xrplPaymentSchema } from './payment.types'
5
6const { createTransactionTool } = useTransactionToolFactory({
7 inputSchema: xrplPaymentSchema,
8})
9
10export const submitPaymentTool = createTransactionTool({
11 toolId: 'submit-payment',
12 description: `Submit a Payment transaction to the XRPL network. A Payment transaction represents a transfer of value from one account to another. This is the only transaction type that can create new accounts by sending enough XRP to an unfunded address.
13
14## Important Notes:
15- Payment is the only transaction type that can create accounts
16- Cross-currency payments may involve multiple exchanges atomically
17- Partial payments can exploit integrations that assume exact delivery amounts`,
18 buildTransaction: payment => {
19 const builtPayment: Payment = {
20 ...payment,
21 Amount: payment.Amount ?? payment.DeliverMax,
22 }
23 return builtPayment
24 },
25 validateTransaction: params => {
26 if (params.Amount === undefined && params.DeliverMax === undefined) {
27 throw new Error('Provide Amount (API v1) or DeliverMax (API v2)')
28 }
29 },
30})
4. Factory Benefits
The transaction factory provides several benefits:
- Automatic Authentication: Handles seed/signature validation automatically
- Consistent Schema: Merges common fields (network, seed, signature) with your transaction fields
- Type Safety: Full TypeScript support with proper type inference
- Error Handling: Centralized error handling and validation
- Reduced Boilerplate: No need to repeat common transaction submission logic
5. Available Common Fields
All transaction tools automatically include these base fields:
network
: WebSocket URL for the XRPL networkseed
: Seed phrase for testnet/devnet accounts (optional)signature
: Pre-signed transaction signature (optional)
Either seed
or signature
must be provided for authentication.
6. Adding to Your Agent
After creating your tool, add it to the agent's tools object:
1// src/mastra/agents/xrpl-agent.ts
2import { submitYourTransactionTool } from '../tools/transactions/your-transaction/your-transaction'
3
4export const xrplAgent = new Agent({
5 // ... other config
6 tools: {
7 // ... existing tools
8 submitYourTransactionTool,
9 },
10})
Customizing Existing Tools
You can customize existing tools by:
- Modifying Descriptions: Update tool descriptions to better match your use case
- Adding Validation: Enhance validation logic for your specific requirements
- Extending Schemas: Add additional fields or constraints to existing schemas
- Custom Error Handling: Implement custom error messages and handling
Best Practices for Customization
- Follow Naming Conventions: Use consistent naming for files and exports
- Add Comprehensive Documentation: Include detailed descriptions and examples
- Validate Inputs: Always validate transaction parameters before submission
- Handle Errors Gracefully: Provide clear error messages for debugging
- Test Thoroughly: Test your custom tools on testnet before mainnet use
Supported Networks
By default, mainnet will be used, if you need to use another network, simply mention "testnet" or "devnet" in your prompt.
Token Issuance Workflow
The template includes a complete token issuance workflow that:
- Creates Wallets - Generates and funds issuer and holder wallets
- Configures Issuer - Sets account flags and domain (optional)
- Establishes Trust Lines - Creates trust lines for token acceptance
- Mints Tokens - Distributes tokens to all holders
Workflow Parameters
Parameter | Type | Description | Example |
---|---|---|---|
network | string | WebSocket URL for XRPL network | 'wss://s.altnet.rippletest.net:51233/' |
holders | number | Number of holder wallets to create | 3 |
trustline.currency | string | Currency code for the token | 'REWARDS' |
trustline.trustlineLimit | string | Trust line limit for each holder | '10000' |
issuerSettings.domain | string | Issuer domain (optional) | 'example.com' |
issuerSettings.flags | string[] | Account flags (optional) | ['asfDefaultRipple'] |
mintAmount | string | Amount of tokens to mint per holder | '1000' |
Best Practices
Security
- Always use testnet/devnet for development and testing
- Store wallet seeds securely in production
- Validate all inputs before processing
- Use appropriate account flags for your use case
Code Quality
- Follow TypeScript best practices
- Use Zod for input validation
- Add comprehensive error handling
- Include detailed documentation and comments