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

mantle-cashflow-engine

v1.0.1

Published

Official SDK for Mantle Cashflow Engine

Readme

Mantle Cashflow Engine SDK

Official JavaScript/TypeScript SDK for the Mantle Cashflow Engine - A protocol-level settlement and distribution engine for RealFi applications.

npm version License: MIT

🚀 Features

  • Simple API: Clean, intuitive methods for all cashflow operations
  • Type-Safe: Full TypeScript support with comprehensive JSDoc comments
  • Error Handling: Custom error classes for better debugging
  • Validation: Built-in input validation before API calls
  • Batch Operations: Efficient batch settlement and querying
  • Automation Ready: Built-in keeper/automation support
  • Webhook Support: Easy webhook registration for events
  • Zero Dependencies: Lightweight with no external dependencies (except fetch API)

📦 Installation

npm install mantle-cashflow-engine

Or with yarn:

yarn add mantle-cashflow-engine

🏁 Quick Start

const { MantleCashflowSDK } = require("mantle-cashflow-engine");

// Initialize the SDK
const sdk = new MantleCashflowSDK({
  apiUrl: "https://mce-rust.vercel.app",
});

// Create a cashflow
const cashflow = await sdk.createCashflow({
  startTime: new Date("2024-01-01"),
  endTime: new Date("2024-12-31"),
  expectedAmount: "10.0", // ETH
  recipients: [
    { address: "0x123...abc", sharePercentage: 60 },
    { address: "0x456...def", sharePercentage: 40 },
  ],
  mintNFT: true,
});

console.log("Cashflow created:", cashflow.cashflowId);

📚 API Reference

Constructor

const sdk = new MantleCashflowSDK({
  apiUrl: "https://mce-rust.vercel.app", // Required: Your API base URL
  apiKey: "your-api-key", // Optional: API key for authentication
});

Core Methods

createCashflow(config)

Create a new cashflow with automatic fund distribution.

const cashflow = await sdk.createCashflow({
  startTime: new Date("2024-01-01"),
  endTime: new Date("2024-12-31"),
  expectedAmount: "10.0",
  recipients: [
    { address: "0xRecipient1...", sharePercentage: 50 },
    { address: "0xRecipient2...", sharePercentage: 30 },
    { address: "0xRecipient3...", sharePercentage: 20 },
  ],
  eligibleAddresses: ["0xEligible1...", "0xEligible2..."], // Optional whitelist
  mintNFT: true, // Optional: mint NFT certificates
});

Returns: Promise<CashflowInfo>


getCashflow(cashflowId)

Get detailed information about a specific cashflow.

const info = await sdk.getCashflow(1);

console.log(info);
// {
//   id: 1,
//   vaultId: 1,
//   startTime: Date,
//   endTime: Date,
//   expectedAmount: '10.0',
//   isSettled: false,
//   recipientCount: 3,
//   vaultBalance: '10.0',
//   isSettleable: true,
//   autoSettlementEnabled: false
// }

Returns: Promise<CashflowInfo>


getCashflowsBatch(cashflowIds)

Get multiple cashflows in a single request.

const cashflows = await sdk.getCashflowsBatch([1, 2, 3, 4, 5]);

cashflows.forEach((cf) => {
  console.log(`Cashflow ${cf.id}: ${cf.isSettled ? "Settled" : "Pending"}`);
});

Returns: Promise<CashflowInfo[]>


settleCashflow(cashflowId, eligibleAddresses?)

Settle a cashflow and distribute funds to recipients.

// Simple settlement
await sdk.settleCashflow(1);

// With eligibility proof
await sdk.settleCashflow(1, ["0xEligible1...", "0xEligible2..."]);

Returns: Promise<CashflowInfo>


settleCashflowsBatch(cashflowIds)

Settle multiple cashflows in one transaction.

const result = await sdk.settleCashflowsBatch([1, 2, 3, 4, 5]);

console.log(`Successfully settled: ${result.settled.length}`);
console.log(`Failed: ${result.failed.length}`);

result.failed.forEach((f) => {
  console.log(`Cashflow ${f.cashflowId} failed: ${f.error}`);
});

