# Yagi Finance Introduction

🐐 -> (🐐)

{% hint style="info" %}
Yagi aggregates yield opportunities across pioneering StarkNet protocols
{% endhint %}

Yagi is a StarkNet Yield Aggregator. We curate & develop targeted vaults in collaboration with the leading StarkNet DeFi protocols. Each vault simplifies the process of depositing funds into a specific StarkNet protocol. We also feature third party vaults using our unified UI.

## Get Started

To get started, with vaults, see the [Introduction](/products/vaults/introduction) or go straight to the [Vault UI](https://www.yagi.fi/vaults).

<figure><img src="/files/GWThJpO7YBqtc9vlsUdH" alt=""><figcaption><p>Yagi Vault UI</p></figcaption></figure>

## Why StarkNet?

In short, we believe StarkNet is the most powerful network for Ethereum developers. Due to its underlying properties, a vibrant, sophisticated and friendly developer community, it's our belief that StarkNet will support the next generation of DeFi and GameFi applications.

You can read our more detailed perspective about this:

{% embed url="<https://medium.com/yagi-fi/provable-vs-composable-computation-or-why-cairo-will-supersede-solidity-6b00e69bfc9e>" %}


# Contact Us

### Partnerships

Please DM us on [Twitter](https://www.twitter.com/yagi_fi).

### Support

Please use the #support channel in [Discord](https://discord.gg/49TYpjfkUn).


# Vaults


# Introduction

## What is a vault?

A vault is a smart contract that automates depositing capital into a DeFi protocol. Vaults also commonly pool capital from various users and create economies of scale through reducing gas costs and achieving higher levels of protocol incentives.

Vaults are a great way to participate in DeFi:

* Minimal maintenance (compared to manually using a protocol)
* Useful metrics to help evaluate opportunities (vault user interfaces commonly show APY, overall value locked in an opportunity, deposit history, etc.)
* Helpful with discovering new protocols
* Often cheaper to use than protocols directly, sometimes with higher returns

### Guides: Jump right in

Follow our handy guides to get started on the basics as quickly as possible:

### Fundamentals: Dive a little deeper

Learn the fundamentals of Yagi to get a deeper understanding of our main features:

{% content-ref url="/pages/wqk63WkHqlVVENeJaEwP" %}
[ERC4626](/products/vaults/erc4626)
{% endcontent-ref %}


# How to use Yagi Vaults

Our vaults can be accessed from the [Vault UI](http://www.yagi.fi/vaults).

{% embed url="<https://www.yagi.fi/vaults>" %}

For a step-by-step explanation of how to allocate testnet funds into a Yagi vault, please see the community article below by katsuyusama

{% embed url="<https://katsuyusama.medium.com/yagi-finance-7c89435d37c1>" %}


# ERC4626

ERC4626 is an emerging standard for vaults. Yagi leverages ERC4626 for all our vaults, providing a consistent experience of users and maximum interopability with future StarkNet products. We are also helping other teams develop their own wrappers or vaults using our ERC4626 template.


# Automation


# Introduction

🐐 -> (🐐)

{% hint style="info" %}
Yagi Automation is a network of keepers on StarkNet L2 that automate protocol actions
{% endhint %}

There are three participants in our system:

* **Task authors** create automations. These are smart contracts that need to be invoked on a regular basis,
* **Automation keepers** execute automations,
* **End-users** use different automations to take advantage of emerging yield opportunities.

Yagi is a protocol that connects task authors and automation keepers and a community that connects task authors with end-users.

## Why Automation?

Some types of smart contracts require regular upkeep. For example, vaults need to harvest rewards, trading strategies require rebalancing of positions and players playing on-chain games seek to automate their farming.

StarkNet (like other built-in networks) does not support automated smart contract invocation. Smart contracts can only be invoked from "outside" the network whether by an external user or a computer program that mimics a user interaction.

But it's problematic for smart contract teams to maintain their own automation infrastructure:

* **Opportunity cost**. Developing a bot distracts developer time from the core product,
* **No redundancy**. A single bot is a single point of failure,
* **Centralization**. A protocol relying on the team's own proprietary execution infrastructure could be tactically exploited (e.g., by withholding or front-running executions at certain points in time).

Yagi is a network of keepers that will execute smart contracts as required by their authors. To create an automated smart contract, a task author will create a Yagi task and define **when** it should be called and **how** it should be called by the keepers. After deploying the task, keepers will begin automated execution.

{% hint style="info" %}
StarkNet transactions are currently free so Yagi Automation is free to use.
{% endhint %}

## Benefits of Yagi Automation

There are several benefits to using Yagi Automation:

* No need to deploy off-chain code, creating a task only requires building 2 smart contract functions,
* Increased reliability by working with a network of keepers,
* On-chain transparency of execution requirements and parameters builds trust from community.

## Why StarkNet?

In short, we believe StarkNet is the best available architecture for enabling mass-automation on-chain. Due to low transaction cost, automations on StarkNet will be cheaper than anywhere else and also will be able to execute more complex tasks. As a result, we expect Yagi automations will enable entirely new use cases for DeFi, NFTs, gaming and other verticals.

You can read our more detailed perspective about this:

{% embed url="<https://medium.com/yagi-fi/provable-vs-composable-computation-or-why-cairo-will-supersede-solidity-6b00e69bfc9e>" %}

### Guides: Jump right in

Follow our handy guides to get started on the basics as quickly as possible:

{% content-ref url="/pages/srP6qPuRdHQfqI42QU0A" %}
[How it Works](/developers/automation/how-it-works)
{% endcontent-ref %}

{% content-ref url="/pages/OGDLgB4UG6c74VR5T6mh" %}
[How to Create a Task](/developers/automation/how-to-create-a-task)
{% endcontent-ref %}

{% content-ref url="/pages/2009akHOU8pUiEfGhVCt" %}
[Security](/developers/automation/security)
{% endcontent-ref %}

### Fundamentals: Dive a little deeper

Learn the fundamentals of Yagi to get a deeper understanding of our main features:

{% content-ref url="/pages/TyD28oNzyzrqvynHF6lA" %}
[Tasks](/developers/automation/tasks)
{% endcontent-ref %}

{% content-ref url="/pages/p9lYTkplf8DQBmcnFCor" %}
[Keepers](/developers/automation/keepers)
{% endcontent-ref %}


# How it Works

{% hint style="info" %}
**Warning**. The protocol is in active development so expect this section to change regularly
{% endhint %}

## Low-level explanation

If you are not familiar with the protocol at the high-level, please read [Yagi Finance Introduction](/)first.

The protocol defines a task interface `ITask.cairo` that consists of two functions:

* `probeTask` – defines conditions for task execution, returns `1` if task is ready to be executed and `0` otherwise
* `executeTask` – executes task.

The task author creates a task contract that conforms to this interface and deploys it to StarkNet. Once deployed, the task smart contract's address is whitelisted by the Yagi team and keepers begin to execute.

Each keeper will first call `probeTask` to see if task is ready for execution and upon receiving a `1` (ready) will invoke `executeTask`. Keepers do this by running dedicated software (see example below).

{% embed url="<https://twitter.com/yagi_fi/status/1485238730319355905>" %}

The task interface model is very flexible and can accomodate several different use cases:

* Regular timed execution (by using `get_block_timestamp()`
* Conditioned execution (by manually checking for certain conditions)
* Deploying a task separately from the contract (by "authorizing" the task to perform certain contract actions).


# How to Create a Task

Task creation is as easy as creating and deploying a new smart contract. Task authors should follow the interface at [ITask.cairo](/developers/automation/itask.cairo) create a task that defines their automation.

### Get our help

The Yagi team is happy to help in brainstorming different ideas for tasks that could be helpful to your protocol as well as task development.

Just ask on [Discord](https://discord.gg/49TYpjfkUn) or [Twitter](https://www.twitter.com/yagi_fi).

### Example task

This is an example task that maintains a counter to be called at least every minute. Note: there is nothing currently preventing the counter to be called more frequently.

```
## SPDX-License-Identifier: AGPL-3.0-or-later

%lang starknet

from starkware.cairo.common.cairo_builtins import HashBuiltin
from starkware.starknet.common.syscalls import get_block_timestamp
from starkware.cairo.common.math_cmp import is_le

## @title Example counter task.
## @description Incrementable counter.
## @author Peteris <github.com/Pet3ris>

#############################################
##                 STORAGE                 ##
#############################################

@storage_var
func __counter() -> (counter: felt):
end

@storage_var
func __lastExecuted() -> (lastExecuted: felt):
end

#############################################
##                 GETTERS                 ##
#############################################

@view
func counter{
        syscall_ptr : felt*,
        pedersen_ptr : HashBuiltin*,
        range_check_ptr
    }() -> (counter: felt):
    let (counter) = __counter.read()
    return (counter)
end

@view
func lastExecuted{
        syscall_ptr : felt*,
        pedersen_ptr : HashBuiltin*,
        range_check_ptr
    }() -> (lastExecuted: felt):
    let (lastExecuted) = __lastExecuted.read()
    return (lastExecuted)
end

#############################################
##                  TASK                   ##
#############################################

@view
func probeTask{
        syscall_ptr : felt*,
        pedersen_ptr : HashBuiltin*,
        range_check_ptr
    }() -> (taskReady: felt):
    alloc_locals

    let (lastExecuted) = __lastExecuted.read()
    let (block_timestamp) = get_block_timestamp()
    let deadline = lastExecuted + 60
    let (taskReady) = is_le(deadline, block_timestamp)

    return (taskReady=taskReady)
end

@external
func executeTask{
        syscall_ptr : felt*,
        pedersen_ptr : HashBuiltin*,
        range_check_ptr
    }() -> ():
    # One could call `probeTask` here; it depends
    # entirely on the application.

    let (counter) = __counter.read()
    let new_counter = counter + 1
    let (block_timestamp) = get_block_timestamp()
    __lastExecuted.write(block_timestamp)
    __counter.write(new_counter)
    return ()
end

```


# How to View Existing Tasks

Please visit [our app](https://yagi.fi/automation) to see existing running tasks.


# ITask.cairo

This is the contract interface that all task authors should follow when creating a task.

```
## SPDX-License-Identifier: AGPL-3.0-or-later

%lang starknet

## @title Automation task interface.
## @description Implements a task that will be called automatically by keepers.
## @dev We recommend keeping this contract separate from your core protocols and instead
## giving it permissions to call into your core protocol. This will give you the most
## flexibility in using and modifying tasks going forward.
## @author Peteris <github.com/Pet3ris>

@contract_interface
namespace ITask:

    ## @notice Called by task automators to see if task needs to be executed.
    ## @dev Do not return other values as keeper behavior is undefined.
    ## @return taskReady Assumes the value 1 if automation is ready to be called and 0 otherwise.
    func probeTask() -> (taskReady: felt):
    end

    ## @notice Main endpoint for task execution. Task automators call this to execute your task.
    ## @dev This function should not have access restrictions. However, this function could
    ## still be called even if `probeTask` returns 0 and needs to be protected accordingly.
    func executeTask() -> ():
    end

end

```


# Fee Model

Since StarkNet transactions are currently free, Yagi automation is also free. When gas fees will be introduced, will update this page with a proposed fee model.


# Security

Yagi is currently a non-custodial protocol, however, keepers do require permissionless access to the task interface on a contract. Therefore, it is up to the task author to only use Yagi for non-exploitable actions such as rebalancing, harvesting, filling limit orders, etc.

{% hint style="info" %}
Do not create external functions on your smart contract that could be exploited by malicious external actors
{% endhint %}


# Tasks

Tasks are smart contracts that request some form of automated execution from Yagi. In practice, tasks conform to the `ITask.cairo` interface.


# Keepers

Keepers are independent bot operators that run dedicated software to invoke tasks.


# For Vaults and Bridges

Building a StarkNet vault or a bridge? [Get in touch](https://www.twitter.com/yagi_fi) and we will be happy to help you get started with automation.

Vaults and Bridges rely on certain activities to be completed at a regular interval:

* Harvesting rewards
* Rebasing
* Rebalancing across positions
* Aggregating epoch deposits.


# For Order Books and Lenders

Building a StarkNet on-chain order book or lending service? [Get in touch](https://www.twitter.com/yagi_fi) and we will be happy to help you get started with automation.

While large orders and lending positions in order books and automated lending don't usually require maintenance, there are positions that do:

* Smaller liquidatable positions
* Long-standing small orders.

You can use Yagi automations to conduct a regular clean-up of your on-chain state.


# For AMMs

Building a StarkNet AMM? [Get in touch](https://www.twitter.com/yagi_fi) and we will be happy to help you get started with automation.

AMMs enable instant trade execution when the price is acceptable by traders. However, limit orders are not possible in most AMM designs. Consider adding a limit order or order book integration with Yagi.


# For Derivatives Platforms

Building a StarkNet derivatives protocol? [Get in touch](https://www.twitter.com/yagi_fi) and we will be happy to help you get started with automation.

Some use cases where Yagi automation could be helpful:

* Options exercising (especially smaller positions).


# For Games

Building a StarkNet game or playing one? [Get in touch](https://www.twitter.com/yagi_fi) and we will be happy to help you get started with automation.

The StarkNet platform is ideally suited to play more complex resource management, breeding and other long-term games involving on-chain asset management. Players can automate resource acquisition or maintenance strategies using Yagi:

* Reinvest resource rewards
* Trigger certain events
* Set limit orders on item purchases.

We did a presentation for MatchboxDAO on how to incorporate automation in gaming.

{% file src="/files/DM17aToH8X8CUL1PcTMJ" %}


# Build a Yagi Vault

We are looking for ambitious developers that would like to develop a vault for Yagi and form the nucleus of our contributor community.

{% hint style="info" %}
Phase 1 applications will soon open. Please join our Discord to stay informed!
{% endhint %}

<figure><img src="/files/t1D2tuj9VMmEkiK6bm4n" alt=""><figcaption></figcaption></figure>

## Phase 1

*Discover and nurture the most promising StarkNet developers – Q4 2022 (estimated)*

Our objective for Phase 1 of the contributor program is to discover the best talent in the StarkNet ecosystem and help them make their first contributions to Yagi. Successful participants will be in a great position to develop their careers with another StarkNet protocol or may join us for Phase 2 to build mainnet vaults and receive incentives. We will consider talented applicants with no Cairo experience as long as they have existing familiarity with Solidity and an interest in learning to develop on StarkNet.

## Phase 2

*Reward vault developers with a fee share model  – H1 2023 (estimated)*

Our next step will be to gather the most promising candidates from Phase 1 and allow them to independently work on vaults. When published, these vaults will receive fees from users and the fee will be shared between Yagi and the contributor for that vault.

## Phase 3 (More details to follow)


# How to contribute

At the moment there are two ways to contribute to Yagi.

### Technical contributions

* Learn Cairo and create task. We believe creating an automation task is one of the simplest programming challenges one could do in Cairo that can be useful to end-users. For task ideas, please refer to [Broken mention](broken://pages/2TYN0GqCOYZlMv6VvDOh) or come up with your own.

### Non-technical contributions

* Suggest tasks and automation ideas in the #starknet-yield channel in [Discord](https://discord.gg/49TYpjfkUn) (e.g., "How could I create a limit order?", "I would like my Realms farming to be automated").


# Roadmap

TBD, in the meantime, we recommend reading this paper:

> This paper examines the long-run behavior of learning with bandit feedback in non-cooperative concave games. The bandit framework accounts for extremely low-information environments where the agents may not even know they are playing a game; as such, the agents’ most sensible choice in this setting would be to employ a no-regret learning algorithm.

{% embed url="<https://proceedings.neurips.cc/paper/2018/file/47fd3c87f42f55d4b233417d49c34783-Paper.pdf>" %}


