---
# System prepended metadata

title: Hackmos 2023

---

# Hackmos 2023


## Problem Statement

Lending systems and leverage trading (like perps) have liquidation when a position goes to an unhealthy state. For lending systems this happens when the Loan To Value has crossed a liquidation threshold. For perps, liquidation happens when there is no margin (or the margin is too low). Liquidation reduces (or closes) a trader position, to protect a system from unhealthy debts.

Usually, a liquidator buys out the trader position and receives a premium from the trader collateral. Liquidations brings around 5% immediate profit. For example, liquidating a $100k position will bring $5k immediately. If that happens every hour, that would make `5*24*365/100 * 100% = 43800%` APY!


## Context

Cross chain liquidations are complex, they require:
+ Moving liquidity from a chain where a user has liquidity to another one (where there is a liquidation option). 
+ An overview of available liquidation options across all chains.


Today, this requires lot of work by querying the chains, moving the liquidity and executing the liquidation.

## Proposal

+ A unified, user friendly dashboard to list available liquidations across different chains.
+ Use IBC to orchestrate the liquidity transfer from one chain to another and automatically liquidate.

## Proof of Concept

We will use:
1. Umee for both a liquidity (lending) provider and a potential liquidation target (borrowing).
2. Nibiru for both an orchestrator (smart contract) and a potential liquidation target (perps DEX).

### What

Alice, Bob and Charlie supply money in Umee, the biggest Cosmos lending system. Alice and Bob supply Umee. Charlie collateralizes Atom and Umee and borrows Juno.
Dylan trades perps (SC <> USD) in Niburu with Atom as a collateral. `SC` is a coin registered in Niburu x/bank.

Dylan and Charlie are overly optimistic and they put their positions under the water. The dashboard displays 2 liquidation targets:
1. Dylan's to liquidate SC.
    - Liquidator has to repay `SC` and he receives `Atom` (with extra %5 of Atom).
2. Charlie's to liquidate Juno. (For the example: Atom has a constant price: $10, and Umee: $0.04, while Juno drops from $3 to $0.3).
    - Liquidator repays `Juno` and has an option to get a reward of Umee or Atom.

For the first liquidation, Alice or Bob borrow Atom (on the Umee Chain), against the Umee collateral they have, send it to Nibiru and liquidate Dylan's SC.
Note: in a later step they should sell SC.



## How

+ IBC over cosmwasm to orchestrate liquidity provisioning.
+ DeFi adapters: set of contracts to interact with different DeFi protocols to browse and liquidate.
+ Liquidation Targets API (which queries available liquidaiton targest for the UI).
+ ABCI++ Handlers to organize transactions, adjust liquidaiton so every transaction will get in, making it fair and available for everyone.


## ABCI++ track

Liquidations are very profitable transactions. However, liquidaitons suffer heavily from MEV!!!!
The goal is to use a block proposer to reorder and adjust transaction in a block to allow that all liquidation requests will be executed.
+ we created a custom **Mempool** which prioritizes and puts at the front `MsgLiquidate` transactions
+ **`PrepareProposal`** computes total liquidation that is being made in the block, and inserts adjustmet data in the transaction chain of the block in case there are more liquidators than available targets (by total volume to liquidate).
+ **`ProcessProposal`** that tries to extract the adjustment number, recalculates the total liquidation amount in transactions in the block and check if it works.
+ **`PreBlock`** handler to inject the adjustment info in the keeper.



## Deliverables

The liquidation aggregation is done through IBC using polytone contract to exchange packets between chains. There are liquidation adapter contracts on each of the chains aggregated.

Contracts:

1. Controller contract: 

The contract keep the funds deposited by users to be used for liquidations. The admin can trigger a check where the controller queries the adapters to multiple chains if there is an open position up for liquidation. If there is such position found, the funds are IBCed over to the adapter chain and the adapter performs the liquidation and returns the liquidated collateral back over to the controller chain.

2. Umee liquidation adapter: 

