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


- ✅ 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)
``bash`
npm install mantle-cashflow-engine
Or with yarn:
`bash`
yarn add mantle-cashflow-engine
`javascript
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);
`
`javascript`
const sdk = new MantleCashflowSDK({
apiUrl: "https://mce-rust.vercel.app", // Required: Your API base URL
apiKey: "your-api-key", // Optional: API key for authentication
});
---
#### createCashflow(config)
Create a new cashflow with automatic fund distribution.
`javascript`
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
---
#### getCashflow(cashflowId)
Get detailed information about a specific cashflow.
`javascript
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
---
#### getCashflowsBatch(cashflowIds)
Get multiple cashflows in a single request.
`javascript
const cashflows = await sdk.getCashflowsBatch([1, 2, 3, 4, 5]);
cashflows.forEach((cf) => {
console.log(Cashflow ${cf.id}: ${cf.isSettled ? "Settled" : "Pending"});`
});
Returns: Promise
---
#### settleCashflow(cashflowId, eligibleAddresses?)
Settle a cashflow and distribute funds to recipients.
`javascript
// Simple settlement
await sdk.settleCashflow(1);
// With eligibility proof
await sdk.settleCashflow(1, ["0xEligible1...", "0xEligible2..."]);
`
Returns: Promise
---
#### settleCashflowsBatch(cashflowIds)
Settle multiple cashflows in one transaction.
`javascript
const result = await sdk.settleCashflowsBatch([1, 2, 3, 4, 5]);
console.log(Successfully settled: ${result.settled.length});Failed: ${result.failed.length}
console.log();
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.
`javascript
const canSettle = await sdk.isSettleable(1);
if (canSettle) {
await sdk.settleCashflow(1);
}
`
Returns: Promise
---
#### accrueYield(cashflowId, yieldAmount)
Add yield/interest to a cashflow.
`javascript
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
---
#### enableAutoSettlement(cashflowId)
Enable automatic settlement for a cashflow.
`javascript
await sdk.enableAutoSettlement(1);
console.log("Auto-settlement enabled for cashflow 1");
`
Returns: Promise<{ cashflowId: number }>
---
#### getSettleableCashflows(limit?, offset?)
Get all cashflows ready for settlement with auto-settlement enabled.
`javascript
const result = await sdk.getSettleableCashflows(20, 0);
console.log(Found ${result.count} settleable cashflows);Cashflow ${id} is ready to settle
result.settleable.forEach((id) => {
console.log();`
});
Returns: Promise<{ settleable: number[], count: number, offset: number, limit: number }>
---
#### settleAllReady(limit?)
Automatically settle all ready cashflows (perfect for keeper bots).
`javascript
const result = await sdk.settleAllReady(10);
console.log(Settled ${result.settled.length} cashflows);Failed ${result.failed.length} cashflows
console.log();`
Returns: Promise<{ settled: number[], failed: number[], total: number }>
---
#### registerWebhook(config)
Register a webhook to receive event notifications.
`javascript`
await sdk.registerWebhook({
url: "https://myapp.com/webhooks/mce",
events: ["cashflow.created", "cashflow.settled"],
secret: "my-webhook-secret", // Optional
});
Webhook Payload Example:
`json`
{
"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 }>
---
#### getHealth()
Check the API server health status.
`javascript
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
---
#### Static Utilities
`javascript
// Convert percentage to basis points
const bps = MantleCashflowSDK.percentageToBasisPoints(25.5); // 2550
// Convert basis points to percentage
const pct = MantleCashflowSDK.basisPointsToPercentage(2550); // 25.5
`
---
`javascript
// 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);
`
---
`javascript
// 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);
`
---
`javascript
// 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);
`
---
`javascript
// 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});❌ Failed: ${result.failed.length}
console.log();
// 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();
`
---
`javascript
// 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");
});
`
---
The SDK provides custom error classes for better error handling:
`javascript
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);
}
}
`
---
The SDK includes full JSDoc comments for excellent IDE autocomplete:
`typescript
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);
`
---
- API Documentation: API Docs
- Smart Contracts: Contracts
---
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)git commit -m 'Add some AmazingFeature'
3. Commit your changes ()git push origin feature/AmazingFeature`)
4. Push to the branch (
5. Open a Pull Request
---
- Issues: GitHub Issues
---
Built with ❤️ for the Mantle ecosystem