Skip to content

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

 

History

13 Commits

Folders and files

Repository files navigation

Solana Gasless SDK

Let users interact with your Solana dApp without needing SOL for transaction fees.

npm version License: MIT TypeScript


🎯 The Problem

New users in Solana dApps face a chicken-and-egg problem:

  • They need SOL to pay transaction fees
  • But they need to DO something to GET SOL
  • Result: High friction, poor UX, users bounce

💡 The Solution

Gasless SDK lets YOUR protocol pay transaction fees while users just sign.

// User sends tokens WITHOUT needing SOL!
await gasless.execute({
  instructions: [transferInstruction],
  signers: [userWallet]  // User signs, YOU pay 🎉
});

⚡ Quick Start

Installation

npm install solana-gasless-sdk @solana/web3.js

5-Line Integration

import { GaslessClient } from 'solana-gasless-sdk';
import { Keypair, SystemProgram, LAMPORTS_PER_SOL } from '@solana/web3.js';

// 1. Initialize (your treasury pays fees)
const gasless = new GaslessClient({
  payer: {
    payerKeypair: yourTreasuryWallet,
  },
  connection: {
    rpcUrls: ['https://api.mainnet-beta.solana.com'],
  },
});

// 2. User creates transaction (NO SOL NEEDED!)
const instruction = SystemProgram.transfer({
  fromPubkey: userWallet.publicKey,
  toPubkey: recipient,
  lamports: 0.1 * LAMPORTS_PER_SOL,
});

// 3. Execute gasless transaction
const result = await gasless.execute({
  instructions: [instruction],
  signers: [userWallet],  // User just signs!
});

console.log('Success:', result.signature);
// User sent 0.1 SOL without needing SOL for fees! ✨

🎮 Use Cases

Gaming

// Player collects item without gas fees
await gasless.execute({
  instructions: [collectItemInstruction],
  signers: [playerWallet]
});

Result: Players can play immediately, no SOL onboarding needed.

NFT Marketplace

// User mints NFT for free (you pay)
await gasless.execute({
  instructions: [mintNFTInstruction],
  signers: [userWallet]
});

Result: Zero-friction NFT minting for new users.

DeFi Protocol

// New user stakes without gas fees
await gasless.execute({
  instructions: [stakeInstruction],
  signers: [newUserWallet]
});

Result: Instant onboarding, higher conversion rates.


✨ Features

🎯 Core Functionality

  • ✅ Gasless Transactions - User signs, you pay fees
  • ✅ Pre-flight Simulation - Test before execution
  • ✅ Accurate Fee Estimation - Know costs upfront
  • ✅ Automatic Retries - Handle network issues gracefully

💪 Production Ready

  • ✅ Multi-Payer Support - Load balance across wallets
  • ✅ Smart Fee Optimization - Don't overpay during low congestion
  • ✅ RPC Failover - Automatic switching between endpoints
  • ✅ Comprehensive Monitoring - Track metrics, health, errors

👨‍💻 Developer Experience

  • ✅ Full TypeScript - Type-safe with IntelliSense
  • ✅ Simple API - 5-line integration
  • ✅ Well Documented - Extensive guides and examples
  • ✅ Production Tested - Battle-tested error handling

📚 Examples

Example 1: Basic Transfer

import { GaslessClient } from 'solana-gasless-sdk';
import { Keypair, SystemProgram, LAMPORTS_PER_SOL } from '@solana/web3.js';

async function sendGaslessTransfer() {
  // Initialize
  const gasless = new GaslessClient({
    payer: {
      payerKeypair: treasuryWallet,
    },
    connection: {
      rpcUrls: ['https://api.mainnet-beta.solana.com'],
    },
  });

  // User wants to send SOL (but has no SOL for fees!)
  const userWallet = Keypair.generate();
  const recipient = new PublicKey('...');

  const instruction = SystemProgram.transfer({
    fromPubkey: userWallet.publicKey,
    toPubkey: recipient,
    lamports: 0.1 * LAMPORTS_PER_SOL,
  });

  // Execute - treasury pays the fee!
  const result = await gasless.execute({
    instructions: [instruction],
    signers: [userWallet],
  });

  console.log('Transaction:', result.signature);
  console.log('Fee paid by treasury:', result.feePaid / LAMPORTS_PER_SOL, 'SOL');
}

Example 2: Simulate Before Execute

