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.
- 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-routerfor real-time compliance processing - Webhook-based Event Processing: Asynchronous reward distribution events trigger automatic withholding calculations
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
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
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)
}
}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}`);
}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}`);
});
});
}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}`;
}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(),
};
}
}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;
}
}- Node.js 18+
- Rust toolchain + Soroban CLI
- git
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 buildCreate .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# Development mode
yarn dev
# Production mode
yarn build && yarn startServer listens on http://localhost:3001
curl http://localhost:3001/healthResponse:
{
"status": "healthy",
"router": "CXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"timestamp": "2026-06-17T16:54:00.000Z"
}The compliance engine automatically processes rewards distributed by the autofi-reward-router contract:
- Reward Distribution β Router emits
reward.distributedevent - Webhook Trigger β Compliance engine receives webhook payload
- Withholding Calculation β Applies configured tax percentage
- Escrow Lock β Funds transferred to compliance escrow contract
- Tax Receipt β Cryptographic proof generated for developer
See ROUTER_INTEGRATION.md for detailed setup.
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)
}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',
};# 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| 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 |
- Contract authorization checks via
require_auth() - HMAC signature verification for webhooks
- Immutable on-chain escrow storage
- Cryptographic proof generation
- ROUTER_INTEGRATION.md β Integration setup with
autofi-reward-router - package.json β Dependencies and scripts
- Soroban Docs β Contract reference
This is 40% of the complete project. The remaining 60% will be developed as open-source contributions.
[Your License Here]
StellarFlow-Lab Β· AutoFi Ecosystem
Built with β€οΈ for open-source compliance infrastructure