Skip to content

Repository files navigation

AutoFi Compliance Engine

The autofi-compliance-engine is the official enterprise compliance and tax-withholding companion extension for the AutoFi ecosystem. It automatically intercepts a slice of developer rewards passing through the core autofi-reward-router, locking estimated income tax obligations into an immutable Soroban escrow contract.

Developers can subsequently batch-release locked holdings directly to corporate or local tax portals via specialized fiat anchor rails or pull official cryptographically signed income proofs for personal tax filing declarations.

🎯 Features

  • Automated Escrow Pools: Divert statutory estimated tax percentages cleanly prior to regional bank off-ramps
  • Verifiable Income Proofs: Generates immutable transaction metadata logs for localized tax audit accounting
  • Regulated Settlement Integrations: Partners with regional financial anchors to match standard corporate or individual tax ledger payment formats
  • Cross-Contract Integration: Direct Soroban invocation from autofi-reward-router for real-time compliance processing
  • Webhook-based Event Processing: Asynchronous reward distribution events trigger automatic withholding calculations

πŸ—οΈ Architecture

autofi-compliance-engine/
β”œβ”€β”€ contracts/
β”‚   └── compliance_escrow/              # Soroban smart contract
β”‚       β”œβ”€β”€ Cargo.toml                  # Rust manifest
β”‚       └── src/
β”‚           └── lib.rs                  # EscrowLedger + contract impl
β”‚
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ index.ts                        # Main orchestration hook
β”‚   β”œβ”€β”€ server.ts                       # Express webhook server
β”‚   β”œβ”€β”€ config/
β”‚   β”‚   └── router.config.ts            # Router linking + env config
β”‚   β”œβ”€β”€ integrations/
β”‚   β”‚   β”œβ”€β”€ walletRouterClient.ts       # Cross-contract communication
β”‚   β”‚   └── webhookListener.ts          # Event handler
β”‚   β”œβ”€β”€ services/
β”‚   β”‚   β”œβ”€β”€ statementGen.ts             # Cryptographic proof generation
β”‚   β”‚   └── taxOffRamp.ts               # Tax settlement rails
β”‚   └── types/
β”‚       └── index.ts                    # TypeScript interfaces
β”‚
β”œβ”€β”€ package.json                        # Dependencies
β”œβ”€β”€ tsconfig.json                       # TypeScript config
β”œβ”€β”€ jest.config.js                      # Test configuration
β”œβ”€β”€ ROUTER_INTEGRATION.md               # Integration guide
└── README.md                           # This file

πŸ”„ Data Flow

autofi-reward-router (StellarFlow-Lab)
        ↓
   [Reward Distribution Event]
        ↓
webhook POST /compliance/webhook
        ↓
  handleComplianceIngestion()
        ↓
Calculate Withholding % β†’ Escrow Amount
        ↓
ComplianceEscrow.credit_escrow()
        ↓
On-Chain Escrow Storage (Soroban)
        ↓
generateSignedStatement()
        ↓
Developer Receipt + Tax Authority Settlement

πŸ“¦ Core Components

1. Soroban Smart Contract

Location: contracts/compliance_escrow/src/lib.rs

Manages immutable escrow ledgers for tax withholding:

#[contracttype]
pub struct EscrowLedger {
    pub total_withheld: u128,           // Amount locked in escrow
    pub compliance_tier: u32,            // Regional tax filing tier
    pub tax_authority_id: Vec<u8>,      // Authority identifier
}

#[contractimpl]
impl ComplianceEscrow {
    // Developer funds locked into escrow
    pub fn credit_escrow(env: Env, developer: Address, amount: u128, authority: Vec<u8>) {
        developer.require_auth();
        let mut ledger = env.storage().persistent().get(&"LEDGER").unwrap_or(Map::new(&env));
        // ... update ledger
        env.storage().persistent().set(&"LEDGER", &ledger);
    }

    // Settlement to tax authority
    pub fn release_to_authority(env: Env, clearing_agent: Address, developer: Address, amount: u128) {
        clearing_agent.require_auth();
        // ... deduct from escrow, dispatch to authority
    }

    // Query escrow balance
    pub fn get_escrow(env: Env, developer: Address) -> Option<EscrowLedger> {
        let ledger = env.storage().persistent().get(&"LEDGER")?;
        ledger.get(developer)
    }
}

2. Backend Orchestration

Location: src/index.ts

Subscribes to reward distribution events and triggers compliance processing:

