# From Factories to Ethereans DeFi Tools **Published by:** [N🟣N Labs](https://paragraph.com/@nonlabs/) **Published on:** 2023-02-09 **URL:** https://paragraph.com/@nonlabs/from-factories-to-ethereans-defi-tools ## Content Live FactoriesThe generalized smart contract factories built by Ethereans Labs offer the potential for greater security in the contract deployment process, enabling anyone to launch on-chain verified contracts that can be found in an aggregated factory marketplace. We believe this model of customizable building block contracts that can be cloned and deployed can serve as a framework for future dapps, DAO’s, and projects. At Ethereans Labs, we went beyond the development of the theoretical framework, launching real use case factories with this system. Ethereans Labs has already deployed a suite of DeFi Factories to allow anyone to safely deploy the tools to support their on-chain project. Here we will introduce three basic tools:Routines - This is a configurable contract that is used to distribute tokens at periodic intervals. A separate extension contract manages the Routine’s funds, and must be supplied with the necessary funds prior to each execution. Who pays the gas for the execution of the routine? Anyone can! And if they do, they will automatically receive a reward, which is a percentage of the transacted value. The EthereansOS organization uses Routines to mint and distribute OS tokens daily, some of which are sent to the farming rewards contract, while the rest is sold for ETH and routed to various Components including the Treasury, the EthereansLabs team, and investments.Farming - This is your standard farming contract. Anyone can create a simple farm that rewards a single token of their choice to farmers who provide liquidity to the chosen pool. If using Uniswap V3, you can even designate a specific liquidity range!Presto - Presto allows you to define a bundle of transactions, similar to a Routine contract, but more generic. The contract defines a list of operations to execute at once, including sending tokens, swapping and sending tokens, or adding liquidity to a given pool. Instead of offering a reward to the public for executing the operations and using a separate extension to manage the necessary funds for the execution, this responsibility is held by the caller.We have also deployed another DeFi tool for solidity developers: the AMM Aggregator, which is a separate protocol that simply provides a standardized on-chain API for calling swap and add/remove liquidity functions in Uniswap V2 style AMM’s that use liquid LP tokens. The model contracts for the above Factories make use of the Aggregator, which make it much easier to route swaps through the desired AMM. Next we will cover each of these applications in more technical detail.RoutinesThe general purpose Routines Factory was originally created to provide safe contracts for token inflation, hence the name of the contracts:The Factory: [FixedInflationFactory.sol]The model contract: [FixedInflationUniV3.sol]The default extension: [FixedInflationExtension.sol]The Factory lets anyone deploy a clone of the Routine contract that defines a set of one or more operations, which may be executed periodically with a defined block interval. The operations can include any combination of the following:Distribute a token onlyMint and distribute a tokenSwap and distribute a token (using the AMM Aggregator, or Uniswap V3)For each operation, the output token may be distributed in any proportions to a list of receivers including address(0) to burn the allocation.The Business ModelEach time the model contract executes a routine, a percentage is payed to:The address which calls execute, defined by callerRewardPercentage The caller of the execute function passes a single boolean parameter - if true, the executor will receive a percent of the input token for each operation; if false, the they will receive the output token instead.The EthereansOS Treasury, defined by the Ethereans Organization subDAO vote (governance tab, Covenants Routine Fee) The model contract implements a Usage Fee in which the EthereansOS Treasury will receive a percent of the output token of each operation. (A percent of this Usage Fee is taken by the FoF; however, in this case the receiver of the FoF fee is also the EthereansOS Treasury.)The FactoryThe factory contains the address of the model contract to clone, the address of the default extension that can be cloned upon request. The factory has two public functions:cloneDefaultExtension - clones the default extensiondeploy - clones the routines model contract, links it to its extension, and sets its entry and operationsThe Model ContractThe model contract allows its public execute function to be called periodically, transferring a reward to the executor. The model contract is defined by its entry (FixedInflationEntry) and operations. The entry contains the model contract’sname - a stringblockInterval - number of blocks that must pass between each execution of operations.lastBlock - defines the start blockcallerRewardPercentage - amount of each operation’s tokens given to the executorThe operations (FixedInflationOperation) each define the necessary parameters to perform minting, transferring, swapping, or burning a token. The model contract’s entry and operations can be changed only by its extension contract as described below.The ExtensionThe extension manages the routine’s funds and execution of its operations.Default ExtensionThe extension’s host acts as the owner of the Routine and can call the following functions:setEntry - changes the model contract’s entry and operationsflushBack - retrieve all of each requested token from the model contractsetActive - set the extension’s statussetHost - changes the host addressThe extension can be in two states - active or inactive. The execute function of the model contract can only be called if the extension is active. Each time the routine attempts to execute (with the block interval satisfied), the extension is asked to transfer (and possibly mint) the necessary tokens for execution to the model contract. If the routine is unable to acquire the necessary funds, the extension’s status is set to inactive, and must be reactivated by its host. The core functions of the default extension are as follows:active - a view function returning the boolean active variableAnd the following functions, which are only authorized to be called by the model contract:receiveTokens - sends (and possibly mints) the requested tokens to the model contractdeactivationByFailure - sets the active variable as falseA custom extension can be created so long as it implements the above core functions.Farming The Farming dApp allows anyone to deploy a farm from the Factory, or to participate in any active farming setup by depositing liquidity and earning farming rewards. A farming setup is synonymous with a farming season, defined by its duration and the amount of rewards allocated to that season. The owner of a farm can maintain the setup’s settings such as the reward amount per block and the season duration.The Business ModelThe model contract implements a Usage Fee in which the EthereansOS Treasury will receive a fee when farmers withdraw their earned fees. (A percent of this Usage Fee is taken by the FoF; however, in this case the receiver of the FoF fee is also the EthereansOS Treasury.) The user can choose to pay their fee either as a fixed amount of 5 OS* that is burned, or 0.08%* of the LP fees earned, not including farming rewards, which is also burned if the token is OS.The fee amount is decided by OS holders via subDAO vote - see governance tab, Covenants Farming Transaction Fee (percentage fee) and Covenants Farming Burn Fee (static OS fee).The FactoryThe factory has two functions:cloneDefaultExtension - clones the default extensiondeploy - clones and initializes a farming contract (the Factory’s model contract), and initializes the default extension.The Model ContractThe model contract is the farming contract, defined by the token (_rewardTokenAddress) that is rewarded to farmers at every block. This address is defined when the model contract is initialized and can not be changed. The other values that define the farm are contained in the farmingSetupConfiguration struct, which can be changed only by the extension’s host. The values in this struct are used to create a farming season and include the:duration of a farming seasontotal amount of reward token given per blockminimum amount a farmer can stakenumber of times the season can be renewedaddress of the liquidity pool in which farmers must participateAn individual farming season is then described by the FarmingSetup struct, which defines whether the season is active, its start and end block, and the amount of rewards per block. A farmer can join the farm by submitting a FarmingPositionRequest, which includes the index of the setup they wish to join, the owner of the position, the amounts of each token they are adding to the liquidity pool, and slippage tolerance. If successful, the farmer now owns a FarmingPosition that tracks the rewards earned by that position.The Default ExtensionThe extension is a separate contract linked to the farming contract that manages the farming reward funds and setup settings.TreasuryThe extension also defines a treasury address to which unissued rewards are sent, which may result from blocks in which no farmers participate, or from actions taken by the owner.HostThe extension’s host is the owner of the farm, and it is the only address with permission to make important changes, including activating a season or modifying its parameters. The host can modify farming season parameters by calling the setFarmingSetups function, which sets a new farmingSetupConfiguration from which farming seasons are created. This function can be used to terminate an active season or reduce the amount of farming rewards per block, in which case the unissued tokens allocated at that season’s start will be sent to the treasury. The host may also set a new host or change the treasury address.RewardsAt the start of each farming season, the extension will attempt to send the total amount of rewards necessary for that season to the farming contract. If this action fails, the season will be deactivated. This means that the extension must be funded externally with all rewards prior to a season’s start. Alternatively, the extension can mint the reward tokens itself in which case it will call the mint function on the reward token, so it must be approved to do so.PrestoThe Presto contract allows anyone to execute a set of operations in a single transaction. The contract contains a single function, execute, which takes a list of operations and performs them in sequence. Each operation starts with some amount of input token, and ends with an output token being distributed to the receivers according to their respective percentages, where the allocation will be burned if its receiver is address(0). The total amount of input tokens for all operations is collected from the msg.sender prior to the first operation, i.e., an operation can not use the output tokens from a previous operation as its input tokens.OperationsEach operation is defined by the prestoOperation struct. The values which define the operation type are:address inputTokenAddressaddress ammPluginaddress[] liquidityPoolAddressesaddress[] receiversToken Distribution OnlyTo define the operation as a token distribution only (i.e., without first swapping or adding liquidity), the ammPlugin should be passed as address(0). Here, the output token will be the same as the input token.SwapTo define the operation as a swap, the ammPlugin should be populated with the plugin address corresponding to the desired AMM, and the liquidityPoolAddresses should be populated with the desired pools used in the swap route. Here, the output token will be the final token in the route, which will be distributed to the defined receivers as described above. The swap operation supports Uniswap V3, as well as any of the AMM Aggregator’s whitelisted AMMs: Uniswap V2, Sushiswap, Balancer V1, and Mooniswap.Add LiquidityTo define the operation as add liquidity, the ammPlugin should be populated with the plugin address of the desired AMM, and the liquidityPoolAddress should be set to address(0). Here, the inputTokenAddress is the address of the liquidity pool to which liquidity will be added, and is also the address of the liquidity pool token (output token) which will be distributed to the defined receivers as described above. The add liquidity operation supports only the AMM Aggregator’s whitelisted AMMs: Uniswap V2, Sushiswap, Balancer V1, and Mooniswap.AMM AggregatorThe AMM Aggregator is composed of the aggregator contract ([AMMAggregator.sol]) that routes calls to its whitelisted AMMs, and a separate model contract for each whitelisted AMM. The current AMM interface used by the model contracts is based on AMMs that use the “Uniswap V2” style ERC20 LP token. Currently supported are:Uniswap V2MooniswapBalancer V1SushiswapStandardized APIThe IAMM interface, implemented by each AMM-model contract (not to be confused with Factories’ model contracts), provides standardized functions for adding & removing liquidity and swapping. This allows developers to write smart contracts that interact with the generic interface rather than specific contracts for each AMM. Swapping functions use the SwapData struct, and adding/removing liquidity functions use the LiquidityPoolData struct, containing all the necessary information to execute the function in any of the whitelisted AMMs. For example, the aggregator’s addLiquidity function will receive the address of the desired liquidity pool, and route the call to the correct AMM. The AMM’s model contract will use the respective function for that protocol. E.g., if the liquidity pool belongs to balancer, its model contract will call [BPool.joinPool]; if the liquidity pool belongs to Uniswap V2, its model contract will call [UniswapV2Router01.addLiquidity].UpgradeabilityThe whitelist simply contains the contract addresses of each AMM model contract. When a call is made to any of the IAMM functions, the aggregator cycles through this list to find the appropriate AMM, and then routes the call to that model contract. The AMM Aggregator is hosted by Ethereans Labs, who is authorized to call the add and remove functions in the main contract to maintain the aggregator’s whitelisted AMMs. To add a new AMM to the aggregator, a model contract implementing IAMM must be created for that AMM, and then the host can add its address to the whitelist.The AMM Aggregator is a perfect example of a standalone protocol that integrates EthOS governance. The add and remove functions use the authorizedOnly modifier, specifying that only the host can call them. The host is the Covenants DFO (an earlier version of the current EthOS Organization), who manages proposals to modify the whitelist. Right now, EthereansLabs manages the aggregator, but in the future this power could be handed down to a deserving Organization by simply changing the host!ConclusionThese factories are all live and able to be cloned and the AMM aggregator is an example of what can be developed using the tools and governance of EthereansOS. While these are all standalone factories that can be integrated with a larger on-chain structures, there are even more factories that handle things like governance proposals that we will discuss in the future. This framework is ready to be built upon and these developed tools can be used by all protocols and projects.To be continued… ## Publication Information - [N🟣N Labs](https://paragraph.com/@nonlabs/): Publication homepage - [All Posts](https://paragraph.com/@nonlabs/): More posts from this publication - [RSS Feed](https://api.paragraph.com/blogs/rss/@nonlabs): Subscribe to updates