The contract performs liquidation on Umee on behalf of the controller, since the controller contract sits on Umee, it does not require funds to be sent over IBC and the liquidation can be performed within the same chain atomically (transfer of funds + liquidation action), so there is no requirement of sending back funds to controller chain.

3. Nibiru liquidation adapter: 

The contract performs liquidations on Niburu chain for the perps positions that are up for liqudiation, the condition for that is the perp position is low on margin. In Nibiru, meeting the margin requirement means maintaining a margin ratio on the position that exceeds the maintenance margin ratio (6.25%), which is the minimum margin ratio that a position can have before being liquidated.

4. Mars liquidation adapter: 

The contract keeps track of all the accounts that have a loan position in Mars contracts deployed on Osmosis. Whenever the contract receives liquidate message from controller contract, it checks the position and if the position is still open, it performs the liquidation and returns the collateral to controller or else with return the funds sent by controller back to it.

The adapter calls the `red_bank` contract on Osmosis and abstracts the calls to a genralised txn calls for controller contract.

a. `LiquidatePosition()`: It calls the `Liquidate()` msg of `red_bank` to liquidate a position. If successful, collateral is received by the adapter from red bank, else the sent funds remain in the adapter.
b. `DepositAndBorrow()`: Deposits the collateral and borrows the asset from red bank.
c. `WithdrawCollateral()`: Repay the asset loan and withdraw the collateral from red bank.

### Deploy polytone

1. Clone the repository, `git clone https://github.com/udit-gulati/polytone`
2. Install wasmkit, `cd polytone && yarn install`
3. Compile contracts to generate wasm binary and schema files, `npx wasmkit compile`
4. Run the deploy script, `npx wasmkit run scripts/deploy.ts --network umee` and `npx wasmkit run scripts/deploy.ts --network nibiru`
5. If deployed correctly, the contract address and code id for 3 contracts (note, voice and proxy) for each network should show up in `artifacts/checkpoints/` directory as `.yaml` files.

### Nibiru

+ Nibiru has an SDK module for Perps and Cosmowasm for deploying contracts.
+ So, we can have a contract which will call a native module and trigger a liquidation.

### Umee

1. Note:
    * codeId: 1
    * contractAddress: umee14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9scsdqqx
2. Proxy:
    * codeId: 3
    * contractAddress: umee1qg5ega6dykkxc307y25pecuufrjkxkaggkkxh7nad0vhyhtuhw3shmlsys
4. Voice:
    * codeId: 2
    * contractAddress: umee1xr3rq8yvd7qplsw5yx90ftsr2zdhg4e9z60h5duusgxpv72hud3scz87vz
5. Liquidation adapter:
    * codeId: 4
    * contractAddress: umee1ghd753shjuwexxywmgs4xz7x2q732vcnkm6h2pyv9s6ah3hylvrqsgm7t9

### Nibiru

1. Liquidation adapter:
    * codeId: 1
    * contractAddress: nibi14hj2tavq8fpesdwxxcu44rty3hh90vhujrvcmstl4zr3txmfvw9ssa9gcs
    
### Deployed endpoints

UMEE:
RPC: 35.246.147.222:36657
GRPC: 35.246.147.222:8090
GRPC-WEB: 35.246.147.222:8091
REST: 35.246.147.222:2317

Key mnemonic: only song turkey pelican settle claw loud glass raccoon school alert powder clap suit harvest pizza street split point swallow filter element carry memory

NIBIRU:
RPC: 35.246.147.222:26657
GRPC: 35.246.147.222:9090
GRPC-WEB: 35.246.147.222:9091
REST: 35.246.147.222:1317

## Prerequisits

Deploy two local chains and connect them via IBC using a relayer.
Chain 1: nibiru (https://github.com/NibiruChain/nibiru)
Chain 2: umee (https://github.com/umee-network/umee)
Relayer: hermes (https://github.com/informalsystems/hermes/)


## What's going for v2 

+ Liquidation delay to allow more IBC tx aggregation.
+ Bot with subscription to automatically trigger liquidations.




