# Keeper service and smart contract description

### Keeper service

Keeper is a node.js service that monitors riskiest long and short positions within Marginly pools for liquidation and triggers the keeper contract to do so.&#x20;

Service configuration takes in Marginly pools addresses, network parameters and account address. This account is used for keeper transactions. The Keeper service then checks riskiest long and short positions. If a position’s leverage exceeds max leverage parameter (20 by default), the Keeper service calls up the smart contract to perform liquidation.&#x20;

The Keeper service attempts to liquidate positions in a loop every 3 seconds if the smart contract throws an error.&#x20;

### Keeper smart contract

Keeper smart contract’s job is to liquidate a position in Marginly. To this end the contract does the following:

* Takes out a loan in AAVE
* Makes the swap on Uniswap
* Return the loan to AAVE and any proceeds to the liquidator

All users can trigger the contract. It utilizes AAVE V3 for flash loan functionality and Uniswap V3 to execute swaps.&#x20;

Transaction takes the following inputs:

* Token
* Amount
* Marginly pool address
* Position address
* Minimum profit amount

Keeper transaction then does the following operations:

* requests an AAVE V3 flashloan&#x20;
* attempts to liquidate the position upon receiving a callback&#x20;
* gives the liquidated position’s collateral to the liquidator
* withdraws collateral and swaps for the token that was loaned out on AAVE

Two checks happen after the swap:

* Is the collateral sufficient to return AAVE flash loan and keep required premium
* Is the remaining amount equal to or greater than the minimum profit amount

Transaction reverts if an exception is thrown at any stage during the liquidation process. Most notable examples include the following:

* position can not be liquidated
* minimum profit amount check fails
* insufficient collateral to cover the flash loan&#x20;

In this case the user pays a fee for calling up the transaction.

<br>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.marginly.com/risk-management/keeper-service-and-smart-contract-description.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