export async function handleComplianceIngestion(payload: CoreWalletPayload): Promise<void> {
  const gross = parseFloat(payload.grossPayoutAmount);
  const taxWithheld = (gross * payload.withholdingPct) / 100;
  const netTakeHome = gross - taxWithheld;

  console.log(`πŸ“Š Processing Compliance for ${payload.developerAddress}:`);
  console.log(`   [Gross]: ${gross} ${payload.currencySymbol}`);
  console.log(`   [Escrowed Tax]: ${taxWithheld} ${payload.currencySymbol}`);
  console.log(`   [Net Payout]: ${netTakeHome} ${payload.currencySymbol}`);

  // Generate cryptographic proof
  const documentHash = await generateSignedStatement(
    payload.developerAddress,
    taxWithheld.toString(),
    payload.currencySymbol
  );

  console.log(`πŸ“ Tax Receipt: ${documentHash}`);
}

3. Webhook Server

Location: src/server.ts

Listens for reward.distributed events from autofi-reward-router:

export async function setupWebhookServer(): Promise<Express> {
  const app = express();
  app.use(express.json());

  const webhookListener = new WebhookListener(routerConfig.webhookSecret);
  const routerClient = await initializeRouterClient(routerConfig.mainRouterContractId);

  // Register handler for reward distribution events
  webhookListener.registerHandler('reward.distributed', handleComplianceIngestion);

  // Webhook endpoint
  app.post(routerConfig.webhookPath, async (req: Request, res: Response) => {
    try {
      const payload: WebhookPayload = req.body;
      await webhookListener.handleWebhook(payload);
      res.json({ success: true, message: 'Compliance processed' });
    } catch (error) {
      res.status(400).json({ error: (error as Error).message });
    }
  });

  // Health check
  app.get('/health', (req: Request, res: Response) => {
    res.json({
      status: 'healthy',
      router: routerClient.getContractId(),
      timestamp: new Date().toISOString(),
    });
  });

  return app;
}

export function startServer(port: number = routerConfig.webhookPort): void {
  setupWebhookServer().then((app) => {
    app.listen(port, () => {
      console.log(`πŸš€ Webhook server listening on port ${port}`);
    });
  });
}

4. Statement Generation

Location: src/services/statementGen.ts

Generates cryptographically signed income proofs:

export async function generateSignedStatement(
  developer: string,
  amountEscrowed: string,
  assetCode: string
): Promise<string> {
  const metadata: ComplianceStatement = {
    issuanceTimestamp: Date.now(),
    issuer: 'AutoFi Compliance Engine Protocol v1',
    subjectDeveloper: developer,
    withheldQuantum: amountEscrowed,
    denominatedAsset: assetCode,
    regulatoryStatus: 'ESCROWED_ON_CHAIN',
  };

  const signatureString = JSON.stringify(metadata);
  const cryptographicProofHash = crypto
    .createHash('sha256')
    .update(signatureString)
    .digest('hex');

  return `autofi-proof-0x${cryptographicProofHash}`;
}

5. Tax Off-Ramp Service

Location: src/services/taxOffRamp.ts

Handles settlement to regional tax authorities:

export class TaxOffRampService {
  private config: TaxOffRampConfig;

  constructor(config: TaxOffRampConfig) {
    this.config = config;
  }

  async validateCurrency(assetCode: string): Promise<boolean> {
    return this.config.supportedCurrencies.includes(assetCode);
  }

  async settleTaxPayment(
    developer: string,
    amount: string,
    assetCode: string
  ): Promise<string> {
    if (!(await this.validateCurrency(assetCode))) {
      throw new Error(`Currency ${assetCode} not supported in ${this.config.region}`);
    }

    // Settlement transaction ID
    return `settlement-${Date.now()}-${developer.substring(0, 8)}`;
  }

  async getOffRampStatus(developer: string, transactionId: string) {
    return {
      status: 'PENDING_AUTHORITY_REVIEW',
      timestamp: Date.now(),
    };
  }
}

6. Router Integration

Location: src/integrations/walletRouterClient.ts

Communicates with autofi-reward-router contract:

export class WalletRouterClient {
  private config: WalletRouterConfig;

  constructor(config: WalletRouterConfig) {
    this.config = config;
  }

  async registerComplianceHook(callbackUrl: string): Promise<void> {
    console.log(`βœ… Compliance Engine registered with router: ${this.config.contractId}`);
    console.log(`   Callback URL: ${callbackUrl}`);
  }

  getContractId(): string {
    return this.config.contractId;
  }
}

πŸš€ Quick Start

Prerequisites

  • Node.js 18+
  • Rust toolchain + Soroban CLI
  • git

Installation

git clone https://github.com/StellarFlow-Lab/autofi-compliance-engine.git
cd autofi-compliance-engine

# Install TypeScript dependencies
yarn install

# Build Soroban contract
cd contracts/compliance_escrow
cargo build
cd ../..

# Build TypeScript
yarn build

Environment Setup

Create .env.local:

AUTOFI_REWARD_ROUTER_CONTRACT_ID=CXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
COMPLIANCE_ESCROW_CONTRACT_ID=CXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
WEBHOOK_SECRET=your-webhook-signing-key
WEBHOOK_PORT=3001
SOROBAN_RPC_URL=https://soroban-testnet.stellar.org
SOROBAN_NETWORK=testnet

Run

# Development mode
yarn dev

# Production mode
yarn build && yarn start

Server listens on http://localhost:3001

Health Check

curl http://localhost:3001/health

Response:

{
  "status": "healthy",
  "router": "CXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
  "timestamp": "2026-06-17T16:54:00.000Z"
}

πŸ”— Integration with autofi-reward-router

The compliance engine automatically processes rewards distributed by the autofi-reward-router contract:

  1. Reward Distribution β†’ Router emits reward.distributed event
  2. Webhook Trigger β†’ Compliance engine receives webhook payload
  3. Withholding Calculation β†’ Applies configured tax percentage
  4. Escrow Lock β†’ Funds transferred to compliance escrow contract
  5. Tax Receipt β†’ Cryptographic proof generated for developer

See ROUTER_INTEGRATION.md for detailed setup.

πŸ“Š Data Types

CoreWalletPayload:

interface CoreWalletPayload {
  developerAddress: string;        // Recipient address
  grossPayoutAmount: string;       // Total before withholding
  withholdingPct: number;          // Tax withholding percentage
  currencySymbol: string;          // Asset code (USD, EUR, etc.)
}

EscrowLedger (On-Chain):

struct EscrowLedger {
  total_withheld: u128,            // Amount in escrow
  compliance_tier: u32,            // Tax filing tier
  tax_authority_id: Vec<u8>,       // Authority identifier
}

ComplianceStatement:

interface ComplianceStatement {
  issuanceTimestamp: number;       // When generated
  issuer: string;                  // Engine identifier
  subjectDeveloper: string;        // Developer address
  withheldQuantum: string;         // Amount escrowed
  denominatedAsset: string;        // Currency
  regulatoryStatus: string;        // Status (ESCROWED_ON_CHAIN)
}

πŸ“ Configuration

Location: src/config/router.config.ts

export const routerConfig = {
  mainRouterContractId: process.env.AUTOFI_REWARD_ROUTER_CONTRACT_ID || '',
  mainRouterRepoUrl: 'https://github.com/StellarFlow-Lab/autofi-reward-router',
  organizationUrl: 'https://github.com/orgs/StellarFlow-Lab/repositories',
  complianceEscrowContractId: process.env.COMPLIANCE_ESCROW_CONTRACT_ID || '',
  webhookSecret: process.env.WEBHOOK_SECRET || 'dev-secret',
  webhookPort: parseInt(process.env.WEBHOOK_PORT || '3001'),
  webhookPath: '/compliance/webhook',
  defaultWithholdingPct: 20,
  sorobanNetwork: process.env.SOROBAN_NETWORK || 'testnet',
  sorobanRpcUrl: process.env.SOROBAN_RPC_URL || 'https://soroban-testnet.stellar.org',
};

πŸ§ͺ Testing

# Run all tests
yarn test

# Run specific service tests
yarn test statementGen.ts
yarn test taxOffRamp.ts

# Test Soroban contract
cd contracts/compliance_escrow
cargo test

πŸ“š Project Structure Summary

Component Purpose Language
ComplianceEscrow Tax withholding escrow Rust (Soroban)
handleComplianceIngestion() Event processor TypeScript
TaxOffRampService Settlement handler TypeScript
generateSignedStatement() Proof generation TypeScript
WebhookListener Event subscription TypeScript
WalletRouterClient Router communication TypeScript
Webhook Server Event listener Express.js

πŸ” Security

  • Contract authorization checks via require_auth()
  • HMAC signature verification for webhooks
  • Immutable on-chain escrow storage
  • Cryptographic proof generation

πŸ“– Documentation

🀝 Contributing

This is 40% of the complete project. The remaining 60% will be developed as open-source contributions.

πŸ“„ License

[Your License Here]

🌟 Supported By

StellarFlow-Lab Β· AutoFi Ecosystem


Built with ❀️ for open-source compliance infrastructure

About

# AutoFi Compliance Engine The `autofi-compliance-engine` is the official enterprise compliance and tax-withholding companion extension for the AutoFi ecosystem. It automatically intercepts a slice of developer rewards passing through the core router, locking estimated income tax obligations into an immutable Soroban escrow contract.

Resources

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages