Documentation

Learn how to integrate RelayXplore into your DApps

Introduction to RelayXplore

Learn about the RelayXplore relayer system and how it can benefit your DApp

RelayXplore is a relayer system that enables DApps to offer gasless transactions for their users. It introduces a provider funding model, allowing DApp developers to deposit/withdraw funds into a relayer account to pay for gas and access the service through a subscription-based SDK authenticated via API keys.

How RelayXplore Works

Traditional blockchain transactions require end-users to pay gas fees, which can be a significant barrier to adoption, especially for new users. RelayXplore solves this problem by allowing DApp developers to cover these costs on behalf of their users.

Traditional Transaction Flow

  1. User initiates a transaction in DApp
  2. User must have native tokens for gas
  3. User signs transaction with their wallet
  4. Transaction is sent to the blockchain
  5. User pays gas fees from their wallet

RelayXplore Transaction Flow

  1. User initiates a transaction in DApp
  2. DApp sends transaction to RelayXplore
  3. User signs a message (not a transaction)
  4. RelayXplore submits the transaction to the blockchain
  5. Gas fees are paid from the DApp's funded account

Key Benefits

  • Improve user experience by removing the gas fee barrier
  • Simplify onboarding for new users unfamiliar with blockchain
  • Maintain control over transaction costs through the provider funding model
  • Easy integration with our SDK
  • Support for multiple blockchain networks
  • Detailed analytics and monitoring tools

Supported Networks

Ethereum Mainnet
Polygon
Arbitrum
Optimism
Base
Avalanche (Beta)

Quick Start

Get up and running with RelayXplore in minutes

This quick start guide will help you integrate RelayXplore into your DApp in just a few minutes. Follow these steps to enable gasless transactions for your users.

1. Create an Account

First, you'll need to create an account on the RelayXplore platform. Visit dashboard.relayxplore.com to sign up.

2. Generate an API Key

After creating an account, generate an API key from the dashboard. This key will be used to authenticate your requests to the RelayXplore API.

3. Install the SDK

bash
bash
npm install @relayxplore/sdk

4. Initialize the SDK

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';

// Initialize the SDK with your API key
const relay = new RelayXplore({
  apiKey: 'your-api-key',
  network: 'mainnet', // or 'polygon', 'arbitrum', 'optimism', 'base'
});

5. Fund Your Account

Before sending transactions, you'll need to fund your RelayXplore account. You can do this from the dashboard by depositing ETH or other native tokens depending on the network.

6. Send a Gasless Transaction

javascript
javascript
// Example: Send a gasless transaction
const transaction = {
  to: '0x742d35Cc6634C0532925a3b844Bc454e4438f44e',
  data: '0x...',  // Contract method call data
  value: '0',     // Amount of ETH to send
};

// Send the transaction through the relayer
const result = await relay.sendTransaction(transaction);
console.log('Transaction hash:', result.hash);

Pro Tip: Environment Variables

Store your API key in an environment variable to keep it secure. Never expose your API key in client-side code.

javascript
javascript
// Server-side code
const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

Powerful Documentation Search

Find exactly what you need with our comprehensive search functionality

Our documentation search helps you quickly find the information you need to integrate RelayXplore into your DApps.

  • Search across all documentation pages
  • Find code examples and implementation guides
  • Access API references and troubleshooting tips

Installation

Detailed instructions for installing and configuring the RelayXplore SDK

Requirements

  • Node.js v14 or higher
  • An active RelayXplore account with API keys
  • Funded relayer account

Installation Methods

bash
bash
npm install @relayxplore/sdk

Configuration

javascript
javascript
// Configure the SDK with your project settings
import { RelayXplore } from '@relayxplore/sdk';

const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
  timeout: 30000, // Optional: request timeout in ms
  maxRetries: 3,  // Optional: number of retry attempts
});

Configuration Options

OptionTypeDefaultDescription
apiKeystring-Your RelayXplore API key (required)
networkstring'mainnet'Blockchain network to use (mainnet, polygon, arbitrum, optimism, base)
timeoutnumber30000Request timeout in milliseconds
maxRetriesnumber3Maximum number of retry attempts for failed requests
baseUrlstring'https://api.relayxplore.com'Base URL for the RelayXplore API
debugbooleanfalseEnable debug logging

Framework-Specific Setup

Authentication

Learn how to authenticate your DApp with RelayXplore

API Keys

RelayXplore uses API keys to authenticate requests. You can generate API keys from your dashboard after creating an account.

API Key Types

Development

For testing and development environments. Limited rate limits and features.

Testing

For staging and QA environments. Moderate rate limits and features.

Production

For production environments. Higher rate limits and full feature access.

Securing Your API Keys

Always keep your API keys secure and never expose them in client-side code. Use environment variables to store your API keys and access them in your server-side code.

javascript
javascript
// Server-side code (e.g., Next.js API route)
import { RelayXplore } from '@relayxplore/sdk';

export async function POST(req) {
  const relay = new RelayXplore({
    apiKey: process.env.RELAYXPLORE_API_KEY,
    network: 'mainnet',
  });
  
  // Process the request
  // ...
}

Security Warning

Never include your API key in client-side code, frontend applications, or public repositories. Anyone with your API key can use your RelayXplore account and spend your funds.

API Key Rotation

It's a good practice to rotate your API keys periodically. You can generate new API keys from your dashboard and update your applications accordingly. Make sure to revoke old keys after transitioning to new ones.

Authentication Flow

  1. Generate an API key from the RelayXplore dashboard
  2. Store the API key securely in your server environment
  3. Initialize the SDK with your API key
  4. The SDK will automatically include your API key in all requests to the RelayXplore API

Funding Your Account

Learn how to fund your RelayXplore account to cover gas costs

Before you can start using RelayXplore to send gasless transactions, you need to fund your account with the native token of the blockchain network you're using (e.g., ETH for Ethereum, MATIC for Polygon).

Funding Methods

Dashboard Deposit

The simplest way to fund your account is through the RelayXplore dashboard. You can deposit funds directly using your wallet.

  1. Log in to your RelayXplore dashboard
  2. Navigate to the "Funding" section
  3. Click on "Add Funds"
  4. Connect your wallet and specify the amount to deposit
  5. Confirm the transaction in your wallet

Direct Transfer

You can also fund your account by directly transferring tokens to your unique RelayXplore deposit address.

  1. Log in to your RelayXplore dashboard
  2. Navigate to the "Funding" section
  3. Find your unique deposit address
  4. Send tokens to this address from any wallet or exchange
  5. Funds will be credited to your account after confirmation

Managing Your Balance

You can monitor your account balance and transaction history in the RelayXplore dashboard. The dashboard provides detailed information about your deposits, withdrawals, and gas usage.

Balance Alerts

Set up balance alerts to receive notifications when your account balance falls below a specified threshold. This helps ensure your service remains uninterrupted.

Email Alerts

Receive email notifications when your balance is low

Webhook Notifications

Integrate with your systems for automated monitoring

Auto-Funding

Set up automatic deposits when balance is low (coming soon)

Withdrawing Funds

You can withdraw funds from your RelayXplore account at any time. Withdrawals are processed within 24 hours and sent to your specified wallet address.

javascript
javascript
// Check your account balance programmatically
const balance = await relay.getAccountBalance();
console.log('Account balance:', balance);

// You can also check the minimum required balance
const minBalance = await relay.getMinimumRequiredBalance();
console.log('Minimum required balance:', minBalance);

// If your balance is low, you might want to notify your team
if (parseFloat(balance) < parseFloat(minBalance) * 2) {
  console.warn('Account balance is running low!');
}

Implementing Gasless Transactions

A comprehensive guide to implementing gasless transactions in your DApp

How Gasless Transactions Work

Gasless transactions allow users to interact with your DApp without needing to pay for gas. Instead, the DApp provider (you) covers the gas costs through the RelayXplore relayer system.

Technical Overview

RelayXplore uses meta-transactions to enable gasless transactions. Here's how it works:

  1. User signs a message: Instead of signing a transaction, the user signs a message containing the transaction details.
  2. Message is sent to RelayXplore: Your DApp sends the signed message to the RelayXplore API.
  3. RelayXplore verifies the signature: The API verifies that the message was signed by the user.
  4. RelayXplore submits the transaction: If the signature is valid, RelayXplore submits the transaction to the blockchain.
  5. Gas is paid from your account: The gas fees are deducted from your RelayXplore account balance.

Implementation Steps

  1. Initialize the RelayXplore SDK with your API key
  2. Create a transaction object with the necessary parameters
  3. Send the transaction through the relayer
  4. Handle the response and provide feedback to the user

Example Implementation

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';

// Initialize the SDK
const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

// Function to send a gasless transaction
async function sendGaslessTransaction(to, data, value = '0') {
  try {
    // Create the transaction object
    const transaction = {
      to,
      data,
      value,
    };
    
    // Send the transaction through the relayer
    const result = await relay.sendTransaction(transaction);
    
    // Return the transaction hash
    return {
      success: true,
      hash: result.hash,
    };
  } catch (error) {
    console.error('Error sending gasless transaction:', error);
    return {
      success: false,
      error: error.message,
    };
  }
}

Contract Interactions

You can use RelayXplore to interact with smart contracts on behalf of your users. Here's an example of how to call a contract method:

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';
import { ethers } from 'ethers';

// Initialize the SDK
const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

// Function to interact with a contract
async function callContractMethod(contractAddress, abi, methodName, methodArgs) {
  try {
    // Create a contract interface
    const iface = new ethers.utils.Interface(abi);
    
    // Encode the function call
    const data = iface.encodeFunctionData(methodName, methodArgs);
    
    // Create the transaction object
    const transaction = {
      to: contractAddress,
      data,
      value: '0',
    };
    
    // Send the transaction through the relayer
    const result = await relay.sendTransaction(transaction);
    
    return {
      success: true,
      hash: result.hash,
    };
  } catch (error) {
    console.error('Error calling contract method:', error);
    return {
      success: false,
      error: error.message,
    };
  }
}

// Example usage
const contractAddress = '0x123...';
const abi = [...]; // Contract ABI
const methodName = 'transfer';
const methodArgs = ['0x456...', ethers.utils.parseEther('1.0')];

const result = await callContractMethod(contractAddress, abi, methodName, methodArgs);
console.log(result);

Advanced Features

Transaction Batching

Batch multiple transactions together to reduce gas costs and improve efficiency.

javascript
javascript
// Batch multiple transactions
const batch = [
  {
    to: '0x123...',
    data: '0x...',
    value: '0',
  },
  {
    to: '0x456...',
    data: '0x...',
    value: '0',
  },
];

const result = await relay.sendBatchTransaction(batch);
console.log('Batch transaction hash:', result.hash);

Transaction Scheduling

Schedule transactions to be executed at a specific time in the future.

javascript
javascript
// Schedule a transaction
const transaction = {
  to: '0x123...',
  data: '0x...',
  value: '0',
  executeAt: new Date(Date.now() + 3600000), // 1 hour from now
};

const result = await relay.scheduleTransaction(transaction);
console.log('Scheduled transaction ID:', result.id);

Managing API Keys

Learn how to create, use, and manage your RelayXplore API keys

API keys are used to authenticate your requests to the RelayXplore API. This section covers how to create, manage, and secure your API keys.

Creating API Keys

You can create API keys from the RelayXplore dashboard. Each key can be configured with specific permissions and rate limits.

  1. Log in to your RelayXplore dashboard
  2. Navigate to the "API Keys" section
  3. Click on "Generate New API Key"
  4. Provide a name for your key and select the environment (development, testing, production)
  5. Configure permissions and rate limits as needed
  6. Click "Create" to generate the key

Important

Your API key will only be displayed once when it's created. Make sure to copy it and store it securely. If you lose your key, you'll need to generate a new one.

API Key Permissions

You can configure your API keys with specific permissions to limit what actions they can perform. This is useful for creating keys with the minimum necessary permissions for different parts of your application.

PermissionDescription
ReadCan read account information, transaction history, and balance
WriteCan send transactions and interact with contracts
AdminCan manage API keys, account settings, and billing information

Revoking API Keys

If an API key is compromised or no longer needed, you should revoke it immediately. Revoked keys cannot be used to authenticate requests.

  1. Log in to your RelayXplore dashboard
  2. Navigate to the "API Keys" section
  3. Find the key you want to revoke
  4. Click on the "Revoke" button
  5. Confirm the action

API Key Best Practices

  • Use different API keys for different environments (development, testing, production)
  • Limit API key permissions to only what is necessary
  • Store API keys securely using environment variables or a secrets manager
  • Rotate API keys periodically to reduce the risk of compromise
  • Monitor API key usage to detect unusual activity
  • Revoke unused or compromised API keys immediately

Programmatic API Key Management

You can also manage your API keys programmatically using the RelayXplore Management API. This is useful for automating key rotation and management.

javascript
javascript
// Example: Create a new API key programmatically
const response = await fetch('https://api.relayxplore.com/v1/api-keys', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer YOUR_ADMIN_API_KEY',
  },
  body: JSON.stringify({
    name: 'Production API Key',
    environment: 'production',
    permissions: ['read', 'write'],
  }),
});

const data = await response.json();
console.log('New API key:', data.key);

Monitoring Usage

Track and analyze your RelayXplore usage and transactions

RelayXplore provides comprehensive monitoring tools to help you track your usage, analyze transaction patterns, and optimize your costs.

Dashboard Analytics

The RelayXplore dashboard provides real-time analytics on your account usage, including:

  • Transaction volume and success rates
  • Gas usage and costs
  • API key usage and rate limit consumption
  • Account balance and funding history

Transaction Metrics

  • Total transactions sent
  • Success and failure rates
  • Average gas used per transaction
  • Transaction types and patterns

Cost Analysis

  • Total gas costs
  • Cost per transaction
  • Cost trends over time
  • Cost breakdown by DApp or API key

Programmatic Monitoring

You can also monitor your usage programmatically using the RelayXplore API. This allows you to integrate RelayXplore metrics into your own monitoring systems.

javascript
javascript
// Get transaction history
const transactions = await relay.getTransactions({
  limit: 10,
  offset: 0,
  status: 'success', // 'success', 'pending', 'failed'
});

console.log('Recent transactions:', transactions);

// Get usage metrics
const metrics = await relay.getUsageMetrics({
  startDate: '2023-04-01',
  endDate: '2023-04-30',
});

console.log('Monthly usage metrics:', metrics);

Alerts and Notifications

Set up alerts to be notified of important events, such as:

  • Low account balance
  • High transaction failure rates
  • Unusual transaction patterns
  • API rate limit warnings

Alerts can be delivered via email, webhook, or Slack integration.

Transaction Explorer

The transaction explorer in the RelayXplore dashboard allows you to search, filter, and analyze your transactions in detail. You can:

  • View transaction details, including gas used, status, and timestamps
  • Filter transactions by status, date, contract, or user
  • Export transaction data for further analysis
  • View transaction receipts and event logs

Pro Tip: Custom Dashboards

You can create custom dashboards to monitor specific metrics that are important to your business. Contact our support team to set up custom dashboards tailored to your needs.

Core Concepts

Understand the fundamental concepts behind RelayXplore

This section covers the core concepts and architecture of RelayXplore, helping you understand how the system works under the hood.

Meta-Transactions

RelayXplore uses meta-transactions to enable gasless transactions. Meta-transactions separate the action of signing a transaction from the action of submitting it to the blockchain.

How Meta-Transactions Work

  1. User signs a message: The user signs a message containing the transaction details (to, data, value, etc.) using their private key.
  2. Signature verification: The signature is verified to ensure it was created by the user's private key.
  3. Transaction execution: The relayer (RelayXplore) creates and submits a transaction to the blockchain based on the signed message.
  4. Gas payment: The relayer pays for the gas using funds from your RelayXplore account.

Relayer Architecture

The RelayXplore relayer system consists of several components working together to provide a reliable and secure service.

API Gateway

Handles authentication, rate limiting, and request routing. The gateway validates API keys and ensures requests are properly formatted.

Transaction Processor

Validates signatures, estimates gas, and prepares transactions for submission. The processor also handles transaction batching and scheduling.

Blockchain Connector

Submits transactions to the blockchain and monitors their status. The connector handles retries and gas price adjustments to ensure transactions are confirmed.

Account Model

RelayXplore uses a provider funding model, where DApp developers fund their accounts to cover gas costs for their users.

Account Components

  • Balance: The amount of native tokens (ETH, MATIC, etc.) in your account.
  • API Keys: Used to authenticate requests to the RelayXplore API.
  • Usage Limits: Constraints on the number of transactions, gas usage, or other metrics.
  • Transaction History: Record of all transactions sent through your account.

Security Model

RelayXplore is designed with security as a top priority. The system includes multiple layers of protection to ensure the safety of your funds and transactions.

Signature Verification

All transactions require a valid signature from the user's private key. This ensures that only authorized users can initiate transactions.

API Key Authentication

All requests to the RelayXplore API must include a valid API key. API keys can be restricted to specific permissions and rate limits.

Transaction Validation

All transactions are validated before submission to ensure they meet security and formatting requirements.

Fraud Detection

RelayXplore monitors for unusual transaction patterns and can alert you to potential security issues.

Gas Management

