Skip to content

getmoltfi/smart-contracts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

MoltFi Smart Contracts

Onchain Banking for Autonomous AI Agents

MoltFi is an authorization-based onchain neobank designed to give AI agents autonomous economic capabilities. Built on Ethereum and Layer 2 networks (Base, Arbitrum, Optimism), MoltFi provides AI agents with programmable bank accounts that enable secure, policy-controlled transactions without human intervention for each payment.

Architecture

Core Contracts

1. MoltFiAccount.sol

The foundational smart account for AI agents. Each account is an ERC-4337 compatible smart contract wallet with:

  • Delegation Framework (ERC-7710): Limited, revocable permissions for AI agents
  • Multi-token Support: Native support for USDC, USDT, DAI, and other ERC-20 tokens
  • Role-based Access Control: Owner, Delegate, Admin, and Viewer roles
  • Emergency Controls: Freeze/unfreeze functionality for security incidents
  • Spending Limits: Daily, per-transaction limits enforced on-chain

2. AuthorizationEngine.sol

Real-time policy validation engine that enforces spending rules:

  • Velocity Control: Daily/weekly/monthly spending limits
  • Merchant Whitelisting: Approved recipient addresses only
  • Multi-party Approval: Threshold signatures for high-value transactions
  • Time Restrictions: Business hours or scheduled payment windows
  • Session-based Authorization: MPP-compatible for streaming micro-payments

3. MoltFiAccountFactory.sol

Standardized account deployment infrastructure:

  • Deterministic Account Creation: Predictable addresses
  • Batch Deployment: Gas-optimized multi-account creation
  • Registry Management: On-chain account discovery and verification
  • Default Token Configuration: Pre-configured stablecoin support

Supporting Libraries

PolicyLib.sol

Utility library for policy evaluation and spending tracking:

  • Daily/weekly/monthly spending trackers with automatic resets
  • Recipient whitelist validation
  • Velocity limit checking
  • Gas-optimized pure/view functions

Key Features

For Users (Agent Operators)

  • One-click Account Creation: Deploy AI agent accounts in seconds
  • Flexible Delegation: Grant limited permissions to AI agents
  • Real-time Monitoring: Dashboard with transaction history and spending analytics
  • Emergency Controls: Instant freeze and revoke capabilities
  • Multi-agent Management: Support for multiple AI agents under one account

For AI Agents (OpenClaw Integration)

  • Autonomous Transactions: Self-service payment execution within policy bounds
  • Balance Checking: Query account balances programmatically
  • Policy-aware: Agents can check authorization before attempting transactions
  • Gas Sponsorship: Paymaster integration for gasless operations (optional)

For Developers

  • Simple Integration: Standard Solidity interfaces
  • ERC-4337 Compatible: Works with existing AA infrastructure
  • Event-driven: Comprehensive event emission for monitoring
  • Multi-chain Ready: Deploy on Base, Ethereum, Arbitrum, Optimism, Polygon

Deployment

Prerequisites

npm install

Environment Setup

Create a .env file:

PRIVATE_KEY=your_private_key_here
INFURA_API_KEY=your_infura_key
ETHERSCAN_API_KEY=your_etherscan_key

# Optional: Override default token addresses
USDC_TOKEN_ADDRESS=0x...
USDT_TOKEN_ADDRESS=0x...
DAI_TOKEN_ADDRESS=0x...

Deploy to Network

# Deploy to Base Sepolia testnet
npx hardhat run scripts/deploy-all.js --network base-sepolia

# Deploy to Base mainnet
npx hardhat run scripts/deploy-all.js --network base

# Deploy to Ethereum mainnet
npx hardhat run scripts/deploy-all.js --network mainnet

Verify Contracts

npx hardhat verify --network base-sepolia <CONTRACT_ADDRESS> <CONSTRUCTOR_ARGS>

Usage Examples

1. Create AI Agent Account

const factory = await ethers.getContractAt("MoltFiAccountFactory", factoryAddress);

const tx = await factory.createAccount(
  "Trading Agent Alpha",    // Account name
  "openclaw-agent-001",     // Unique agent ID
  userAddress,              // Owner address
  []                        // Additional tokens (optional)
);

const receipt = await tx.wait();
const accountAddress = receipt.events[0].args.accountAddress;

2. Set Delegation for AI Agent

const account = await ethers.getContractAt("MoltFiAccount", accountAddress);

await account.setDelegation(
  agentWalletAddress,         // AI agent's wallet address
  ethers.parseUnits("1000", 6), // Daily limit: 1000 USDC
  ethers.parseUnits("100", 6),  // Per-tx limit: 100 USDC
  30,                          // Duration: 30 days
  []                           // Allowed contracts (empty = all)
);

3. Configure Spending Policy

const authEngine = await ethers.getContractAt("AuthorizationEngine", authEngineAddress);

const policy = {
  policyType: 1,               // VelocityControl
  dailyLimit: ethers.parseUnits("1000", 6),
  weeklyLimit: ethers.parseUnits("5000", 6),
  monthlyLimit: ethers.parseUnits("20000", 6),
  allowedRecipients: [],       // Empty = allow all
  approvalThreshold: ethers.parseUnits("500", 6), // Require approval above 500 USDC
  approvers: [admin1, admin2],
  minApprovers: 2,
  approvalTimeoutMinutes: 60,
  allowedTimeStart: 0,
  allowedTimeEnd: 86400
};

await authEngine.createPolicy(accountAddress, policy);

4. AI Agent Executes Transaction

// AI agent (with delegated permission) executes payment
const account = await ethers.getContractAt("MoltFiAccount", accountAddress, agentSigner);

await account.executeDelegatedTransaction(
  usdcAddress,                // Token address
  recipientAddress,           // Recipient
  ethers.parseUnits("50", 6), // Amount: 50 USDC
  "Payment for API access"    // Memo
);

5. Check Authorization (Before Transaction)

const authEngine = await ethers.getContractAt("AuthorizationEngine", authEngineAddress);

const request = {
  accountAddress: accountAddress,
  delegateAddress: agentWalletAddress,
  token: usdcAddress,
  amount: ethers.parseUnits("50", 6),
  recipient: recipientAddress,
  memo: "Test transaction",
  timestamp: Math.floor(Date.now() / 1000)
};

const [wouldAuthorize, reason] = await authEngine.checkAuthorization(request);

if (!wouldAuthorize) {
  console.log("Transaction would be declined:", reason);
}

Supported Networks

Network Chain ID USDC Address Status
Base Mainnet 8453 0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913 ✅ Ready
Base Sepolia 84532 0x036CbD53842c5426634e7929541eC2318f3dCF7e ✅ Ready
Ethereum Mainnet 1 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 ✅ Ready
Ethereum Sepolia 11155111 0x1c7D4B196Cb0C7B01d743Fbc6116a902379C7238 ✅ Ready
Arbitrum One 42161 - 🚧 Coming Soon
Optimism 10 - 🚧 Coming Soon
Polygon 137 - 🚧 Coming Soon

Security Considerations

Audits

  • Trail of Bits security audit
  • OpenZeppelin security review
  • Consensys Diligence audit

Status: Pre-audit. Do not use in production with real funds until audited.

Bug Bounty

We will launch a bug bounty program ($500K pool) before mainnet deployment.

Best Practices

  1. Never give AI agents direct private key access: Use delegation framework instead
  2. Start with conservative limits: Begin with small daily limits and increase gradually
  3. Monitor transactions: Set up alerts for unusual spending patterns
  4. Regular audits: Review delegation permissions and spending limits monthly
  5. Emergency procedures: Know how to freeze accounts quickly if needed

Testing

Run the full test suite:

npx hardhat test

Run specific test file:

npx hardhat test test/MoltFiAccount.test.js

Generate coverage report:

npx hardhat coverage

Gas Optimization

The contracts are optimized for gas efficiency:

  • Account Creation: ~2.5M gas
  • Delegation Setup: ~150K gas
  • Policy Creation: ~200K gas
  • Transaction Execution: ~120K gas (with policy checks)

License

MIT License - see LICENSE file for details.

Links

Support

For technical support or questions:


Built with ❤️ for the agentic AI economy

About

MoltFi Smart Contracts

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors