# The Rebalancing Bot

Now that we've covered the fundamental API structure and workflows, let's proceed to design a straightforward Vault Rebalancing bot. This bot will automatically redistribute assets among Morpho Vaults

> The complete example is available in the project's GitHub repository at <https://github.com/Brahma-fi/console-automation-examples/tree/main/examples/yieldagg>

To Design Our Rebalanceoor Bot, we need to define a policy that grants our bot permission to perform rebalance actions between multiple vaults. For simplicity, let's assume the bot only accepts USDC and rebalances between the top few vaults. The policy would look something like this:

<pre class="language-json" data-overflow="wrap" data-line-numbers><code class="lang-json"><strong>{
</strong>  "inputTokens": [
    "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913"
  ],
  "hopAddresses": [
    "0xeE8F4eC5672F09119b96Ab6fB59C27E1b7e44b61",
    "0xdB90A4e973B7663ce0Ccc32B6FbD37ffb19BfA83",
    "0xc1256Ae5FF1cf2719D4937adb3bbCCab2E00A2Ca",
    "0xc0c5689e6f4D256E861F65465b691aeEcC0dEb12",
    "0x12AFDeFb2237a5963e7BAb3e2D46ad0eee70406e",
    "0x0FaBfEAcedf47e890c50C8120177fff69C6a1d9B"
  ],
  "limitPerExecution": false
}
</code></pre>

Once we've defined our policy and registered our executor, we can design the full system end-to-end.

<figure><img src="/files/5WaszsiICO7JtA5TAlNt" alt=""><figcaption><p>Rebalanceooor BOT</p></figcaption></figure>

### Syncing Subscriptions

As users subscribe and unsubscribe from automation, the subscriptions endpoint would be used to fetch new and cancelled subscriptions. Our bot would keep track of the currently active ones. This can be facilitated with a persistent data storage layer like Redis or PostgreSQL, where the bot would maintain execution logs and current subscription statuses.

### Trigger Monitors

The trigger mechanism is straightforward: for each subscriber, the monitoring service would periodically check if the user's assets are currently allocated in the vault with the highest APY. If not, a rebalance trigger would be generated to move the user's position to the new vault.

This can be achieved using a simple cron monitor or a more sophisticated system like Temporal for a production-ready and more resilient system.

Once a rebalance trigger is generated, the bot proceeds to the callData generation logic, which would move funds to the new vault. Our bot should ensure that the new vault is one of the whitelisted vaults.

### Signing Request

Once the callData is ready, our bot attests the request by signing the EIP712 message for execution. The signer would be the same as our registered executor. Key management should be handled carefully, using any of the available key managers or a simple vault-based plugin to secure the signing key.

After signing, the request is submitted to the execute endpoint, and a taskID or an error is returned.

### Post Execution

Our bot polls the Brahma relayer to get the relayed transaction hash from the returned taskID. Once the transaction is relayed, it validates the user's state, and the monitor schedules the next interval to perform the check and run the automation.

We can also persist the executed transactions and logs in the datastore for better visibility.

{% embed url="<https://youtu.be/iiNy_BoYRBE>" %}

### Summary

When building automations, developers need to manage several critical components:

1. **State Management**: Tracking logs, execution states, and operational data
2. **Monitoring**: Implementing reliable job scheduling and failure recovery systems
3. **Key Management**: Ensuring secure handling and rotation of signing keys
4. **Error Handling**: Developing robust mechanisms to manage failures across components

The Brahma Builder Kit offers two approaches to handling these requirements: developers can either manage these components independently using the Execution Layer's core endpoints, or leverage the Orchestration Layer which abstracts these complexities. The Orchestration Layer provides:

* Streamlined development process
* Reduced boilerplate code
* Built-in best practices for common automation tasks
* Improved scalability and maintainability

By understanding both approaches, developers can choose the implementation that best suits their automation needs - whether it's direct control through the Execution Layer or the simplified development experience via the Orchestration Layer.


---

# 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.brahma.fi/brahma-builder-kit/the-rebalancing-bot.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.