RelayXplore includes sophisticated gas management features to optimize transaction costs and ensure timely confirmation.

  • Dynamic Gas Pricing: Automatically adjusts gas prices based on network conditions to ensure transactions are confirmed in a timely manner.
  • Gas Estimation: Accurately estimates gas usage for transactions to avoid overpaying or underpaying for gas.
  • Gas Optimization: Implements techniques like transaction batching to reduce overall gas costs.
  • EIP-1559 Support: Uses the EIP-1559 fee structure on supported networks for more predictable gas fees and faster transaction confirmations.

API Methods

Reference documentation for the RelayXplore SDK API methods

The RelayXplore SDK provides a comprehensive set of methods for interacting with the RelayXplore API. This section documents all available methods and their parameters.

Transaction Methods

Account Methods

Utility Methods

Error Handling

Learn how to handle errors and exceptions when using the RelayXplore SDK

The RelayXplore SDK may throw errors or exceptions in various scenarios, such as invalid API keys, insufficient balance, or network issues. This section provides guidance on how to handle these errors gracefully.

Common Error Codes

CodeDescriptionResolution
INVALID_API_KEYThe API key is invalid or has been revoked.Verify that your API key is correct and active.
INSUFFICIENT_BALANCEYour account balance is too low to cover the gas costs.Fund your account with more tokens.
TRANSACTION_FAILEDThe transaction failed on the blockchain.Check the transaction details and try again.
NETWORK_ERRORThere was a network error while communicating with the blockchain.Check your internet connection and try again.
RATE_LIMITEDYou have exceeded the rate limit for your API key.Wait for the rate limit to reset or upgrade your plan.

Handling Errors in Code

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';

const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

async function sendTransaction(transaction) {
  try {
    const result = await relay.sendTransaction(transaction);
    console.log('Transaction hash:', result.hash);
  } catch (error) {
    console.error('Error sending transaction:', error.message);

    if (error.code === 'INSUFFICIENT_BALANCE') {
      console.warn('Your account balance is too low. Please fund your account.');
    } else if (error.code === 'INVALID_API_KEY') {
      console.error('Invalid API key. Please check your API key.');
    } else {
      console.error('An unexpected error occurred.');
    }
  }
}

Custom Error Handling

You can implement custom error handling logic to suit your specific needs. For example, you might want to retry failed transactions, notify your users of errors, or log errors for debugging purposes.

javascript
javascript
async function sendTransactionWithRetry(transaction, maxRetries = 3) {
  let retries = 0;

  while (retries < maxRetries) {
    try {
      const result = await relay.sendTransaction(transaction);
      console.log('Transaction hash:', result.hash);
      return result;
    } catch (error) {
      console.error(`Transaction failed (retry ${retries + 1}):`, error.message);
      retries++;

      // Wait for a short period before retrying
      await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }

  console.error('Transaction failed after multiple retries.');
  throw new Error('Transaction failed after multiple retries.');
}

Examples

Code examples demonstrating how to use the RelayXplore SDK in various scenarios

This section provides code examples demonstrating how to use the RelayXplore SDK in various scenarios, such as sending gasless transactions, interacting with smart contracts, and managing API keys.

Sending a Gasless Transaction

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';

const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

async function sendGaslessTransaction(to, data, value = '0') {
  try {
    const transaction = {
      to,
      data,
      value,
    };

    const result = await relay.sendTransaction(transaction);
    console.log('Transaction hash:', result.hash);
    return result;
  } catch (error) {
    console.error('Error sending transaction:', error);
    throw error;
  }
}

Interacting with a Smart Contract

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';
import { ethers } from 'ethers';

const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

async function callContractFunction(contractAddress, abi, functionName, args) {
  try {
    const iface = new ethers.utils.Interface(abi);
    const data = iface.encodeFunctionData(functionName, args);

    const transaction = {
      to: contractAddress,
      data,
      value: '0',
    };

    const result = await relay.sendTransaction(transaction);
    console.log('Transaction hash:', result.hash);
    return result;
  } catch (error) {
    console.error('Error calling contract function:', error);
    throw error;
  }
}

Batching Transactions

javascript
javascript
import { RelayXplore } from '@relayxplore/sdk';

const relay = new RelayXplore({
  apiKey: process.env.RELAYXPLORE_API_KEY,
  network: 'mainnet',
});

async function sendBatchTransactions(transactions) {
  try {
    const result = await relay.sendBatchTransaction(transactions);
    console.log('Batch transaction hash:', result.hash);
    return result;
  } catch (error) {
    console.error('Error sending batch transactions:', error);
    throw error;
  }
}