Returns: Promise<{ settled: number[], failed: Array<{cashflowId: number, error: string}>, total: number }>


isSettleable(cashflowId)

Check if a cashflow can be settled now.

const canSettle = await sdk.isSettleable(1);

if (canSettle) {
  await sdk.settleCashflow(1);
}

Returns: Promise<boolean>


accrueYield(cashflowId, yieldAmount)

Add yield/interest to a cashflow.

await sdk.accrueYield(1, "0.5"); // Add 0.5 ETH yield

const updated = await sdk.getCashflow(1);
console.log("New balance:", updated.vaultBalance);

Returns: Promise<CashflowInfo>


enableAutoSettlement(cashflowId)

Enable automatic settlement for a cashflow.

await sdk.enableAutoSettlement(1);

console.log("Auto-settlement enabled for cashflow 1");

Returns: Promise<{ cashflowId: number }>


Automation Methods

getSettleableCashflows(limit?, offset?)

Get all cashflows ready for settlement with auto-settlement enabled.

const result = await sdk.getSettleableCashflows(20, 0);

console.log(`Found ${result.count} settleable cashflows`);
result.settleable.forEach((id) => {
  console.log(`Cashflow ${id} is ready to settle`);
});

Returns: Promise<{ settleable: number[], count: number, offset: number, limit: number }>


settleAllReady(limit?)

Automatically settle all ready cashflows (perfect for keeper bots).

const result = await sdk.settleAllReady(10);

console.log(`Settled ${result.settled.length} cashflows`);
console.log(`Failed ${result.failed.length} cashflows`);

Returns: Promise<{ settled: number[], failed: number[], total: number }>


Webhook Methods

registerWebhook(config)

Register a webhook to receive event notifications.

await sdk.registerWebhook({
  url: "https://myapp.com/webhooks/mce",
  events: ["cashflow.created", "cashflow.settled"],
  secret: "my-webhook-secret", // Optional
});

Webhook Payload Example:

{
  "event": "cashflow.created",
  "timestamp": "2024-01-01T00:00:00.000Z",
  "data": {
    "cashflowId": 1,
    "vaultId": 1,
    "startTime": "2024-01-01T00:00:00.000Z",
    "endTime": "2024-12-31T23:59:59.000Z",
    "expectedAmount": "10.0",
    "transactionHash": "0x..."
  }
}

Returns: Promise<{ id: number, url: string, events: string[], secret?: string }>


Utility Methods

getHealth()

Check the API server health status.

const health = await sdk.getHealth();

console.log(health);
// {
//   success: true,
//   status: 'healthy',
//   timestamp: '2024-01-01T00:00:00.000Z',
//   version: '1.0.0',
//   network: 'https://rpc.mantle.xyz',
//   engine: '0x...',
//   vault: '0x...'
// }

Returns: Promise<Object>


Static Utilities

// Convert percentage to basis points
const bps = MantleCashflowSDK.percentageToBasisPoints(25.5); // 2550

// Convert basis points to percentage
const pct = MantleCashflowSDK.basisPointsToPercentage(2550); // 25.5

💡 Usage Examples

Example 1: Real Estate Rental Distribution

// Monthly rental income distribution
const rentalCashflow = await sdk.createCashflow({
  startTime: new Date("2024-01-01"),
  endTime: new Date("2024-01-31"),
  expectedAmount: "5.0", // 5 ETH monthly rent
  recipients: [
    { address: "0xOwner...", sharePercentage: 70 }, // Property owner
    { address: "0xManager...", sharePercentage: 20 }, // Property manager
    { address: "0xMaintenance...", sharePercentage: 10 }, // Maintenance fund
  ],
  mintNFT: true, // NFT certificate for tax records
});

// Enable auto-settlement at month end
await sdk.enableAutoSettlement(rentalCashflow.cashflowId);

Example 2: Invoice Factoring

