gelato-morpho-sdk
v1.0.5
Published
Professional TypeScript SDK for Gelato Smart Wallet with Morpho integration
Maintainers
Readme
Gelato Morpho SDK
A professional TypeScript SDK for integrating Gelato Smart Wallet with Morpho lending protocol. This SDK provides a clean, type-safe interface for borrowing, supplying, and managing positions on Morpho markets.
Features
- 🚀 Easy Integration: Simple API for borrowing and supplying tokens
- 🔒 Type Safety: Full TypeScript support with comprehensive type definitions
- 💰 Smart Collateral Management: Automatic collateral calculation and supply
- 🌐 Multi-Market Support: Support for multiple markets with easy configuration
- 📊 Market Data: Real-time price feeds and market information
- ⚡ Gasless Transactions: Powered by Gelato's sponsored transactions
- 🛡️ Error Handling: Comprehensive error handling with detailed error messages
Installation
npm install @gelato-morpho/sdkQuick Start
1. Initialize the SDK
import { createGelatoMorphoSDK } from '@gelato-morpho/sdk';
const sdk = createGelatoMorphoSDK({
gelatoApiKey: 'your-gelato-api-key',
rpcUrl: 'https://sepolia.base.org',
chainId: 84532, // Base Sepolia
});2. Set up the Smart Wallet Client
import { useGelatoSmartWalletProviderContext } from '@gelatonetwork/smartwallet-react-sdk';
// In your React component
const { gelato: { client } } = useGelatoSmartWalletProviderContext();
// Set the client in the SDK
sdk.setClient(client);3. Borrow Tokens
// Borrow 100 USDC using the default BTC-USDC market
const result = await sdk.borrow(100, 'btc-usdc');
console.log('Transaction successful:', result);
// {
// userOpHash: '0x...',
// txHash: '0x...',
// success: true
// }
// Or borrow using custom market parameters
const customMarket = {
collateralToken: '0x...',
loanToken: '0x...',
oracle: '0x...',
irm: '0x...',
lltv: BigInt(945000000000000000), // 94.5%
};
const result2 = await sdk.borrow(50, customMarket);4. Get Borrow Preview
// Get preview information before borrowing
const preview = await sdk.getBorrowPreview(100, 'btc-usdc');
console.log('Borrow preview:', preview);
// {
// borrowAmount: '100',
// requiredCollateral: '0.0023',
// totalCollateral: '0.0024',
// liquidationPrice: '45000.00',
// market: { ... }
// }5. Supply Tokens
// Supply 100 USDC to earn interest
const result = await sdk.supply(100, 'btc-usdc');
// Supply collateral without borrowing
const result2 = await sdk.supplyCollateral(0.1, 'btc-usdc');6. Get Market Data
// Get current market information
const marketData = await sdk.getMarketData('btc-usdc');
console.log('Market data:', marketData);
// {
// collateralPrice: '45000.00',
// loanPrice: '1.00',
// apr: '5.2%',
// lltv: '94.5%',
// liquidationPrice: '42525.00'
// }7. Get User Balances
// Get balances for multiple tokens
const balances = await sdk.getBalances(
'0x1234...',
[
'0x63cc3c2b5B5881000aC7615D3aB0551CE30C72D8', // cbBTC
'0x87c25229AFBC30418D0144e8Dfb2bcf8eFd92c6c' // USDC
]
);
console.log('Balances:', balances);API Reference
Core Methods
borrow(amount, market, options?)
Borrow tokens with automatic collateral supply.
amount: Amount to borrow (string or number)market: Market name or market configurationoptions: Optional parametersonBehalf: Address to borrow on behalf ofreceiver: Address to receive borrowed tokens
supply(amount, market, options?)
Supply tokens to earn interest.
amount: Amount to supply (string or number)market: Market name or market configurationoptions: Optional parametersonBehalf: Address to supply on behalf ofreceiver: Address to receive supply shares
supplyCollateral(amount, market, options?)
Supply collateral without borrowing.
amount: Amount of collateral to supply (string or number)market: Market name or market configurationoptions: Optional parametersonBehalf: Address to supply on behalf of
getBorrowPreview(amount, market)
Get preview information for a borrow operation.
getMarketData(market)
Get current market data including prices and rates.
getBalances(userAddress, tokenAddresses)
Get token balances for a user.
Market Configuration
Predefined Markets
The SDK comes with predefined markets:
'btc-usdc': BTC-USDC market on Base Sepolia'default': Default market (same as btc-usdc)
Custom Markets
You can also create custom markets:
const customMarket = {
collateralToken: '0x...',
loanToken: '0x...',
oracle: '0x...',
irm: '0x...',
lltv: BigInt(945000000000000000), // 94.5%
};
await sdk.borrow(100, customMarket);Error Handling
The SDK provides comprehensive error handling:
try {
const result = await sdk.borrow(100, 'btc-usdc');
} catch (error) {
if (error instanceof SDKError) {
console.log('Error type:', error.type);
console.log('Error message:', error.message);
console.log('Error code:', error.code);
}
}Error Types
INSUFFICIENT_BALANCE: User doesn't have enough tokensINVALID_MARKET: Market configuration is invalidTRANSACTION_FAILED: Transaction failed to executeINVALID_AMOUNT: Amount is invalid or negativeNETWORK_ERROR: Network or RPC errorCONFIGURATION_ERROR: SDK configuration error
Configuration
SDK Configuration
interface SDKConfig {
gelatoApiKey: string; // Required: Your Gelato API key
rpcUrl?: string; // Optional: RPC URL (default: Base Sepolia)
chainId?: number; // Optional: Chain ID (default: 84532)
morphoAddress?: Address; // Optional: Morpho contract address
defaultGasLimit?: bigint; // Optional: Default gas limit
}Environment Variables
# Required
GELATO_API_KEY=your-gelato-api-key
# Optional
RPC_URL=https://sepolia.base.org
CHAIN_ID=84532Examples
Complete Borrowing Example
import { createGelatoMorphoSDK } from '@gelato-morpho/sdk';
async function borrowExample() {
// Initialize SDK
const sdk = createGelatoMorphoSDK({
gelatoApiKey: process.env.GELATO_API_KEY!,
rpcUrl: 'https://sepolia.base.org',
});
// Set client (from your React app)
sdk.setClient(client);
try {
// Get borrow preview
const preview = await sdk.getBorrowPreview(100, 'btc-usdc');
console.log('Required collateral:', preview.totalCollateral, 'BTC');
// Check if user has enough collateral
const balances = await sdk.getBalances(
client.account.address,
['0x63cc3c2b5B5881000aC7615D3aB0551CE30C72D8'] // cbBTC
);
const btcBalance = parseFloat(balances['0x63cc3c2b5B5881000aC7615D3aB0551CE30C72D8'].formatted);
const requiredCollateral = parseFloat(preview.totalCollateral);
if (btcBalance < requiredCollateral) {
console.log('Insufficient collateral balance');
return;
}
// Execute borrow
const result = await sdk.borrow(100, 'btc-usdc');
console.log('Borrow successful:', result.txHash);
} catch (error) {
console.error('Borrow failed:', error);
}
}Market Data Monitoring
async function monitorMarket() {
const sdk = createGelatoMorphoSDK({
gelatoApiKey: process.env.GELATO_API_KEY!,
});
// Get market data
const marketData = await sdk.getMarketData('btc-usdc');
console.log('BTC Price:', marketData.collateralPrice);
console.log('LTV:', marketData.lltv);
console.log('Liquidation Price:', marketData.liquidationPrice);
console.log('APR:', marketData.apr);
}Earn Functionality Example (New!)
async function earnExample() {
const sdk = createGelatoMorphoSDK({
gelatoApiKey: process.env.GELATO_API_KEY!,
rpcUrl: 'https://sepolia.base.org',
});
// Set client (from your React app)
sdk.setClient(client);
try {
// Get vault information
const vaultInfo = await sdk.getVaultInfo(client.account.address);
console.log('Vault Total Assets:', vaultInfo.totalAssets.toString());
console.log('Vault APR:', vaultInfo.apr, '%');
// Get current earn position
const position = await sdk.getEarnPosition(client.account.address, 'btc-usdc');
console.log('Current Position:', position.depositedAmount, 'USDC');
// Deposit to earn interest
const depositAmount = 100;
console.log(`Depositing ${depositAmount} USDC...`);
const depositResult = await sdk.earnDeposit(depositAmount, 'btc-usdc');
console.log('Deposit successful:', depositResult.txHash);
// Wait for transaction to be processed
await new Promise(resolve => setTimeout(resolve, 5000));
// Check updated position
const updatedPosition = await sdk.getEarnPosition(client.account.address, 'btc-usdc');
console.log('Updated Position:', updatedPosition.depositedAmount, 'USDC');
// Withdraw some funds
const withdrawAmount = 50;
console.log(`Withdrawing ${withdrawAmount} USDC...`);
const withdrawResult = await sdk.earnWithdraw(withdrawAmount, 'btc-usdc');
console.log('Withdraw successful:', withdrawResult.txHash);
// Check final position
const finalPosition = await sdk.getEarnPosition(client.account.address, 'btc-usdc');
console.log('Final Position:', finalPosition.depositedAmount, 'USDC');
} catch (error) {
console.error('Earn operation failed:', error);
}
}Development
Building the SDK
cd sdk
npm install
npm run buildRunning Tests
npm testLinting
npm run lintContributing
- Fork the repository
- Create a feature branch
- Make your changes
- Add tests
- Submit a pull request
License
MIT License - see LICENSE file for details
Support
For support and questions:
- Create an issue on GitHub
- Join our Discord community
- Check the documentation
Changelog
v1.0.0
- Initial release
- Core borrowing and supplying functionality
- Market data and balance queries
- TypeScript support
- Error handling
