npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

gelato-morpho-sdk

v1.0.5

Published

Professional TypeScript SDK for Gelato Smart Wallet with Morpho integration

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/sdk

Quick 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 configuration
  • options: Optional parameters
    • onBehalf: Address to borrow on behalf of
    • receiver: 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 configuration
  • options: Optional parameters
    • onBehalf: Address to supply on behalf of
    • receiver: 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 configuration
  • options: Optional parameters
    • onBehalf: 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 tokens
  • INVALID_MARKET: Market configuration is invalid
  • TRANSACTION_FAILED: Transaction failed to execute
  • INVALID_AMOUNT: Amount is invalid or negative
  • NETWORK_ERROR: Network or RPC error
  • CONFIGURATION_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=84532

Examples

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 build

Running Tests

npm test

Linting

npm run lint

Contributing

  1. Fork the repository
  2. Create a feature branch
  3. Make your changes
  4. Add tests
  5. 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