// Invoice payment with multiple stakeholders
const invoiceCashflow = await sdk.createCashflow({
  startTime: new Date(), // Immediate
  endTime: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000), // 30 days
  expectedAmount: "25.0",
  recipients: [
    { address: "0xSupplier...", sharePercentage: 85 }, // Supplier
    { address: "0xFactoringFee...", sharePercentage: 10 }, // Factoring fee
    { address: "0xPlatform...", sharePercentage: 5 }, // Platform fee
  ],
});

// Settle when payment received
await sdk.settleCashflow(invoiceCashflow.cashflowId);

Example 3: Yield-Bearing Savings Pool

// Create savings pool
const savingsCashflow = await sdk.createCashflow({
  startTime: new Date("2024-01-01"),
  endTime: new Date("2025-01-01"),
  expectedAmount: "100.0",
  recipients: [
    { address: "0xSaver1...", sharePercentage: 40 },
    { address: "0xSaver2...", sharePercentage: 30 },
    { address: "0xSaver3...", sharePercentage: 30 },
  ],
});

// Add monthly yield
setInterval(async () => {
  await sdk.accrueYield(savingsCashflow.cashflowId, "0.5");
  console.log("Monthly yield added");
}, 30 * 24 * 60 * 60 * 1000);

Example 4: Batch Settlement Keeper Bot

// Automated keeper bot for settling cashflows
async function keeperBot() {
  try {
    console.log("Keeper bot running...");

    // Get all settleable cashflows
    const settleable = await sdk.getSettleableCashflows(50);
    console.log(`Found ${settleable.count} cashflows ready to settle`);

    if (settleable.count > 0) {
      // Settle all in batch
      const result = await sdk.settleAllReady(50);

      console.log(`✅ Successfully settled: ${result.settled.length}`);
      console.log(`❌ Failed: ${result.failed.length}`);

      // Log failures
      result.failed.forEach((id) => {
        console.error(`Failed to settle cashflow ${id}`);
      });
    }
  } catch (error) {
    console.error("Keeper bot error:", error);
  }

  // Run every 5 minutes
  setTimeout(keeperBot, 5 * 60 * 1000);
}

keeperBot();

Example 5: Monitoring with Webhooks

// Register webhook for notifications
await sdk.registerWebhook({
  url: "https://myapp.com/api/webhooks/cashflow",
  events: ["cashflow.created", "cashflow.settled"],
  secret: process.env.WEBHOOK_SECRET,
});

// Webhook handler (Express.js example)
app.post("/api/webhooks/cashflow", (req, res) => {
  const { event, data } = req.body;

  switch (event) {
    case "cashflow.created":
      console.log(`New cashflow created: ${data.cashflowId}`);
      // Send notification, update database, etc.
      break;

    case "cashflow.settled":
      console.log(
        `Cashflow ${data.cashflowId} settled: ${data.totalDistributed} ETH`
      );
      // Update records, notify users, etc.
      break;
  }

  res.status(200).send("OK");
});

🛡️ Error Handling

The SDK provides custom error classes for better error handling:

const { ValidationError, APIError } = require("mantle-cashflow-engine");

try {
  await sdk.createCashflow({
    // Invalid config
    recipients: [
      { address: "0x123", sharePercentage: 60 },
      // Missing 40% - doesn't sum to 100
    ],
  });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error("Validation Error:", error.message);
    console.error("Details:", error.details);
  } else if (error instanceof APIError) {
    console.error("API Error:", error.statusCode, error.message);
  } else {
    console.error("Unknown Error:", error);
  }
}

🔧 TypeScript Support

The SDK includes full JSDoc comments for excellent IDE autocomplete:

import {
  MantleCashflowSDK,
  CashflowConfig,
  CashflowInfo,
} from "mantle-cashflow-engine";

const sdk = new MantleCashflowSDK({
  apiUrl: "https://mce-rust.vercel.app",
});

const config: CashflowConfig = {
  startTime: new Date("2024-01-01"),
  endTime: new Date("2024-12-31"),
  expectedAmount: "10.0",
  recipients: [{ address: "0x123...", sharePercentage: 100 }],
};

const cashflow: CashflowInfo = await sdk.createCashflow(config);

📖 Additional Resources


🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

🙋 Support


Built with ❤️ for the Mantle ecosystem