Let users interact with your Solana dApp without needing SOL for transaction fees.
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
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 🎉
});npm install solana-gasless-sdk @solana/web3.jsimport { 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! ✨// Player collects item without gas fees
await gasless.execute({
instructions: [collectItemInstruction],
signers: [playerWallet]
});Result: Players can play immediately, no SOL onboarding needed.
// User mints NFT for free (you pay)
await gasless.execute({
instructions: [mintNFTInstruction],
signers: [userWallet]
});Result: Zero-friction NFT minting for new users.
// New user stakes without gas fees
await gasless.execute({
instructions: [stakeInstruction],
signers: [newUserWallet]
});Result: Instant onboarding, higher conversion rates.
- ✅ 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
- ✅ 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
- ✅ Full TypeScript - Type-safe with IntelliSense
- ✅ Simple API - 5-line integration
- ✅ Well Documented - Extensive guides and examples
- ✅ Production Tested - Battle-tested error handling
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');
}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;
}// 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
}// 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);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');
}
}// 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 ? '✅' : '❌'}`);
});// 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>;
}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,
});Execute a gasless transaction.
Parameters:
instructions: TransactionInstruction[]- Transaction instructionssigners: Signer[]- Signers (user wallets)priorityLevel?: 'none' | 'low' | 'medium' | 'high' | 'veryHigh'maxFee?: number- Maximum fee in lamportscomputeUnitLimit?: number- Custom compute limit
Returns: { signature, slot, confirmationStatus, feePaid }
Simulate transaction before execution.
Returns: { success, unitsConsumed, logs, err }
Estimate transaction fee.
Returns: { baseFee, computeUnits, priorityFee, totalFee, breakdown }
Get transaction metrics.
Check system health.
User needs:
- SOL for transaction ✓
- SOL for fees ✓
- Understanding of gas ✓
Friction: HIGH ❌
Conversion: LOW ❌
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
- 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
// Check payer balance
const balances = await gasless.getPayerBalances();
console.log('Balances:', balances);// Check why it failed
const sim = await gasless.simulate(params);
console.log('Logs:', sim.logs);// Check RPC health
const health = await gasless.healthCheck();
console.log('RPC Status:', health.rpc);- Token swap fee payment (pay fees in USDC/USDT)
- Transaction bundling (batch multiple transactions)
- Enhanced monitoring dashboard
- Production audit
- Performance benchmarks
- Enterprise features
MIT License - see LICENSE file for details.
Built with ❤️ for the Solana ecosystem.
npm install solana-gasless-sdkLike it? Give us a ⭐ on GitHub!
Built for developers, by Shankstwin
Making Solana dApps more accessible, one gasless transaction at a time