async function safeExecute(instruction, userWallet) {
  // 1. Simulate first
  const simulation = await gasless.simulate({
    instructions: [instruction],
    signers: [userWallet],
  });

  if (!simulation.success) {
    console.error('Transaction will fail:', simulation.logs);
    return;
  }

  // 2. Estimate cost
  const estimate = await gasless.estimateFee({
    instructions: [instruction],
    signers: [userWallet],
  });

  console.log(`Will cost: ${estimate.totalFee / LAMPORTS_PER_SOL} SOL`);

  // 3. Execute safely
  const result = await gasless.execute({
    instructions: [instruction],
    signers: [userWallet],
  });

  return result.signature;
}

Example 3: Multi-Payer Load Balancing

// For high-volume apps, use multiple payer wallets
const gasless = new GaslessClient({
  payer: {
    payerKeypairs: [
      treasuryWallet1,
      treasuryWallet2,
      treasuryWallet3,
    ],
    payerStrategy: 'round-robin', // Distribute load
    minBalance: 1 * LAMPORTS_PER_SOL,
    stopIfBalanceBelow: 0.5 * LAMPORTS_PER_SOL,
  },
  connection: {
    rpcUrls: [
      'https://api.mainnet-beta.solana.com',
      'https://solana-api.projectserum.com', // Backup
    ],
  },
});

// SDK automatically rotates between payers!
for (let i = 0; i < 1000; i++) {
  await gasless.execute({...}); // Different payer each time
}

Example 4: Smart Fee Management

// Adjust fees based on urgency
const priority = isUrgent ? 'high' : 'medium';

await gasless.execute({
  instructions: [instruction],
  signers: [user],
  priorityLevel: priority, // SDK optimizes fees
  maxFee: 0.01 * LAMPORTS_PER_SOL, // Budget limit
});

// Check network conditions
if (gasless.isNetworkCongested()) {
  console.log('Network busy, using higher priority');
}

// Get AI suggestion
const suggested = gasless.suggestPriorityLevel();
console.log('Recommended priority:', suggested);

Example 5: Error Handling

import {
  ValidationError,
  SimulationError,
  InsufficientBalanceError,
  TransactionFailedError,
} from 'solana-gasless-sdk';

try {
  const result = await gasless.execute({
    instructions: [instruction],
    signers: [user],
  });
  
  console.log('Success:', result.signature);
  
} catch (error) {
  if (error instanceof ValidationError) {
    console.error('Invalid parameters:', error.message);
    
  } else if (error instanceof SimulationError) {
    console.error('Transaction will fail:', error.details.logs);
    showUserError('This transaction cannot be completed');
    
  } else if (error instanceof InsufficientBalanceError) {
    console.error('Treasury balance low!');
    alertAdmin('REFILL_NEEDED', error.details);
    
  } else if (error instanceof TransactionFailedError) {
    console.error('Transaction failed on-chain');
  }
}

Example 6: Monitoring & Metrics

// Track your gasless spending
const metrics = gasless.getMetrics();

console.log(`
  Total Transactions: ${metrics.totalTransactions}
  Success Rate: ${metrics.successRate}%
  Total Fees Spent: ${metrics.totalFeesSpent / LAMPORTS_PER_SOL} SOL
  Average Fee: ${metrics.averageFeePerTransaction / LAMPORTS_PER_SOL} SOL
  Avg Confirmation Time: ${metrics.averageConfirmationTime}ms
`);

// Health check
const health = await gasless.healthCheck();

if (!health.payer) {
  console.warn('⚠️ Payer balance low!');
  console.log('Balance:', health.payerBalance / LAMPORTS_PER_SOL, 'SOL');
  // Send alert to refill
}

// Check RPC health
health.rpc.forEach(rpc => {
  console.log(`${rpc.url}: ${rpc.healthy ? '✅' : '❌'}`);
});

Example 7: React Integration

// Custom hook
import { useEffect, useState } from 'react';
import { GaslessClient } from 'solana-gasless-sdk';

export function useGasless() {
  const [gasless, setGasless] = useState<GaslessClient | null>(null);

  useEffect(() => {
    const client = new GaslessClient({
      payer: { payerKeypair: getPayerWallet() },
      connection: { rpcUrls: [process.env.REACT_APP_RPC_URL] },
    });
    
    setGasless(client);
    return () => client.destroy();
  }, []);

  const execute = async (instructions, signers) => {
    if (!gasless) throw new Error('Not initialized');
    return await gasless.execute({ instructions, signers });
  };

  return { gasless, execute };
}

// Component
function TransferButton() {
  const { execute } = useGasless();
  const { publicKey } = useWallet();

  const handleClick = async () => {
    const instruction = SystemProgram.transfer({...});
    const result = await execute([instruction], [wallet]);
    alert(`Success! ${result.signature}`);
  };

  return <button onClick={handleClick}>Send (Gasless!)</button>;
}

🚀 Advanced Configuration

const gasless = new GaslessClient({
  // Payer configuration
  payer: {
    payerKeypairs: [wallet1, wallet2, wallet3],
    payerStrategy: 'round-robin', // or 'lowest-balance' or 'random'
    minBalance: 0.1 * LAMPORTS_PER_SOL,
    stopIfBalanceBelow: 0.05 * LAMPORTS_PER_SOL,
  },

  // Connection configuration
  connection: {
    rpcUrls: [
      'https://api.mainnet-beta.solana.com',
      'https://solana-api.projectserum.com', // Fallback
    ],
    commitment: 'confirmed',
    timeout: 30000,
    healthCheckInterval: 30000,
  },

  // Retry configuration
  retry: {
    maxAttempts: 5,
    baseDelayMs: 1000,
    maxDelayMs: 10000,
    exponentialBackoff: true,
  },

  // Fee configuration
  fee: {
    priorityLevel: 'medium',
    maxFeePerTransaction: 0.01 * LAMPORTS_PER_SOL,
    computeUnitPriceMultiplier: 1.0,
  },

  // Monitoring
  monitoring: {
    enableMetrics: true,
    enableLogging: true,
    logLevel: 'info',
  },

  confirmationTimeout: 60000,
  skipPreflight: false,
});

📖 API Reference

Main Methods

execute(params): Promise<TransactionResult>

Execute a gasless transaction.

Parameters:

  • instructions: TransactionInstruction[] - Transaction instructions
  • signers: Signer[] - Signers (user wallets)
  • priorityLevel?: 'none' | 'low' | 'medium' | 'high' | 'veryHigh'
  • maxFee?: number - Maximum fee in lamports
  • computeUnitLimit?: number - Custom compute limit

Returns: { signature, slot, confirmationStatus, feePaid }

simulate(params): Promise<SimulationResult>

Simulate transaction before execution.

Returns: { success, unitsConsumed, logs, err }

estimateFee(params): Promise<FeeEstimate>

Estimate transaction fee.

Returns: { baseFee, computeUnits, priorityFee, totalFee, breakdown }

getMetrics(): Metrics

Get transaction metrics.

healthCheck(): Promise<HealthStatus>

Check system health.

View Full API Documentation →


💰 Cost Comparison

Traditional Flow (User Pays)

User needs:
- SOL for transaction ✓
- SOL for fees ✓
- Understanding of gas ✓

Friction: HIGH ❌
Conversion: LOW ❌

Gasless Flow (You Pay)

User needs:
- Just sign ✓

Friction: ZERO ✅
Conversion: HIGH ✅

Cost to you: ~$0.0001 per transaction

Example:

  • 10,000 transactions/month
  • Cost: ~$1 in SOL
  • ROI: Better user experience, higher conversion

🎯 Who Should Use This?

✅ Perfect For:

  • Gaming dApps - Players shouldn't think about gas
  • NFT Marketplaces - Let users mint instantly
  • DeFi Protocols - Remove onboarding friction
  • Social dApps - Posting shouldn't cost money
  • Any dApp - Wanting better UX

🛠️ Troubleshooting

"Insufficient Balance" Error

// Check payer balance
const balances = await gasless.getPayerBalances();
console.log('Balances:', balances);

"Simulation Failed"

// Check why it failed
const sim = await gasless.simulate(params);
console.log('Logs:', sim.logs);

"All RPCs Down"

// Check RPC health
const health = await gasless.healthCheck();
console.log('RPC Status:', health.rpc);

📚 Documentation


🏗️ Roadmap

v0.2.0 (Coming Soon)

  • Token swap fee payment (pay fees in USDC/USDT)
  • Transaction bundling (batch multiple transactions)
  • Enhanced monitoring dashboard

v1.0.0

  • Production audit
  • Performance benchmarks
  • Enterprise features

📝 License

MIT License - see LICENSE file for details.


🙏 Acknowledgments

Built with ❤️ for the Solana ecosystem.


🚀 Get Started Now!

npm install solana-gasless-sdk

Like it? Give us a ⭐ on GitHub!


Built for developers, by Shankstwin
Making Solana dApps more accessible, one gasless transaction at a time

About

No description, website, or topics provided.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages