← Back to home

TriggerFi

Dynamic capital allocation infrastructure through real world triggers

Problem Statement

TriggerFi Project OverviewDynamic Capital Allocation InfrastructureTriggerFi converts "classic capital" into "smart capital" - capital that automatically shifts between assets using real-world information to maximize productivity.Problem StatementThere's $100T+ in global capital that's blind to real-world events. Current DeFi automation can only react to simple on-chain conditions, missing 99% of market-moving signals (inflation data, tariffs, supply chain disruptions, economic indicators). This creates massive inefficiencies - companies holding depreciating foreign currency reserves, treasuries sitting idle during inflation, traders missing correlations between traditional markets and crypto.Solution: Intelligent Limit Orders with User-Defined Real-World TriggersTriggerFi enables users to create intelligent limit orders that execute based on ANY real-world data source. Users input their own API endpoints, define triggering conditions, and let their capital automatically respond to global events via trustless 1inch swaps.Core FeaturesUser-Defined APIs: Input any API endpoint, key, and trigger conditionsComplex Logic: Combine multiple APIs with AND/OR operatorsAutomatic Integration: APIs automatically integrated into Chainlink FunctionsTrustless Execution: On-chain verification and execution via 1inchSmart Capital: Capital that autonomously optimizes based on world eventsTarget Audience (Priority Order)International Corporations- Managing foreign currency reserves ($10T+ market)Treasury Managers(DAOs, Corporations) - Managing $100M+ in stablecoinsInstitutional DeFi Traders- Seeking automated cross-market arbitrageTokenized Asset Issuers(RWA protocols) - Need dynamic liquidity managementArchitectureCurrent ImplementationFrontend: Next.js 14 with TypeScript, Tailwind CSS, shadcn/ui componentsSmart Contracts: Hardhat development environment with Solidity contractsDeFi Integration: 1inch Limit Order Protocol v4 for executionOracle Integration: Chainlink Functions for API calls and verificationOrder Builder: Creates 1inch orders with custom predicatesSystem Architecture1. Order Creation FlowUser inputs API endpoints, keys, and trigger conditionsUser defines comparison operators (>, <, =) and valuesMultiple APIs can be combined with AND/OR logicOrder signed as EIP-712 message (gasless)2. Predicate GenerationUser's APIs automatically inserted into Chainlink Function contractFunction becomes the predicate for 1inch limit orderSupports complex multi-condition logic3. ExecutionChainlink Functions periodically check API conditionsWhen predicate returns true, order becomes fillableTaker bot executes order on 1inchTrustless swap executionMVP Demo: JPY Stablecoin HedgingUse CaseA company trading with Japanese clients holds JPY stablecoins for efficient transactions. They want to protect against JPY devaluation.Demo PredicateCondition 1: US tariffs on Japanese cars > 15% (current rate)Condition 2: AND JPY inflation rate > 5% (currently ~3.3%)Action: Convert 1,000,000 JPYC to USDC at market rateEconomic ValueThese indicators suggest likely JPY depreciation, so automatic conversion minimizes capital loss and makes their capital more "productive".Blockchain Infrastructure AdvantagesInformation Objectivity: No manipulation of data, trustless verificationFull Capital Control: Users maintain custody, no intermediary risk24/7 Autonomous Execution: No banking hours or human interventionComposability: Other protocols can build on predicatesTransparency: All trades and conditions verifiable on-chainNo Counterparty Risk: Direct wallet-to-wallet executionCensorship Resistance: No institution can block capital movementsGlobal Accessibility: Anyone can create smart capital strategiesProgrammable Capital: Capital becomes responsive to world eventsLower Costs: No management fees, only gas for executionNo Regulatory Overhead: No compliance costs passed to usersTechnical Implementation DetailsChainlink Functions IntegrationUser APIs dynamically inserted into Function source codeHandles authentication (API keys, Bearer tokens) - encrypted with Chainlink DONParses responses to extract comparison valuesReturns boolean for predicate evaluationMVP: Batch check multiple orders to save gasPost-MVP: Transition to off-chain monitoring system ($50/month for 10,000 conditions vs $500,000 in gas)Post-MVP Alternative: TLS Notary integration for trustless HTTPS data verification1inch IntegrationUsing Limit Order Protocol v4Predicate contract calls Chainlink FunctionUses amountGetters for dynamic pricing (e.g., JPYC/USDC from Chainlink price feeds)Taker bot monitors and executes when conditions metAPI ConfigurationEndpoint: Full URL to APIAuthentication: API key, Bearer token, or OAuthResponse Path: JSON path to value (e.g.,data.inflation_rate)Comparison: >, <, or = with threshold valueLogic: AND/OR for multiple conditionsData Type: Currently only supports int256 (integers) for comparison valuesCurrent Limitations - Integer Values OnlyMVP Limitation: External API data must be numeric (int256) for comparisonsExamples of supported data:Inflation rate: 5.2 → 52 (multiply by 10 for decimal precision)Temperature: 75 (Fahrenheit)Price: 1850 (USD cents for $18.50)Percentage: 15 (for 15%)Examples of unsupported data (Post-MVP):Strings: "bullish", "active", "high risk"Booleans: true/false (must use 1/0 instead)Complex objects or arraysLogic Operator LimitationsCurrent MVP: Can only use ALL AND or ALL OR logicSupported logic patterns:A AND B AND C(all conditions must be true)A OR B OR C(any condition can be true)NOT supported (Post-MVP):Mixed operators:A AND (B OR C)Nested groups:(A AND B) OR (C AND D)NOT operators:A AND NOT BWhy this limitation: Simplifies Chainlink Function generation and predicate evaluationPost-hackathon: Will implement expression tree parser for complex logicPost-MVP EnhancementsString Comparisons: Support for equality checks on text valuesExample: "status == 'active'"Example: "alert_level == 'high'"Boolean Support: Native true/false handlingEnum Support: Predefined value setsRange Checks: "value BETWEEN 10 AND 20"Pattern Matching: Basic regex for stringsAPI Response ParsingSupports dot notation:data.rates.inflationSupports bracket notation:data['rates']['inflation']Supports array access:results[0].valueGraceful error handling with safe defaultsAutomatic type conversion to numbersUser can test paths in UI before savingDevelopment GuidelinesUse TypeScript for all new codeFollow React best practices with hooks and functional componentsImplement proper error handling for all blockchain interactionsTest smart contracts thoroughly before deploymentHandle API failures gracefullyImplement rate limiting for API callsUse proper gas estimation for all transactionsPrioritize user control and transparencyIMPORTANT: Environment Variables Issue (Hackathon Workaround)Due to Next.js environment variable issues and hackathon deadline:DO NOT use .env for sensitive variablesHardcode test values directly in filesThis is ONLY for hackathon demo with test walletsTest wallet has no real funds, so security is not criticalPost-hackathon: Fix proper env variable handlingTechnical SolutionsAPI Response ParsingJSONPath-like syntax with dot/bracket notationUI testing tool for path validationTemplate library for common APIsUpdate FrequencyMVP: 5-minute intervals (balance cost/responsiveness)User-configurable: 1-60 minutesFuture: Event-driven via webhooksError Handling3x retry with exponential backoffCache last valid responseSafe default values (-999999 for errors)User notifications for persistent failuresGas OptimizationBatch up to 10 orders per Chainlink call2-minute response cachingPost-MVP: Off-chain monitoring layerSecurityChainlink DON encrypted secrets for API keysNo keys stored in TriggerFi contractsUser controls key lifecycleFile Structure/app- Next.js app router pages/components- Reusable React components/contracts- Solidity smart contracts/lib- Utility functions and integrations/hooks- Custom React hooks/test- Test files for contracts and integrations/scripts- Deployment and monitoring scriptsCurrent Branch: on-chain-order-executionImplementing dynamic API integration with Chainlink Functions for real-world triggered limit orders.Deployed Contracts (Sepolia)DynamicAPIPredicateV2: 0x462C4Be5274e8C616C49B659b1cC3Fbdf7A26b6b (Active - uses Chainlink Functions properly)DynamicAPIPredicateV1: 0xd378Fbce97cD181Cd7A7EcCe32571f1a37E226ed (Deprecated - doesn't inherit FunctionsClient)DynamicAmountGetter: 0x5b02226E1820E80F6212f31Fe51Cf01A7B3D10b2 (Active - for dynamic pricing)IMPORTANT: Always use V2 contract for new development. V1 is kept for reference only.Important Technical Notes1inch IntegrationUsing 1inch Limit Order Protocol v4ASK FOR DOCUMENTATION when implementing taker botTaker bot questions to clarify:How does fillOrder work exactly?What are the gas optimization strategies?How to handle partial fills?What are maker/taker fee structures?Chainlink FunctionsMax execution time: 10 secondsMax memory: 128MBSupports HTTP requests with authConsider response size limitsPlan for API rate limitingIMPORTANT: When deploying to mainnet, update all Chainlink price feed addresses in contractsMVP PrioritiesSingle API condition support firstBasic comparison operators (>, <, =)JPY hedging demo with two APIsSimple UI for API configurationIgnore pre/post interactions for nowCustom Order Management (Not Using 1inch API)Store orders ourselves (on-chain events or Firebase)Allows gas-consuming predicatesTaker pays for predicate executionMore flexibility than 1inch API restrictionsPredicate Encoding (From Mentor)Use arbitraryStaticCall for calling contractsMust strip 0x prefix: hexDataSlice(params, 2)Predicates return uint256 (1 for true, 0 for false)See lib/predicate-encoder.ts for implementationMVP Simplifications (Due to Hackathon Timeline)Protocol-Owned Keeper ModelImplementation: TriggerFi operates the sole keeper serviceRevenue Model: Flat $2 fee per predicate check charged to takersUpdate Frequency: Every 5 minutes for all active ordersNote: Not the most gas-efficient solution, but fastest to implementSimplified Fee CollectionTakers pay fee when filling orders (not optimized for gas)Fee covers Chainlink Function costs + profit marginFuture optimization: Dynamic pricing based on update frequencyDeferred Problems (Post-MVP)Dead Order Problem: Orders that never fill still consume update costsFuture solution: Order expiry or deposit-based updatesUpdate Efficiency: Currently updates all orders every 5 minutesFuture solution: Smart updating based on proximity to triggerFee Structure: Flat fee doesn't account for order sizeFuture solution: Percentage-based or hybrid fee modelWhy These SimplificationsHackathon timeline requires fast implementationProves core concept without complex economicsEasy to understand and demonstrateCan be optimized post-MVP based on usage dataPredicate Verification & Fee SolutionProblem: Taker Gas WasteTakers can't access maker's API keys to check predicatesWithout checking, takers waste gas on orders that won't fillNeed solution that keeps API keys secure while enabling verificationSolution: Protocol-Owned Keeper with On-Chain CachingTriggerFi Keeper Service:Updates all predicates every 5 minutes using Chainlink FunctionsAPI keys remain encrypted in Chainlink DON (secure)Results stored on-chain in DynamicAPIPredicate contractFree Predicate Checking:Takers callcheckCondition()view function (costs no gas)Returns cached predicate result from last updateTakers only attempt fills when predicate = trueFee Structure: $2 Per UpdateCost Model: $2 per predicate update (every 5 minutes)Accumulation: Fees accumulate until order is filledExample: Order updated 10 times = $20 in feesPayment: Taker pays all accumulated fees when fillingReset: After successful fill, update counter resets to 0Implementation Details// In DynamicAPIPredicate contract mapping(bytes32 => uint256) public updateCount; // Track updates per predicate mapping(bytes32 => bool) public lastResult; // Cache predicate results uint256 public constant UPDATE_FEE = 2 * 10**18; // $2 in stablecoin // Keeper calls this every 5 minutes function checkConditions(bytes32 predicateId) external { // ... execute Chainlink Function ... updateCount[predicateId]++; } // Takers call this for free (view function) function checkCondition(bytes32 predicateId) external view returns (uint256) { return lastResult[predicateId] ? 1 : 0; } // Calculate fees owed function getUpdateFees(bytes32 predicateId) external view returns (uint256) { return updateCount[predicateId] * UPDATE_FEE; }Economic FlowTriggerFifronts ~$2 per update in Chainlink costsAccumulation: Costs accumulate as updateCount increasesRecovery: When taker fills, pays updateCount * $2Profit: TriggerFi profits from spread between actual costs and feesRisk: Unfilled orders = unrecovered monitoring costsWhy This WorksFor Takers: No wasted gas + can verify before fillingFor Makers: API keys secure + automatic monitoringFor TriggerFi: Revenue model that scales with usageIncentive Alignment: Quick fills = lower fees for takersDeploymentFirebase Hosting can be used for website deploymentCurrent Deployed Contracts (Sepolia Testnet)Smart ContractsDynamicAPIPredicateV2:0x462C4Be5274e8C616C49B659b1cC3Fbdf7A26b6b(Active)Properly inherits from FunctionsClientManages predicates for Chainlink FunctionsStores API conditions and resultsTracks update counts for fee calculationDynamicAPIPredicate (V1):0xd378Fbce97cD181Cd7A7EcCe32571f1a37E226ed(Deprecated)Original version - doesn't work with Chainlink FunctionsKept for reference onlyDynamicAmountGetter:0x5b02226E1820E80F6212f31Fe51Cf01A7B3D10b2(Active)Implements 1inch IAmountGetter interfaceCalculates dynamic pricing based on gas costs and keeper feesIntegrates with Chainlink price feedsChainlink InfrastructureFunctions Router:0xb83E47C2bC239B3bf370bc41e1459A34b41238D0DON ID:0x66756e2d657468657265756d2d7365706f6c69612d3100000000000000000000Subscription ID: 5385Price Feed Addresses (Sepolia)ETH/USD:0x694AA1769357215DE4FAC081bf1f309aDC325306BTC/USD:0x1b44F3514812d835EB1BDB0acB33d3fA3351Ee43JPY/USD:0x8A6af2B75F23831ADc973ce6288e5329F63D86c6USDC/USD: Hardcoded as 1:1 (no feed on Sepolia)Token Addresses (Sepolia)WETH:0xfff9976782d46cc05630d1f6ebab18b2324d6b14USDC:0x94a9D9AC8a22534E3FaCa9F4e7F2E2cf85d5E4C8DAI:0xFF34B3d4Aee8ddCd6F9AFFFB6Fe49bD371b8a357JPYC:0x431D5dfF03120AFA4bDf332c61A6e1766eF37BDBImportant NotesKeeper Address:0x93d43c27746D76e7606C55493A757127b33D7763Update these addresses when deploying new versionsAll addresses must be updated when moving to mainnet

Solution

Technical Implementation DetailsChainlink Functions IntegrationUser APIs dynamically inserted into Function source codeHandles authentication (API keys, Bearer tokens) - encrypted with Chainlink DONParses responses to extract comparison valuesReturns boolean for predicate evaluationMVP: Batch check multiple orders to save gasPost-MVP: Transition to off-chain monitoring system ($50/month for 10,000 conditions vs $500,000 in gas)Post-MVP Alternative: TLS Notary integration for trustless HTTPS data verification1inch IntegrationUsing Limit Order Protocol v4Predicate contract calls Chainlink FunctionUses amountGetters for dynamic pricing (e.g., JPYC/USDC from Chainlink price feeds)Taker bot monitors and executes when conditions met

Hackathon

ETHGlobal Unite

2025

Contributors