DefiUnite-Jincubator
Limit Order Protocol swap execution, smart orders, treasury and resource management + NEAR Fusion+
Problem Statement
Unite Defi 2025 JincubatorJincubator Unite Defi OverviewJis a research and development lab focusing on Solving, Arbitrage and Capital EfficientJincubator Limit Order ProtocolThis protocol implements four key enhancements to the1:Enhanced Swap Execution:TintegratesTto enable complex swaps across multiple DEXs without upfront liquidityStop Loss and Profit Taking Orders:OOracle-based (starting with chainlink) pricing calculator for advanced order strategiesTreasury Management:Renables makers and takers to immediately balance their funds to a treasury (and moving forward more advanced asset management strategies).Resource Management:Cintegrates the1withTforEsupport and moving forward integration with additional cross chain intent standards such asEleveragingMandA.Enhanced Swap ExecutionWe integrate with Tycho's indexing, simulation and execution via a TcyhoSwapExecutor which allows Solvers to provide a payload with complex routing solutions across multiple liquidity protocols. The design for United Defi allows the taker to submit a Payload with Call Data which will be executed as part of the TakerInteraction flow. This allows, if permitted by the maker, the solver to use the takers tokens and execute the trade without providing any upfront capital.Stop Loss and Profit Taking OrdersThe OracleCalculator extension is a powerful addition to the 1inch Limit Order Protocol that enables dynamic pricing based on Chainlink oracle data. This extension allows orders to be filled at prices that are calculated on-chain using real-time oracle feeds, making it possible to create orders that automatically adjust to market conditions.Treasury ManagementImplemented as an IPostInteraction the RebalancerInteraction contract allows both makers and takers to instantly move their funds to their Treasury of choice.Resource ManagementWe Implemented integration with an ERC-6909 compliant locking mechanism enabling advanced resource management capabilities and laying the foundation to extend the 1inch Limit Order Protocol to open standards such as ERC-7683.NEAR FUSION+ Smart Contract DevelopmentNEAR Fusion+ is a comprehensive DeFi protocol that migrates 1inch's proven Limit Order Protocol and Cross-Chain Swap functionality to the NEAR blockchain. The system provides two primary capabilities: advanced limit order trading with partial fills and extensible features, and atomic cross-chain swaps secured by time-locked escrow contracts.
Solution
Please see https://unite-design.jincubator.comImplementation Limit Order ProtocolCore ComponentsCompact: ERC-6909 enabled Chainlink calculator for price discoveryResourceManager: Manages resource locks for ERC-6909 integrationTychoSwapExecutor: Executes complex swaps using Tycho ExecutionCompactInteraction: Post-interaction handler for resource allocationRebalancerInteraction: Treasury management and portfolio rebalancingOracleCalculator: Price oracle integration for advanced order strategiesKey FeaturesResource Locking: ERC-6909 compliant resource managementMulti-DEX Execution: Cross-platform swap execution via TychoAdvanced Order Types: Stop-loss and take-profit ordersTreasury Management: Automated portfolio rebalancingOracle Integration: Chainlink price feeds for accurate pricingKey Technology EnhancementsSolidity based tests including a migration fromOrderUtils.jsto solidity basedOSolidity^0.8.30compatibility provided by creating an interfaceIand introducingLfor testing.ArchitectureInteractionsEnhanced Swap ExecutionTycho Execution FlowTycho ComponentsActorsMakerCreates orders specifying the spread price they are looking for (currently using chainlink Oracle)Solver ServiceMonitors 1inch Intents createdMonitors Liquidity Positions on Chain using Tycho-indexerSimulates Solves for Orders (to see if profitable)Calls Resolver Contract to execute the SwapSolver Payload - encoded to call TychoResolver a modified version of Tycho ExecutionCalls Order Fill passingtarget: TychoResolver addressinteraction: SolverPayloadResolver Contract (modified version combining ResolverCrossChain and Tycho Dispatcher)Called by LimitOrderProtocol as part of Order.fillExecutes swap using Makers TokensProvides TakerToken to Relayer to pass back to TakerTransfers excess maker (or taker) tokens to TreasuryImplementation Approach1. TychoFillPredicate.sol (Predicate): copied from OracleCalculator.sol 2. TychoFillInteraction.sol : copied from RebalancerInteraction.sol 3. TychoResolver.sol: Copied from ResolverCrossChain.sol and Dispatcher.sol 4. Tests copied from RebalancerInteraction.t.sol and enhanced with 1. Creation of Swap (MakerTokens to TakerTokens) similar to 2. Call of Fill Contract passing 1. target: TychoResolver address 2. interaction: SolverPayload 3. Checking of Treasurer Balances after swap is executedFlowInteractionsInteractions are callbacks that enable the execution of arbitrary code, which is provided by the maker’s order or taker’s fill execution.The order execution logic includes several steps that also involve interaction calls:Validate the orderCall the maker's pre-interactionTransfer the maker's asset to the takerCall the taker's interactionTransfer the taker's asset to the makerCall the maker's post-interactionEmit the OrderFilled eventCalls are executed in the context of the limit order protocol. The target contract should implement theIPreInteractionorIPostInteractioninterfaces for the maker's pre- and post-interactions and theITakerInteractioninterface for the taker's interaction. These interfaces declare the single callback function for maker and taker interactions, respectively.Here is how the maker’s pre- & post- interactions and the taker’s interaction are defined in the interfaces://Maker's pre-interaction function preInteraction( IOrderMixin.Order calldata order, bytes32 orderHash, address taker, uint256 makingAmount, uint256 takingAmount, uint256 remainingMakingAmount, bytes calldata extraData ) external; //Maker's post-interaction function postInteraction( IOrderMixin.Order calldata order, bytes32 orderHash, address taker, uint256 makingAmount, uint256 takingAmount, uint256 remainingMakingAmount, bytes calldata extraData ) external; //Taker's interaction function takerInteraction( IOrderMixin.Order calldata order, bytes32 orderHash, address taker, uint256 makingAmount, uint256 takingAmount, uint256 remainingMakingAmount, bytes calldata extraData ) external returns(uint256 offeredTakingAmount);Resolver Contract executes calls to Tycho Dispatcher or RouterThree functionspreInteraction: used in OracleCalculator (to ensure price before swap)takerInteraction used in SwapExecutor to Execute Swap by TakerpostInteraction used in Rebalancer to Send Funds to TreasuryDesign QuestionsInterface Compatibility:How will the TychoResolver interface be defined to ensure compatibility with the LimitOrderProtocol bytecode deployment approach?Should we create a custom interface for TychoResolver or use the concrete type like the working project?Predicate Logic:What predicate logic will TychoFill.sol use? Will it be similar to OracleCalculator.sol with price comparisons?How will the predicate determine when a solve is profitable vs. when it should execute?Solver Payload Structure:What data structure will the SolverPayload contain? Will it include target addresses, amounts, and execution parameters?How will the payload be encoded/decoded between the Solver Service and TychoResolver?Treasury Integration:How will excess tokens be calculated and transferred to Treasury?What mechanism will prevent MEV attacks on the treasury transfers?Error Handling:How will failed solves be handled? Will orders be cancelled or retried?What happens if the TychoResolver execution fails during the order fill?Gas Optimization:How will the solver service optimize gas costs across multiple orders?Will batch processing be implemented for multiple orders?Oracle Integration:Will TychoFill use the same Chainlink oracle approach as OracleCalculator ?How will price feeds be validated and updated?Cross-Chain Considerations:How will the ResolverCrossChain functionality be integrated with Tycho Dispatcher?What bridge mechanisms will be used for cross-chain swaps?Implementation PlanPhase 1: Core Contract DevelopmentCreateTychoFill.solbased onOracleCalculator.solImplement predicate logic for profitable solve detectionAdd Tycho-specific price calculation methodsEnsure interface compatibility with LimitOrderProtocolCreateTychoFillInteraction.solbased onRebalancerInteraction.solImplement post-interaction logic for treasury transfersAdd balance validation and excess token calculationIntegrate with TychoResolver for swap executionPhase 2: Resolver Contract DevelopmentCreateTychoResolver.solcombining ResolverCrossChain and Dispatcher functionalityImplement swap execution using maker tokensAdd taker token provision for relayerIntegrate treasury transfer logicEnsure proper error handling and revert conditionsPhase 3: Testing FrameworkCreate comprehensive test suite based onRebalancerInteraction.t.solTest order creation with Tycho-specific predicatesTest solver payload encoding/decodingTest treasury balance validationTest cross-chain swap scenariosTest error conditions and edge casesPhase 4: Integration TestingTest end-to-end flow from order creation to executionValidate predicate execution with bytecode deploymentTest solver service integration with Tycho-indexerVerify treasury transfers and balance calculationsPhase 5: Optimization and SecurityImplement gas optimization strategiesAdd comprehensive error handlingImplement MEV protection mechanismsAdd monitoring and logging capabilitiesPhase 6: Deployment and MonitoringDeploy contracts with proper bytecode generationSet up monitoring for solver serviceImplement alerting for failed solvesAdd analytics for treasury performanceStop Loss and Profit Taking OrdersOracle Example OrderOracle Order IntegrationOverviewThe OracleCalculator extension is a powerful addition to the 1inch Limit Order Protocol that enables dynamic pricing based on Chainlink oracle data. This extension allows orders to be filled at prices that are calculated on-chain using real-time oracle feeds, making it possible to create orders that automatically adjust to market conditions.1. What the OracleCalculator Extension DoesThe OracleCalculator extension serves as anIAmountGetterimplementation that:Calculates dynamic exchange ratesusing Chainlink oracle dataSupports both single and double oracle pricingfor different token pairsApplies configurable spreadsto provide maker/taker incentivesHandles inverse pricingfor tokens quoted in different base currenciesValidates oracle freshnessto ensure price data is current (within 4 hours)Integrates with predicatesfor conditional order executionKey Features:Single Oracle Pricing: Uses one oracle to price a token relative to ETH or USDDouble Oracle Pricing: Uses two oracles to price custom token pairs (e.g., INCH/DAI)Spread Application: Applies maker and taker spreads to create profitable order booksInverse Flag Support: Handles cases where oracle prices need to be invertedOracle Freshness Check: Ensures oracle data is not stale (within 4 hours TTL)2. Types of Orders That Can Be CreatedA. Single Oracle OrdersOrders that use one Chainlink oracle to price a token relative to ETH or USD:ETH → DAI: Using DAI/ETH oracleDAI → ETH: Using DAI/ETH oracle with inverse flagWETH → USDC: Using USDC/ETH oracleUSDC → WETH: Using USDC/ETH oracle with inverse flagB. Double Oracle OrdersOrders that use two oracles to price custom token pairs:INCH → DAI: Using INCH/ETH and DAI/ETH oraclesDAI → INCH: Using DAI/ETH and INCH/ETH oraclesCustom Token Pairs: Any combination of tokens with available oraclesC. Conditional Orders (Predicates)Orders that only execute under specific oracle conditions:Stop-Loss Orders: Execute only when price falls below thresholdTake-Profit Orders: Execute only when price rises above thresholdRange Orders: Execute only within specific price ranges3. Fields Passed to the Extension and How They Are PopulatedExtension Data StructureThe extension data is passed asbytes calldata extraDatato thegetMakingAmountandgetTakingAmountfunctions:function getMakingAmount( IOrderMixin.Order calldata order, bytes calldata extension, bytes32 orderHash, address taker, uint256 takingAmount, uint256 remainingMakingAmount, bytes calldata extraData // ← Extension data here ) external view returns (uint256)Single Oracle Data FormatFor single oracle pricing, theextraDatacontains:[1 byte flags][20 bytes oracle address][32 bytes spread]Flags Byte:Bit 7 (0x80): Inverse flag - if set, invert the oracle priceBit 6 (0x40): Double price flag - if set, use double oracle modeBits 0-5: ReservedExample:// DAI/ETH oracle at 0x1234... with 0.99 spread, no inverse bytes memory data = abi.encodePacked( bytes1(0x00), // flags: no inverse, no double price address(daiOracle), // oracle address uint256(990000000) // spread: 0.99 (990000000 / 1e9) );Double Oracle Data FormatFor double oracle pricing, theextraDatacontains:[1 byte flags][20 bytes oracle1][20 bytes oracle2][32 bytes decimalsScale][32 bytes spread]Example:// INCH/DAI pricing using INCH/ETH and DAI/ETH oracles bytes memory data = abi.encodePacked( bytes1(0x40), // flags: double price mode address(inchOracle), // oracle1: INCH/ETH address(daiOracle), // oracle2: DAI/ETH int256(0), // decimalsScale: no adjustment uint256(1010000000) // spread: 1.01 (1010000000 / 1e9) );How Fields Are PopulatedOracle Addresses: Retrieved from Chainlink's oracle registry or deploymentSpreads: Calculated based on desired maker/taker incentives (typically 0.99 for maker, 1.01 for taker)Flags: Set based on pricing requirements (inverse needed, double oracle needed)Decimals Scale: Used to adjust for different oracle decimal precisions4. Test Case WalkthroughTest Case 1: ETH → DAI Chainlink OrderScenario: Maker wants to sell 1 ETH for DAI at oracle price with spreadsOrder Details:Maker: makerAddrTaker: takerAddrMaker Asset: WETH (1 ether)Taker Asset: DAI (4000 ether)Oracle: DAI/ETH at 0.00025 ETH per DAI (1 ETH = 4000 DAI)Extension Data:// Making amount data (maker spread: 0.99) bytes memory makingAmountData = abi.encodePacked( chainlinkCalcAddress, // Calculator address bytes1(0x00), // No inverse flag oracleAddress, // DAI oracle uint256(990000000) // 0.99 spread ); // Taking amount data (taker spread: 1.01) bytes memory takingAmountData = abi.encodePacked( chainlinkCalcAddress, // Calculator address bytes1(0x80), // Inverse flag set oracleAddress, // DAI oracle uint256(1010000000) // 1.01 spread );Execution Flow:Taker callsfillOrderArgswith 4000 DAIProtocol callsgetTakingAmountwith 4000 DAICalculator applies 1.01 spread: 4000 * 1.01 = 4040 DAIProtocol callsgetMakingAmountwith 4040 DAICalculator applies 0.99 spread: 4040 * 0.99 / 4000 = 0.99 ETHOrder executes: taker receives 0.99 ETH, maker receives 4000 DAIResult: Taker pays 4000 DAI, receives 0.99 ETH (effective rate: 1 ETH = 4040.4 DAI)Test Case 2: DAI → ETH Chainlink OrderScenario: Maker wants to sell 4000 DAI for ETH at oracle priceOrder Details:Maker: makerAddrTaker: takerAddrMaker Asset: DAI (4000 ether)Taker Asset: WETH (1 ether)Oracle: DAI/ETH at 0.00025 ETH per DAIExtension Data:// Making amount data (inverse + maker spread) bytes memory makingAmountData = abi.encodePacked( chainlinkCalcAddress, bytes1(0x80), // Inverse flag oracleAddress, uint256(990000000) // 0.99 spread ); // Taking amount data (no inverse + taker spread) bytes memory takingAmountData = abi.encodePacked( chainlinkCalcAddress, bytes1(0x00), // No inverse flag oracleAddress, uint256(1010000000) // 1.01 spread );Execution Flow:Taker calls withmakingAmountflag set to trueProtocol callsgetMakingAmountwith 4000 DAICalculator applies inverse + 0.99 spread: 4000 * 0.99 / 4000 = 0.99 ETHProtocol callsgetTakingAmountwith 0.99 ETHCalculator applies 1.01 spread: 0.99 * 1.01 = 1.01 ETHOrder executes: taker receives 4000 DAI, maker receives 1.01 ETHResult: Taker pays 1.01 ETH, receives 4000 DAI (effective rate: 1 ETH = 3960.4 DAI)Test Case 3: INCH → DAI Double Oracle OrderScenario: Maker wants to sell 100 INCH for DAI using double oracle pricingOrder Details:Maker: makerAddrTaker: takerAddrMaker Asset: INCH (100 ether)Taker Asset: DAI (632 ether)Oracles: INCH/ETH (0.0001577615249227853 ETH) and DAI/ETH (0.00025 ETH)Extension Data:// Making amount data (double oracle + maker spread) bytes memory makingAmountData = abi.encodePacked( chainlinkCalcAddress, bytes1(0x40), // Double price flag address(daiOracle), // Oracle1: DAI/ETH address(inchOracle), // Oracle2: INCH/ETH int256(0), // No decimals adjustment uint256(990000000) // 0.99 spread ); // Taking amount data (double oracle + taker spread) bytes memory takingAmountData = abi.encodePacked( chainlinkCalcAddress, bytes1(0x40), // Double price flag address(inchOracle), // Oracle1: INCH/ETH address(daiOracle), // Oracle2: DAI/ETH int256(0), // No decimals adjustment uint256(1010000000) // 1.01 spread );Execution Flow:Taker calls withmakingAmountflag set to trueProtocol callsgetMakingAmountwith 100 INCHCalculator applies double oracle calculation:INCH price in ETH: 0.0001577615249227853DAI price in ETH: 0.00025INCH/DAI rate: 0.0001577615249227853 / 0.00025 = 0.631046With 0.99 spread: 100 _ 0.631046 _ 0.99 = 62.47 DAIProtocol callsgetTakingAmountwith 62.47 DAICalculator applies inverse calculation with 1.01 spreadOrder executes with calculated amountsResult: Complex pricing based on two oracle feeds with spread adjustmentsTest Case 4: Stop-Loss Order with PredicateScenario: Maker wants to sell INCH for DAI only if INCH/DAI price falls below 6.32Order Details:Maker: makerAddrTaker: takerAddrMaker Asset: INCH (100 ether)Taker Asset: DAI (631 ether)Predicate: INCH/DAI price < 6.32Predicate Construction:// Build price call for predicate bytes memory priceCall = abi.encodeWithSelector( OracleCalculator .doublePrice.selector, inchOracle, // INCH/ETH oracle daiOracle, // DAI/ETH oracle int256(0), // No decimals adjustment 1 ether // Base amount ); // Build predicate call bytes memory predicate = abi.encodeWithSelector( swap.lt.selector, // Less than comparison 6.32 ether, // Threshold: 6.32 abi.encodeWithSelector( swap.arbitraryStaticCall.selector, address(oracleCalculator ), priceCall ) );Execution Flow:Order fill is attemptedProtocol evaluates predicate before executionPredicate callsOracleCalculator .doublePrice()with oracle dataCalculated INCH/DAI price is compared to 6.32 thresholdIf price < 6.32: order executes normallyIf price ≥ 6.32: order reverts with predicate failureResult: Order only executes when INCH/DAI price is below the specified thresholdTest Case 5: Simple Order Without ExtensionScenario: Basic order without any Chainlink integrationOrder Details:Maker: makerAddrTaker: takerAddrMaker Asset: WETH (1 ether)Taker Asset: DAI (4000 ether)No extensions or predicatesExecution Flow:Taker callsfillOrderArgswith 4000 DAINo extension data providedProtocol uses default proportional calculationOrder executes at fixed 1:4000 ratioResult: Simple fixed-rate order execution without dynamic pricingKey Implementation DetailsOracle Freshness Checkif (updatedAt + _ORACLE_TTL < block.timestamp) revert StaleOraclePrice();Ensures oracle data is not older than 4 hoursPrevents execution with stale price dataSpread Applicationreturn spread * amount * latestAnswer.toUint256() / (10 ** oracle.decimals()) / _SPREAD_DENOMINATOR;Spreads are applied as multipliers (e.g., 990000000 = 0.99)_SPREAD_DENOMINATOR = 1e9for 9-decimal precisionDouble Oracle Calculationresult = amount * latestAnswer1.toUint256(); if (decimalsScale > 0) { result *= 10 ** decimalsScale.toUint256(); } else if (decimalsScale < 0) { result /= 10 ** (-decimalsScale).toUint256(); } result /= latestAnswer2.toUint256();Calculates cross-oracle pricing for custom token pairsHandles decimal precision adjustments between oraclesThis extension enables sophisticated DeFi applications that can automatically adjust to market conditions while providing liquidity providers with profitable spreads.Treasury ManagementTreasury Management FlowRebalancer RequirementsCreate an Interaction Contract called RebalancerInteraction.sol (in the src directory)Create a test contract called RebalancerInteraction.t.sol (in the test directory)In RebalancerInteraction.t.solCreate test scenarios the same as in OracleCalculator .t.solAdd to that an Interaction using RebalancerInteraction.sol whichTakes the output tokens the taker receivesTransfers them to a third wallet (addr3) which is a treasurerIf the transfer fails reject the order.Rebalancer ImplementationThe Rebalancer implementation has been successfully completed with the following components:1. RebalancerInteraction.sol (src directory)Purpose: Post-interaction contract that transfers output tokens to a treasurer wallet after successful order execution.Key Features:ImplementsIPostInteractioninterface for Limit Order Protocol integrationTransfers the taker's received tokens (maker asset) to a designated treasurer addressUsesSafeERC20for secure token transfers with proper error handlingReverts the entire order if transfer fails, ensuring atomic executionEmitsTokensTransferredToTreasurerevents for successful transfersValidates treasurer address in constructor to prevent zero address usageCore Functionality:function postInteraction( IOrderMixin.Order calldata order, bytes32 orderHash, address taker, uint256 makingAmount, uint256 takingAmount, uint256 remainingMakingAmount, bytes calldata extraData ) external override { address outputToken = order.makerAsset; uint256 outputAmount = makingAmount; try IERC20(outputToken).safeTransferFrom(taker, treasurer, outputAmount) { emit TokensTransferredToTreasurer(outputToken, taker, treasurer, outputAmount); } catch { revert TransferFailed(); } }2. RebalancerInteraction.t.sol (test directory)Purpose: Comprehensive test suite that replicates all OracleCalculator scenarios with added treasurer functionality.Test Coverage:Single Oracle Orders: ETH→DAI, DAI→ETH with treasurer receiving output tokensDouble Oracle Orders: INCH→DAI with complex pricing and treasurer transferConditional Orders: Stop-loss orders with predicate validation and treasurer transferSimple Orders: Basic orders without Chainlink but with treasurer transferFailure Scenarios: Tests unauthorized transfers that should revertTest Scenarios Implemented:test_eth_to_dai_chainlink_order_with_rebalancer()- Single oracle ETH→DAItest_dai_to_eth_chainlink_order_with_rebalancer()- Single oracle DAI→ETH with inversetest_dai_to_1inch_chainlink_order_takingAmountData_with_rebalancer()- Double oracle INCH→DAItest_dai_to_1inch_chainlink_order_makingAmountData_with_rebalancer()- Double oracle with making amounttest_dai_to_1inch_stop_loss_order_with_rebalancer()- Conditional order with predicatetest_dai_to_1inch_stop_loss_order_predicate_invalid_with_rebalancer()- Invalid predicate testtest_eth_to_dai_stop_loss_order_with_rebalancer()- ETH→DAI with stop-losstest_simple_order_without_extension_with_rebalancer()- Basic order with treasurertest_simple_order_with_different_amounts_with_rebalancer()- Partial amountstest_rebalancer_transfer_failure()- Failure scenario testing3. Key Implementation DetailsPost-Interaction IntegrationEach test includesbuildPostInteractionCalldata(address(rebalancerInteraction))Post-interaction data is added to order extensions viaPostInteractionDataTreasurer (addr3) receives the output tokens after successful order executionTransfer LogicTakes output tokens: The tokens the taker receives (maker asset from the order)Transfers to treasurer: Moves tokens to addr3 (treasurer wallet) usingsafeTransferFromRejects order on failure: If transfer fails, entire order reverts withTransferFailederrorTest VerificationEach test verifies:Order executes successfullywith Chainlink pricing (where applicable)Treasurer receives tokens:assertEq(token.balanceOf(addr3), expectedAmount)All balances are correctfor maker, taker, and treasurerFailure scenarios revertwhen transfers are unauthorizedError HandlingTransferFailed: Reverts entire order ifsafeTransferFromfailsInvalidTreasurer: Prevents deployment with zero address treasurerPredicate failures: Orders with invalid predicates revert before interaction4. Integration with Limit Order ProtocolThe implementation seamlessly integrates with the existing Limit Order Protocol:Extension System: UsesPostInteractionDataextension for post-execution callbacksOrder Flow: Maintains existing order execution flow while adding treasurer transferAtomic Execution: Ensures either complete success (order + transfer) or complete failureEvent Emission: Provides transparency throughTokensTransferredToTreasurerevents5. Security ConsiderationsSafeERC20: Uses OpenZeppelin's SafeERC20 for secure token transfersTry-Catch: Graceful error handling prevents partial state changesAddress Validation: Constructor validates treasurer addressAtomic Operations: Order reverts entirely if transfer failsAuthorization: Relies on existing token approval mechanisms6. Use CasesThis implementation enables:Automated Treasury Management: Automatic transfer of trading profits to treasuryRisk Management: Centralized control of trading outputsCompliance: Regulatory requirements for fund segregationPortfolio Rebalancing: Systematic reallocation of trading proceedsThe Rebalancer implementation successfully meets all requirements from the specification and provides a robust, secure, and comprehensive solution for automated treasury management in limit order trading.Test Results10 out of 10 tests passing (100% success rate)✅All Tests Passing:test_eth_to_dai_chainlink_order_with_rebalancer()- Single oracle ETH→DAItest_dai_to_eth_chainlink_order_with_rebalancer()- Single oracle DAI→ETH with inversetest_eth_to_dai_stop_loss_order_with_rebalancer()- Stop-loss with predicatetest_simple_order_without_extension_with_rebalancer()- Basic order without extensionstest_simple_order_with_different_amounts_with_rebalancer()- Different order amountstest_rebalancer_transfer_failure()- Transfer failure handlingtest_dai_to_1inch_stop_loss_order_predicate_invalid_with_rebalancer()- Invalid predicatetest_dai_to_1inch_chainlink_order_makingAmountData_with_rebalancer()- Double oracle with making amounttest_dai_to_1inch_chainlink_order_takingAmountData_with_rebalancer()- Double oracle with taking amounttest_dai_to_1inch_stop_loss_order_with_rebalancer()- Complex double oracle with stop-loss predicate🎯Core Functionality Verified:✅ Post-interaction transfers tokens to treasurer✅ Proper token approvals and transfers✅ Balance verification accounting for treasurer transfers✅ Error handling with transfer failures✅ Atomic execution (orders either complete fully or revert entirely)✅ Support for multiple token types (WETH, DAI, INCH)✅ Complex oracle-based pricing scenariosResource ManagementResource Management ArchitectureResource Management ComponentsRequirementsRead lib\the-compact\README.md (open in editor) to understand how the compact worksWe are looking to create an end to end flow whereWe register a new contract ResourceManager.sol as a ResourceManagerWe Register ChainLinkCompactInteraction.sol as the ArbiterThe Maker (the Swapper in compact terms signs permission for their tokens (or ETH) to be stored in the-compact as ERC-6909)ChainLinkCompact.sol checks that the we have a ResourceLock for the amount required.ChainLinkCompact then executes the trade using the same logic that was in ChainLinkCalculator and creates a resource lock for their (tokens/ETH)ChainLinkCompactInteraction is copied from RebalancerInteraction it takes the output tokens provided by the Taker andIf they are >= TakerAmount then it calls the ResourceManager to lock the fundsIt then does the token transfer to the treasurer the same as it was done in the original RebalancerInteractionDesign QuestionsResource Manager Registration: How should we register the LimitOrderProtocol as a ResourceManager in The Compact? Should it be a separate contract or integrated directly?Answer: We are registering it as a separate contract let's call it ResourceManager.sol and this contract will be called by ChainLinkCompact to lock the resources before calling the swap on LimitOrderProtoclArbiter Implementation: Should ChainLinkCompactInteraction.sol be a standalone arbiter or integrated with existing ChainLinkCalculator logic?Answer: It should be Standalone ChainLinkCalculator and RebalancerInteraction remain unchangedToken Locking Strategy: Should makers lock their entire balance upfront or lock tokens dynamically when orders are matched?Answer: Initially Lock their whole balanceResource Lock Scope: Should resource locks be chain-specific or multichain for cross-chain order execution?Answer: Chain-specificAllocator Selection: Which allocator should we use for the resource locks? Should we create a custom allocator or use existing ones like Smallocator/Autocator?Answer: Create a custom Allocator based on Autocator(which is used for End User signing which is the Maker in our case)The logic for calling this should be in ChainLinkCompact.t.solMoving forward we will also create a custom Smallocator used when smart contract call thisEIP-712 Signature Structure: How should we structure the EIP-712 signatures for the compact agreements? Should we include mandate data for additional conditions?Answer: For Phase 1 we do not need to add mandate data or Solver Payloads we will incorporate those in a later phaseFallback Mechanisms: What should happen if the arbiter fails to process a claim? Should we implement emissary fallbacks?If an arbiter fails to process the claim the swap should revertGas Optimization: How can we optimize gas usage for the ERC-6909 integration, especially for batch operations?We will optimize gas in phase 2Error Handling: How should we handle cases where resource locks are insufficient or expired?We revert the transaction with custom errors stating the reason for the failureIntegration Points: Should the ERC-6909 functionality be optional (opt-in) or mandatory for all orders?Optional set by a boolean ERC-6909 flag for nowLater this may move to an enum with additional swap typesImplementationPhase 1: Core Contract DevelopmentCreate ResourceManager.sol- New contractRegister as ResourceManager in The CompactHandle resource lock creation and management for makersImplement allocator integration for order validationCalled by ChainLinkCompact to lock resources before swap executionCreate ChainLinkCompact.sol- Copy from ChainLinkCalculator.solAdd ERC-6909 flag for optional functionalityIntegrate with The Compact for resource lock verificationAdd ERC-6909 token validation before order executionCall ResourceManager.sol to lock resources before LimitOrderProtocol executionImplement custom error handling for insufficient/expired locksCreate ChainLinkCompactInteraction.sol- Copy from RebalancerInteraction.solImplement IArbiter interface for The CompactAdd resource lock creation for taker's output tokensMaintain treasurer transfer functionalityAdd EIP-712 signature verification for compact agreementsRevert entire transaction if arbiter fails to process claimCreate Custom Allocator- Based on AutocatorImplement IAllocator interfaceHandle end-user (Maker) signing authorizationAdd nonce management for compact claimsImplement claim authorization logicLogic for calling this should be in ChainLinkCompact.t.solPhase 2: Integration & TestingCompact Registration SystemImplement EIP-712 signature generation for makers (no mandate data for Phase 1)Create compact registration functionsAdd chain-specific resource lock scopeImplement upfront token locking strategyTesting SuiteUnit tests for each contractIntegration tests for end-to-end flowTest ERC-6909 flag functionalityTest custom error handling scenariosPhase 3: Advanced FeaturesGas OptimizationOptimize gas usage for ERC-6909 integrationImplement batch operations optimizationProfile and optimize critical pathsEnhanced FeaturesAdd mandate data structure for order conditionsImplement multichain supportCreate custom Smallocator for smart contract callsAdd emissary fallback mechanismsImplement enum for additional swap types beyond boolean flagTechnical ArchitectureCore Flow:Maker deposits tokens into The Compact (creates ERC-6909 resource lock)Maker signs EIP-712 compact agreement with arbiter (ChainLinkCompactInteraction)Order is posted to LimitOrderProtocol with ERC-6909 extensionTaker fills order through ChainLinkCompact.solChainLinkCompactInteraction processes claim:Verifies resource lock availabilityExecutes trade using ChainLinkCalculator logicCreates new resource lock for taker's output tokensTransfers tokens to treasurerCalls ResourceManager to lock fundsKey Interfaces:ITheCompact- For resource lock managementIAllocator- For claim authorizationIArbiter- For claim processingIEmissary- For fallback verificationData Structures:Compact- EIP-712 payload for single resource lockBatchCompact- EIP-712 payload for multiple resource locksMandate- Witness data for order conditionsClaim- Claim payload for processingFuture Test EnhancementsFor ERC-6909 integration, additional test categories will be needed:ERC-6909 Resource Lock TestsResource lock creation and validationInsufficient lock handlingLock expiration scenariosCompact Integration TestsEIP-712 signature verificationCompact agreement validationArbiter claim processingResource Manager TestsLock management functionalityAllocator integrationError handling for resource conflictsEnd-to-End Flow TestsComplete maker-to-taker flowTreasurer integrationCross-contract interaction validationNEAR FUSION+ Smart Contract DevelopmentNEAR Smart Contract ArchitectureNEAR Limit Order Protocol ContractsNEAR Escrow Smart ContractsOverviewNEAR Fusion+ is a comprehensive DeFi protocol that migrates 1inch's Limit Order Protocol and Cross-Chain Swap functionality to the NEAR blockchain. This project implements advanced trading features including limit orders, cross-chain atomic swaps, and sophisticated escrow mechanisms.ArchitectureThe protocol consists of several interconnected smart contracts that work together to provide a complete DeFi trading experience:Core ComponentsLimit Order Protocol- Handles limit order creation, execution, and managementCross-Chain Swap- Enables atomic swaps across different blockchainsEscrow System- Manages secure fund escrow for cross-chain operationsFee Management- Handles fee collection and distributionMerkle Validation- Provides proof validation for complex order structuresContract Structuresrc/ ├── limit-order-protocol/ # Main limit order functionality ├── cross-chain-swap/ # Cross-chain atomic swap implementation ├── base-escrow-factory/ # Advanced escrow factory with Merkle validation ├── escrow-factory/ # Standard escrow factory ├── escrow-src/ # Source chain escrow contract ├── escrow-dst/ # Destination chain escrow contract ├── fee-taker/ # Fee collection and management └── merkle-storage-invalidator/ # Merkle proof validationKey FeaturesLimit Orders: Advanced limit order protocol with partial fills and multiple execution strategiesCross-Chain Swaps: Atomic swaps between different blockchains with time-locked escrowsMerkle Proofs: Efficient validation for complex order structuresFee Management: Flexible fee collection and distribution mechanismsSecurity: Comprehensive validation and timelock mechanismsDocumentation SectionsACLCEFMISADQuick StartBuild Contracts:cargo near buildRun Tests:cargo testDeploy: Use the deployment scripts indeployment-scripts/DevelopmentRust Version: Seerust-toolchain.tomlNEAR SDK: v5.15.1Testing: Integration tests inintegration-tests/ContributingPlease refer to the mainRfor development setup and contribution guidelines.
Hackathon
ETHGlobal Unite
2025
Contributors
- johnwhitton
59 contributions