# Welcome

I'm Brian 🤖

**Brian** enables users and AI Agents to interact with Web3 by providing textual prompts to execute various Web3-related actions, such as:

* Transactions: "Can you swap 10 usdc for eth on Ethereum ?"&#x20;
* Protocol info: "How Uniswap v4 hooks work?"
* Protocol data: "Give me the pools with the highest TVL on Uniswap"
* Smart contract: "Generate an ERC20 with name BrianAI and a supply of 1000 tokens"

The [Brian API](/brian-api/apis) and [Brian TS SDK](/brian-sdk/brian-typescript-sdk) allow developers to integrate the Brian AI capabilities in their applications to build intent-based apps that could be custodial, non-custodial, or support smart accounts.

The [LangChain<>Brian SDK](/ai-agents/langchain-less-than-greater-than-brian-sdk) allows devs to launch LangChain AI Agents capable of transacting and deploying tokens on-chain.

The [Brian App](https://www.brianknows.org/), built on top of Brian APIs, offers users an interface for performing transactions in a non-custodial way, researching web3 info, and deploying smart contracts by prompt.

{% hint style="warning" %}
There is a Prompt-to-earn program on the Brian App! Find out more [here](/prompt-to-earn).
{% endhint %}

### How Brian API works

**Brian** API is an Intent Recognition and Execution Engine capable of understanding the user intent for Web3 interactions, providing accurate textual answers and data, building transactions, or generating smart contracts.

{% hint style="info" %}
If you have any questions or doubts, join our [**Dev community**](https://t.me/+NJjmAm2Y9p85Mzc0)**!**
{% endhint %}

This is the end-to-end flow of the Brian API.&#x20;

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

Anyone can try it on our non-custodial [Brian App](https://www.brianknows.org/app) or [API swagger](https://api.brianknows.org/swagger). \
\
**1) Prompt/Intent**&#x20;

Users and Agents can prompt their intent for a web3 interaction: \
‣"I want to bridge 1 eth to Base and send them to vitalik.eth" \
‣"Tell me how Uniswap v4 works" \
‣"Deploy an ERC20 with name BrianAl and a supply of 1000 tokens" \
‣"What are the top trending tokens today?" \
\
**2) Intent Recognition Engine\***&#x20;

Brian Al extracts your intent into parameters and passes them to the execution engine. \
\* *Brian mission is to provide the best web3 intent recognition.*&#x20;

**3) Intent Execution Engine**&#x20;

The output of the API is built using a series of existing off-chain tools and, for TXs, on-chain aggregators in the market (like Enso Finance or Bungee Exchange).&#x20;

**4) Output**&#x20;

The API output could be:&#x20;

‣ A TX to sign and execute (by Agents or Users) \
‣ Text answer \
‣ Code to deploy \
‣ Market data


# Prompt-to-earn

Prompt on the Brian App, and earn Brian points.

{% hint style="warning" %}
Read the full **announcement article.** \
\
**Please note:** the Brian App is fully non-custodial and no "AI agent" will execute TXs on your behalf. You can prompt your action (e.g., "I want to bridge 1 eth to Base"), **Brian** extracts your intent and builds the TX via a series of aggregators like Enso Finance, LIFI or Bungee Exchange). **You** have to review and confirm the TX manually with your EOA wallet, and you are **solely responsible** for what happens to the funds.
{% endhint %}

On Wednesday, January 22nd, 2025, we announced the Brian promp-to-earn program on the Brian App.

The Prompt-To-Earn program is your unique chance to contribute to our dataset of TX-intents. By collecting the user's prompts, we'll be able to create a dataset of TX-intents and Instruct Fine-Tune (IFT) the open-weight domain-specific model for web3 we released in December 2024, read the announcement [here](https://x.com/BrianknowsAI/status/1871186518901153882).

If this is your first time using the Brian App, find out here how the Send Transaction feature works:

{% content-ref url="/pages/ApK7z3Korn0KchM9EPKW" %}
[Send Transactions](/brian-app/send-transactions)
{% endcontent-ref %}

## Point system

These are the guidelines to follow:

1. For each action available on the Brian App, the user is rewarded with points after prompting or executing a TX. Prompting and executing a transaction have different amounts of associated points.
2. Points are assigned immediately after the action is prompted or executed, and the user has to wait 24 hours before receiving other points for that action.
3. Everyone can check their score on the leaderboard.

{% hint style="info" %}
An example of a Swap prompt and executed TX:

1. I prompt on the "Send Transaction" feature my intent: *Swap 1 eth to usdc on Arbitrum*. After sending it, I will receive **20 points**;
2. When the TX is built, if I execute it (and the transaction finishes in the "**done**" status), I will receive **150 points;**
3. For each prompt and associated transaction I have to wait 24 hours before receiving these points again.
   {% endhint %}

The reward system is easy and intuitive. In order to create a heterogeneous dataset, we invite users to prompt the same action in different ways each day!

## Daily points allocation

Remember, the daily points reset every 24 hours, each one independently from one another. If you prompt a swap at 10 AM and a transfer at 11 AM, you'll need to wait until tomorrow at 10 AM to get the points for another swap and 11 AM for the transfer.&#x20;

| Action           | Points per Prompt | Points per TX |
| ---------------- | ----------------- | ------------- |
| Read actions\*   | 10                | -             |
| Transfer         | 20                | 100           |
| Swap             | 20                | 150           |
| Bridge           | 20                | 150           |
| Deposit          | 20                | 300           |
| Withdraw         | 20                | 300           |
| ENS Registration | 20                | 300           |
| ENS Renewal      | 20                | 150           |

\*Read actions do not involve the TX execution, you can find the list [here](/prompt-guide).

Follow the Brian updates on [X](https://x.com/BrianknowsAI) because we plan to launch several special programs with a boosted reward for each action!

If you want to learn how to formulate prompts that align with Brian's capabilities, ensuring optimal functionality and successful outcomes, here is a guide for you:

{% content-ref url="/pages/QJIgcKhRZ5RendiA9yGh" %}
[Prompt Guide](/prompt-guide)
{% endcontent-ref %}

## Pre-allocations of points

We decided to reward with a small pre-allocation of points two kinds of contributors during this first year and a half of Brian's life:

* 5k points to Brian App early-stage users: whitelisted users of the private beta.
* 5k points to devs integrating the Brian API: users who have at least one active API key at the snapshot of January 22nd, 2025 (4 pm CET).

Even if an address fulfills both requirements, the 10k allocated points are equivalent to just seven days of prompts and executed TXs.

You can find your pre-allocation of points directly when you connect the wallet to the Brian App, without the need of manually claiming them.


# Why an Intent Recognition Engine?

The first Intent Recognition Engine for web3, designed for Agents and Humans.

From the first day we started working on Brian one year and a half ago (this was a hackathon project; [here](https://medium.com/@BrianknowsAI/buildinpublic-ep-01-brian-three-months-after-ethprague-e7316b3b1053) is the full story), we have been firmly convinced about how, in a few years, **most of the on-chain transactions would be either be performed by autonomous AI Agents or users via intent-based apps, like our non-custodial Brian App.**&#x20;

To achieve that and unleash tons of new possible use cases on top of both technologies, we need a better system to recognize any intent of Web3 interactions from users and agents, whether it is a transaction to make, a request for information, or data of a protocol, or a smart contract to deploy.

That’s how we started building an “Intent Recognition and Execution Engine” that can power the next generation of autonomous Agents and intent-based apps for users. The Brian architecture (Fig. 1), which represents the end-to-end flow of our API, can be split into two components:

* The **Intent Recognition Engine**: the component that receives the textual input and, via the Brian AI models, understands what the user/agent intent is.
* The **Intent Execution Engine**: the component that builds the API output via a series of existing off-chain tools and, for TXs, on-chain aggregators/solvers in the market.

<figure><img src="/files/yXPw9tVr6pG6vmgVbHn4" alt=""><figcaption><p>Fig.1 - How the Brian Architecture works</p></figcaption></figure>

While working on the Intent Recognition Engine and talking with partners in the space, we explored this specific AIxWeb3 niche, and we quickly realized that an element was missing in this market: **no one has released a domain-specific model tailored for web3 yet.** It is well-known in the scientific community that smaller domain-specific models can achieve better performance at lower inference costs than larger models.


# Brian AI models

A series of Open Weights models for web3

{% hint style="warning" %}
Read the full[ **announcement article**](https://x.com/BrianknowsAI/status/1871186518901153882).
{% endhint %}

Large Language Models (LLMs) are rapidly becoming popular across various sectors of knowledge-based work on a global scale. It is known that LLMs demonstrate significant versatility as multi-purpose tools, supporting a wide array of tasks. However, when applied to specialized fields, LLMs often require specialized knowledge to achieve cutting-edge performance, particularly in deep technical fields such as Web3.&#x20;

There are already several similar works for domain-specific models in other sectors; read more here:

* [Astronomy](https://arxiv.org/abs/2411.09012): “AstroMLab 3: Achieving GPT-4o Level Performance in Astronomy with a Specialized 8B-Parameter Large Language Model”
* [Finance](https://arxiv.org/pdf/2303.17564): “BloombergGPT: A Large Language Model for Finance”
* [Medicine](https://arxiv.org/pdf/2305.09617): “Towards Expert-Level Medical Question Answering with Large Language Models”

Although they hold great potential, the significant training resources needed have constrained specialized LLMs advancement. To bridge this gap, domain-specific LLMs can be developed through innovative approaches like training from scratch using domain-specific datasets or applying supervised or instruction-based fine-tuning to existing general-purpose LLMs.&#x20;

### The Brian-8B model

The Brian-8B model, built on top of Llama-3.1-8B, is an LLM tailored for the Web3 space. This model shows excellent capabilities in natural language understanding of technical sentences related to the web3 world. Up-to-date is the best model for web3 practitioners of its size. Such a model is well suited for developers and startups because its size makes it easily deployable and faster at inference. This is our first step to showcase the utility of having web3-related models and the Brian team's objectives towards contributing to the community.&#x20;

Brian-8B acts as a backbone model, which means it is not suited to be released in production since this is only the first phase of a longer process that will take another few months. However, developers can use our backbone model to instruct finetune (IFT) with their custom-supervised dataset for specific downstream tasks.&#x20;

By leveraging the unique dataset (e.g., intents for transactions, QA for info/data, Solidity code) that the Brian team owns, several IFT models covering a wide range of web3-related use cases will be released:

1. **Natural-language to JSON model**&#x20;
2. **Solidity code generation model**
3. **QA model**

Once released, these models will be used in the Brian Intent Recognition Engine, which is the core element of the Brian architecture. Accessible via the Brian API, this architecture is capable of understanding the user and agent intent for Web3 interactions, providing accurate textual answers and data, building transactions, or generating smart contracts.

Read more about it [here](/why-an-intent-recognition-engine).

### Why the Brian-8B model?

In the recent enormous hype for AI Agents and intent-based apps, we have seen most of the devs using OpenAI GPT models, a comprehensible choice considering they are currently leading the market. Even if these models are suitable for a beta version of a web3 product, we do not believe that they will remain a good solution for the long term, especially if we want to build a new open and transparent Internet.&#x20;

<figure><img src="/files/WB5bkrmzdWVxz9E4fsIv" alt=""><figcaption><p>OpenAI GPT models vs Brian models</p></figcaption></figure>

In comparison to OpenAI GPT models, these are the main reasons why devs should choose the Brian models:

* **Performances**\
  General-purpose AI models lack effective natural language understanding of Web3-related topics. Thanks to a lower perplexity (evaluate a language model's ability to predict the next word – models with lower perplexity generally achieve better performances), domain-specific models can have comparable, if not higher, performances to OpenAI GPT models.<br>
* **Further external fine-tunings**\
  The Brian models will be released open-weights, which means the pre-trained weights (the learned parameters that define the model’s behavior) are available while keeping the underlying training data and algorithms private. This approach allows devs to perform further fine-tunings for their project needs. For example, in a multi-agent system, each AI agent could be powered by a fine-tuned model for the specific tasks it has to perform.<br>
* **Inference costs**\
  These models will be available at a fraction of the cost of larger general-purpose models. This will also be reflected in our API tier cost.<br>
* **Decentralized Inference**\
  The Brian models (or other OS IFT versions) could also be hosted on top of a decentralized inference network, and the Brian team has already conducted some R\&D for the future implementation of a [Decentralized Collaborative Intelligence Network](https://mirror.xyz/orbulo.eth/svv4yQCUHiCY1vj4RYlYF7IpWMYtLc1ItjtXIr-D9t0).

In conclusion, these models will be a more suitable solution both for our Intent Recognition Engine (on top of which can be built intent-based apps and AI agents capable of transacting on-chain) but also for innovative use cases built by other devs who can fine-tune them for their specific needs.


# Prompt Guide

Welcome to the Brian Prompt Engineering Guide!

This comprehensive guide aims to assist users with the necessary knowledge to craft prompts effectively for Brian. By understanding the principles outlined here, you will learn to formulate prompts that align with Brian's capabilities, ensuring optimal functionality and successful outcomes.

Brian’s AI capabilities consist of extracting all the attributes from the prompt, effectively extracting the user's intention, and building the desired transaction flow. \
\
The following table gives you an overview of all the supported actions on Brian.&#x20;

{% hint style="info" %}
Multiple-action prompts have the same rules as the single ones. You can mix different actions together (e.g. "swap 10 usdc to eth and renew vitalik.eth for 12 months") or write the same action multiple times (e.g. "swap 10 usdc to eth and swap 10 usdc to usdt"). The AI will extract your intent and build multiple transactions.
{% endhint %}

<table><thead><tr><th width="115">Action</th><th width="147">Description</th><th width="184">Capabilities</th><th>Eg. prompts</th></tr></thead><tbody><tr><td> <mark style="color:yellow;"><strong>Swap</strong></mark></td><td>Swap any token through the LI. FI and ENSO solvers</td><td><ul><li>Use a different address receiver</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my" </li><li>Use the address of the token</li></ul></td><td><ul><li><em>Swap 1 usdc to weth</em></li><li><em>Swap 1 usdc to weth and use vitalik.eth as the receiver address</em></li><li><em>Swap 10 dollars of usdc to eth and send it to 0xabc...eet</em></li><li><em>Buy eth with 10 $usdc</em></li><li><em>Swap 50% of eth to dai and 50% to usdc</em></li><li><em>Swap all my dai to usdc</em></li><li><em>Swap all my eth to</em> 0x94b008aa00579c1307b0ef2c499ad98a8ce58e58</li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Bridge</strong></mark></td><td>Bridge any token through the LI. FI and ENSO solvers. <br><br>*All the available chains on Brian are possible destination chains.</td><td><ul><li>Specify "from chain" and "to chain" or only the destination chain</li><li>Use a different address receiver</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my" </li></ul></td><td><p></p><ul><li><em>Bridge 1 usdc from arbitrum to ethereum</em></li><li><em>Bridge 1 eth to optimism</em> </li><li><em>Bridge 1 usdc to zksync and use vitalik.eth as the receiver address</em></li><li><em>Bridge 10 dollars of usdc to arbitrum and send it to 0xabc...eet</em></li><li><em>Bridge 10 $usdc to ethereum and 10 $eth to arbitrum</em></li><li><em>Bridge 50% of eth to ethereum and 50% to optimism</em></li><li><em>Bridge all my dai to gnosis</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Crosschain swap</strong></mark></td><td>Cross-chain swap any token through the LI. FI and ENSO solvers.<br><br>*All the available chains on Brian are possible destination chains.</td><td><ul><li>Specify "from chain" and "to chain" or only the destination chain</li><li>Use a different address receiver</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my" </li></ul></td><td><p></p><ul><li><em>Bridge 1 usdc to eth from arbitrum to ethereum</em></li><li><em>Crosschain swap 1 eth to usdc to optimism</em> </li><li><em>Make a crosschain swap of 1 usdc to usdt to zksync and use vitalik.eth as the receiver address</em></li><li><em>Crosschain swap 10 dollars of usdc to usdt to arbitrum and send it to 0xabc...eet</em></li><li><em>Crosschain swap 10 $usdc to eth to ethereum</em></li><li><em>Crosschain swap 50% of my eth to usdc ethereum and 50% to usdt to optimism</em></li><li><em>Crosschain swap all my dai to usdc to gnosis</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Transfer</strong></mark></td><td>Transfer any token to an addres or ENS.<br><br>*Always check the address associated to the ENS.</td><td><ul><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my" </li></ul></td><td><ul><li><em>Transfer 10 usdc to vitalik.eth</em></li><li><em>Send 3 $ of dai to 0xabc...e</em></li><li><em>Send 1 usdc to vitalik.eth and 5 dollars of eth to limone.eth</em></li><li><em>Send 10% of my eth to 0xabc.sef and 85% to limone.eth</em></li><li><em>Transfer all my usdc to orbulo.eth</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Wrap</strong></mark></td><td>Wrap any native token.</td><td><ul><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my"</li></ul></td><td><ul><li><em>Wrap 1 eth</em></li><li><em>Wrap 100 dollars of matic on polygon</em></li><li><em>Wrap 100 $matic on polygon and 2 $bnb on the bsc</em></li><li><em>Wrap all my ftm</em> </li><li><em>Wrap 50% of my eth</em> </li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Unwrap</strong></mark></td><td>Unwrap any native token.</td><td><ul><li>in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my"</li></ul></td><td><ul><li><em>Unwrap 1 eth</em></li><li><em>Unwrap 100 dollars of matic on polygon</em></li><li><em>Unwrap 100 $matic on polygon and 2 $bnb on the bsc</em></li><li><em>Unwrap all my ftm</em> </li><li><em>Unwrap 50% of my eth</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Register ENS</strong></mark></td><td>Register an ENS and set it as primary address.</td><td><ul><li>Register multiple ENS at once</li><li>Use ".eth" at the end of the name or only the name</li><li>For the duration use seconds, days, months, years*</li><li>For the name use text, numbers or symbols</li><li>Set the registered ENS as your primary address<br><br>* Always check the conversation</li></ul></td><td><ul><li><em>Register vitalikinu.eth for 12 months</em></li><li><em>Register charlie.eth for 1 year and oscar.eth for 14 months</em></li><li><em>Register the following ens for 10 months: 123.eth and 1234.eth</em></li><li><em>Register 1_344.eth for 100 days</em></li><li><em>Register brianlovesens.eth for 10 days and set it as my primary address.</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Renew ENS</strong></mark></td><td>Renew an ENS.</td><td><p></p><ul><li>Renew multiple ENS at once</li><li>Use ".eth" at the end of the name or only the name</li><li>For the duration use seconds, days, months, years*</li><li>For the name use text, numbers or symbols<br><br>* Always check the conversation</li></ul></td><td><ul><li><em>Renew vitalikinu.eth for 12 months</em></li><li><em>Renew charlie.eth for 1 year and oscar.eth for 14 months</em></li><li><em>Renew the following ens for 10 months: 123.eth and 1234.eth</em></li><li><em>Extend 1_344.eth for 100 days</em></li><li><em>Extend the brianlovesens.eth duration for 10 days</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Check ENS availability, expiration, registrations and renewal cost.</strong></mark></td><td>(Read actions)<br>Perform a series of operations with ENS</td><td><ul><li>Check if an ENS is available or already registered</li><li>Check the ENS expiration</li><li>Check the registration/renewal costs of an ENS</li><li>Use ".eth" at the end of the name or only the name</li><li>For the name use text, numbers or symbols</li></ul></td><td><ul><li><em>Is limone.eth available?</em></li><li><em>When does vitalik.eth expire?</em></li><li><em>Tell me the registrations costs of the following ens: orbulo.eth, vitalik.eth, frankc.eth</em></li><li><em>When does the following ens expire: limone.eth, ethereum.eth, polygon.eth and 112233.eth</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Resolve ENS &#x3C;--> Address</strong></mark></td><td>(Read actions)<br>ENS resolution is the process of mapping an address to an ENS and vice versa</td><td><ul><li>Check what is the ENS associated to an address (only if the ENS is set as the primary name)</li><li>Check what is the address associated to an  ENS (only if the ENS is set as the primary name)</li></ul></td><td><ul><li><em>What are the address associated to the following ENS: vitalik.eth, amir.eth, adele.eth and orbulo.eth</em></li><li><em>What are the ENS domains associated to the following addresses: 0xabc..eer, 0xacd..12e and 0xfcv..edf.</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Deposit</strong></mark></td><td>Deposit ETH and other tokens into DeFi protocols</td><td><p></p><ul><li>The protocol name must be specified</li><li>The token out can be not specified</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li><li>Use "all my"</li></ul></td><td><ul><li><em>Deposit all my eth into lido protocol on ethereum</em></li><li><em>Deposit half of my usdc on polygon on aave and deposit 75% of my eth on aave on arbitrum</em></li><li><em>Stake 1 eth into lido and 0.5 eth into rocket pool protocols</em></li><li><em>Deposit 100 dollars of weth into each: aave, gearbox, compound and frax finance</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Withdraw</strong></mark></td><td>Withdraw ETH and other tokens from DeFi protocols</td><td><p></p><ul><li>The protocol name must be specified</li><li>The token out can be not specified</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li></ul></td><td><p></p><ul><li><em>Withdraw 0.1 eth from lido protocol on ethereum</em></li><li><em>Withdraw half of my usdc on polygon on aave and withdraw 75% of my eth on aave on arbitrum</em></li><li><em>Unstake 1 eth from lido and 0.5 eth from rocket pool protocols</em></li><li><em>Withdraw 100 dollars of weth into each: aave, gearbox, compound and frax finance</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Borrow</strong></mark></td><td>borrow tokens ETH from AAVE v3</td><td><p></p><ul><li>The protocol name if not specified will be considered as AAVE v3</li><li>The token to borrow must specified</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li></ul></td><td><p></p><ul><li><em>Borrow  0.1 eth from aave on arbitrum</em></li><li><em>Borrow  100 usdc from aave on polygon</em></li><li><em>Borrow  10$ cbeth from aave on base</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Repay</strong></mark></td><td>repay debt on AAVE v3</td><td><p></p><ul><li>The protocol name if not specified will be considered as AAVE v3</li><li>The token of the debt to repay must specified</li><li>Express amount in "$" or "dollars"</li><li>Write the "$" close to the token name</li><li>Use percentage (eg. 25%, half of, 75%, 99%)</li></ul></td><td><p></p><ul><li><em>Repay  0.1 eth of my debt on aave on arbitrum</em></li><li><em>Repay  half of my usdc debt on aave on arbitrum</em></li><li><em>Repay  10$ eth of my debt on aave on arbitrum</em></li></ul></td></tr><tr><td><mark style="color:yellow;"><strong>Check AAVE position parameters</strong></mark></td><td>(Read actions)<br>check loan-to-value, health rate, liquidation threshold, borrowed amount, borrowable amount)</td><td><p></p><ul><li>Check the user loan-to-value</li><li>Check the user health rate</li><li>Check the user liquidation threshold</li><li>Check the user total borroed amount</li><li>Check the user total amount available to borrow</li></ul></td><td><ul><li><em>What is my ltv on aave on arbitrum?</em></li><li><em>What is 0x..124 health factor on aave on polygon?</em></li><li><em>How much can i borrow right now on aave on base?</em></li><li><em>What is my position on aave on ethereum?</em></li></ul></td></tr></tbody></table>


# Use Cases

Some Use Cases devs can build on top of the Brian API and SDKs

## ‣ **AI Agent**

AI Agent is the hottest topic in the web3 right now. Build an AI Agent that can execute transactions independently or recommend transactions to the user.

Examples could be:

* DCA: executes transaction recurrently.
* Limit Order: executes transaction when a specified price is reached.
* DeFi Optimizer: dynamically invest on DeFi protocols according to some risk/return preferences.
* Portfolio Manager: balance asset allocation, yield generation, and risk management making data-driven investments.

Other more hardcore ideas include Agents that manage twitter/farcaster accounts by posting and executing transactions independently. Examples include:

* [tee\_hee\_he](https://medium.com/@tee_hee_he/setting-your-pet-rock-free-3e7895201f46)
* [terminal of truths](https://x.com/truth_terminal)
* [Luna](https://x.com/luna_virtuals)
* [elefant](https://warpcast.com/elefant)
* [aethernet](https://warpcast.com/aethernet)

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Multiple AI Agents collaboration**

Push AI Agents to the next step and build an app/framework/etc.. where multiple AI Agents collaborate each other executing transactions independently or recommending transactions to the user. You can find some ideas at the previous point (AI Agent).

For example, you could build a collaborative multi Agents system using LangChain or OpenAI Swarm library that leverages the Brian API.

Take inspiration from:

[lincoln.base.eth on Twitter / X](https://x.com/MurrLincoln/status/1850226148594082120)

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction
* **In-app AI Assistant**

  Embed an AI-powered assistant within an app/wallet/protocol, enabling users to execute transactions, gather market insights, ask information about the app or protocol, or receive personalized investment recommendations through conversational prompts. This assistant could even leverages real-time data and context to provide streamlined user guidance.

  Suggested Brian endpoints:

  * /transaction
  * /knowledge
  * /agent
  * /parameters-extraction

***

## ‣ **Intent based transaction app**

A transaction app designed to understand and respond to user intent directly from natural language prompts, interpreting commands like "invest in low-risk DeFi" or "set up daily purchases" to automate the desired actions with minimal input.

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **AI Powered Frame**

Build frames (using the [open frame standard](https://github.com/open-frames/standard)) that integrates natural language prompts. An example is: <https://github.com/brian-knows/brian-open-frame>

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **XMTP AI Powered Bot**

Build AI powered XMTP bots that integrates natural language prompts in a chat for making transactions or requesting information. An example is brian-agent.eth (try on [Converse](https://app.converse.xyz/conversation), the main XMTP client).

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **XMTP Multi AI Powered Bot in a Group chat**

Build an XMTP group chat with multiple AI powered Bots/Agents that integrates natural language prompts in a chat for making transactions or requesting information. An example is [https://ethglobal.com/showcase/power-agents-djqmb\[b\](https://ethglobal.com/showcase/power-agents-djqmb)](https://ethglobal.com/showcase/power-agents-djqmb%5Bb%5D\(https://ethglobal.com/showcase/power-agents-djqmb\)).

Imagine having your personal agents in a group and using them on demand to perform different types of tasks

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Telegram AI Powered Bot**

Build AI powered Telegram bots that integrates natural language prompts in a chat for making transactions or requesting information.

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Telegram mini app**

Build AI powered Telegram mini app that integrates natural language prompts for making transactions or requesting information.

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

## ‣ **Wearable/hardware devices**

Use Brian API within wearable applications (e.g., apple watch). Provides timely, voice-activated financial insights, make transactions and give market recommendations directly to a smartwatch or similar device, keeping users connected and responsive to market changes on the go.

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Extend Brian API capabilities (using the parameters-extraction endpoint)**

Extend the current /transaction and /knowledge capabilities using the /parameters-extraction endpoint to build new custom logic. You could implement a new solver, a new chain, a new DeFi protocol and so on. Just call the /parameters-extraction, take the parameters extracted and build your own logic with it.

Suggested Brian endpoints:

* /parameters-extraction

***

## ‣ **Voice recognition**

Currently, the Brian API uses text inputs. Build AI-enabled voice recognition allowing users to execute transactions or ask information simply by speaking commands, providing a hands-free and accessible way to interact with their assets. **Attention**: the solution must be robust! it's not enough to use a model to turn voice into text. Why? Standard voice recognition models don't know web3 vocabulary and would work poorly.

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Stable coin payments**

Build AI agents/apps that facilitate and optimize stablecoin payments, whether for DeFi investments, cross-border transfers, or routine transactions proposing. Leverage natural language for proposing new ways of interacting with stablecoins.

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Hackathon assistant**

Build an app/service specialized for hackathons, guiding participants through the different rules, prizes and so on. If you need it, ask the Brian team to create a new custom knowledge box that you can leverage using /knowledge endpoint.

You might think about integrating this service within sites but more interestingly within Notion pages.

Suggested Brian endpoints:

* /knowledge
* /agent

***

## ‣ **Metamask Snap**

Build a Metamask Snap integrating natural language prompts extending Metamask standard wallet functionalities for making transactions or requesting information.

You can check the SnappyAI example here: <https://ethglobal.com/showcase/snappyai-n2igg>

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Browser Extensions**

Build a browser extension providing in-situ AI assistance for transaction management, data analysis, and decision-making, transforming the browser into an interactive, AI-driven Web3 toolkit. You could have this extension that leverages a browser wallet (eg. Metamask) for making web3 transactions or perhaps the extension could have a built-in wallet? 🤷

Suggested Brian endpoints:

* /transaction
* /knowledge
* /agent
* /parameters-extraction

***

## ‣ **Token bound Account**

Build an app leveraging the [ERC-C6551 Token Bound Account Standard](https://www.quicknode.com/guides/ethereum-development/nfts/how-to-create-and-deploy-an-erc-6551-nft). Imagine an app that lets you create a smart account controlled by an NFT. Chat with your NFT in natural language to perform transactions, request information etc.. Propose new NFT user experiences and increase their usefulness. Maybe the NFT can have its own personality or customizable features?

Suggested Brian endpoints:

* /agent
* /parameters-extraction


# Powered by Brian

Some cases studies of projects built on top of our API and SDKs

## ‣ [Brian App](https://www.brianknows.org/app)&#x20;

A non-custodial intent-based app for any web3 interaction.

## ‣ [Mode DeFAI Copilot](https://x.com/modenetwork/status/1882803123523383435)

Your DeFAI Co-Pilot on Mode - Any onchain task in natural language.

## ‣ [AskBrian Farcaster Bot](https://warpcast.com/askbrian)

Tag @askbrian to perform on-chain TXs directly on Farcaster.

## ‣[ Segugio](https://github.com/builders-garden/segugio-bot)

Deploy copy-trading bots directly from a XMTP Chat.

## ‣ [Ava](https://ava-portfolio-manager-ai-agent.vercel.app/)

Specialised AI agents for managing DeFi portfolios

## ‣ [Briannah](https://warpcast.com/briannah)

Deploy ERC-20s via natural

## ‣ [Synapse](https://synapse-amber.vercel.app/)

Synapse is an intelligent DeFi assistant that provides personalized guidance and automated interactions with Starknet's DeFi ecosystem.&#x20;

## ‣ [BEAMX](https://beamx-meme.vercel.app/)

Launch memecoins with AI-driven prompts on the Unruggable Meme SDK.


# FAQ

This is a list of the most frequently asked questions about Brian to help you better understand how it works.

**1) What is Brian?**

**Brian** enables users and AI Agents to interact with Web3 by providing textual prompts to execute various Web3-related actions, such as:

* Transactions: "Can you swap 10 usdc for eth on Ethereum ?"&#x20;
* Protocol info: "How Uniswap v4 hooks work?"
* Protocol data: "Give me the pools with the highest TVL on Uniswap"
* Smart contract: "Generate an ERC20 with name BrianAI and a supply of 1000 tokens"

The [Brian API](/brian-api/apis) and [Brian TS SDK](/brian-sdk/brian-typescript-sdk) allow developers to integrate the Brian AI capabilities in their applications to build intent-based apps that could be custodial, non-custodial, or support smart accounts.

The [LangChain<>Brian SDK](/ai-agents/langchain-less-than-greater-than-brian-sdk) allows devs to launch LangChain AI Agents capable of transacting and deploying tokens on-chain.

The [Brian App](https://www.brianknows.org/), built on top of Brian APIs, offers users an interface for performing transactions in a non-custodial way, researching web3 info, and deploying smart contracts by prompt.

**2) How can I use Brian?**

If you are an application or a protocol, you can offer your users a new way to interact based on prompts in English. Instead of building complex UX/UI, you can do everything through a simple prompt.&#x20;

If you are a bot or a chat-based app, you can offer tour users some powerful capabilities such as making transactions using prompts in the app.

If you are a developer, you can use Brian as a dev tool to improve your pipeline and testing phase by being able to have faster access to tools to manipulate data, extract transaction calldata, have access to tokens lists on different chains, execute transactions, quickly deploy contracts for testing, etc... starting from prompts.

If you are a Web3 user, even if you are not skilled, you can use the [Brian app](https://www.brianknows.org/app) and perform transactions or search for information by prompting

**3) Why should I use Brian and not ChatGPT?**

Brian has web3-specific capabilities that chatGPT does not have such as:

* input a prompt and get the transaction object for different kinds of transactions such as swap, bridge, cross-chain swap, transfer, create a Safe Account, etc...
* input a prompt, deploy, and interact with a smart contract (look at the smart contracts supported)

We want to remain at the forefront of blockchain technology and can adapt to evolving industry standards and protocols.

**4) Is Brian App a custodial solution?**

No! the Brian App is a non-custodial solution and for the transaction feature you have to confirm the operation, Brian will not execute it for you.

**5) Why I should trust an AI?**

You're not trusting any AI! The AI component of the Brian application only extracts your intent and then gives you the transaction you have to confirm with your wallet. You have to try it to understand it!

**6) What are some TX examples?**

Bridge \
"Bridge 0.01 eth from ethereum to polygon" \
"Bridge 0.01 usdc from optimism to arbitrum" \
"Bridge 0.01 dai to gnosis and bridge 0.01 eth to arbitrum"  \
\
Swap \
"Swap 1 usdc to eth" \
"Swap 1 usdc to eth with address 0xabc as receiver" \
"Create a portfolio of 1000 usdc and split them into 4 tokens: pendle, gmx, eth, usdt"  \
\
Crosschain Swap \
"Bridge 1 usdc to dai from polygon to ethereum" \
"Bridge 1 eth to usdt from polygon to arbitrum with limone.eth as receiver" \
"Bridge 1 usdc to dai and 1 usdt to dai from polygon to ethereum" \
\
Transfer \
"Send 0.1 eth to vitalik.eth" \
"Transfer 1 usdc to vitalik.eth and 1 usdt to orbulo.eth" \
"You have 257 usdc, split them in 3 transfers to vitalik.eth, limone.eth, orbulo.eth"  \
\
Multiple operations \
"Send 0.1 eth to vitalik.eth and bridge 1 usdc to dai from polygon to ethereum" \
"Bridge 0.01 usdc from optimism to arbitrum and Swap 1 usdc to eth with address 0xabc as receiver" \
"Bridge 0.01 dai to gnosis and bridge 0.01 eth to arbitrum and send 1 usdc to matteoikari.eth"

**7) What blockchains does Brian support?**

Ethereum and the main L2s (Arbitrum, Optimism, Gnosis, Polygon, Linea, Base, zksync, Mode, Taiko) and side chains (BNB Chain). Plus Starknet and Solana.


# APIs

Integrate Brian in your project via APIs.

{% hint style="success" %}
Check the [Prompt Guide](/prompt-guide) to better prompt on Brian.
{% endhint %}

Brian API provides endpoints to interact with through English prompts for making web3 interactions.

* `/transaction`: get executable transactions from a prompt.
* `/knowledge`: get a textual response (and the web3 docs used) from a prompt.
* `/agent`: get executable transactions and textual response (and the web3 docs used) from a prompt and a chat history.
* `/smart-contract`: get the solidity smart contract code from a prompt.
* `/parameters-extraction`: get the extracted parameters for the user's intent from a prompt.
* `/networks`: get the networks supported by Brian.
* `/actions`: get the actions supported by Brian with the related parameters and descriptions.


# API Swagger

Try the Brian API!

You can visit the Swagger page of the APIs here: <https://api.brianknows.org/swagger>

To use the Swagger, you need a Brian API Key. Create one for free 👉 [here](/brian-api/api-key).


# /transaction

{% hint style="success" %}
Check the [Prompt Guide](/prompt-guide) to better prompt on Brian.
{% endhint %}

{% hint style="danger" %}
API calls to the `/transaction` endpoint don't automatically execute transactions onchain. The `/transaction` endpoint gives you back the data representing a standard transaction object! **Learn more** at the [Transaction flow ](/brian-api/apis/transaction/transactions-flow)page.
{% endhint %}

## Generate transaction(s)  from a prompt.

<mark style="color:green;">`POST`</mark> `https://api.brianknows.org/api/v0/agent/transaction`

This allows you to send a prompt to Brian and return a transaction calldata, ready to be executed onchain, and multiple transaction info parameters.

Some of the supported actions include:

* swap
* bridge
* transfer
* deposit and withdraw from DeFi protocols
* ENS domain registration

{% hint style="info" %}
Check the [next page](/brian-api/apis/transaction/actions-networks-and-tokens-supported) for a comprehensive overview of actions and chains supported.
{% endhint %}

#### Headers

| Name                                              | Type             | Description        |
| ------------------------------------------------- | ---------------- | ------------------ |
| x-brian-api-key<mark style="color:red;">\*</mark> | String           | Brian API key.     |
| Content-Type<mark style="color:red;">\*</mark>    | application/json | Body content type. |

#### Request Body

| Name                                      | Type   | Description                              |
| ----------------------------------------- | ------ | ---------------------------------------- |
| prompt<mark style="color:red;">\*</mark>  | String | User input prompt.                       |
| chainId                                   | String | Chain ID of the user.                    |
| address<mark style="color:red;">\*</mark> | String | Address that will send the transactions. |

*\*mandatory parameters*

{% hint style="success" %}
If you don't pass the `chainId` in the body, the source chain will be deducted from the prompt, if available. Otherwise, it will throw an error.
{% endhint %}

{% tabs %}
{% tab title="200: OK." %}
View below for some real examples.

```json
{
  "result": [
    {
      "solver": "",
      "action": "",
      "type": "",
      "data": {
        "description": "",
        "steps": [
          {
            "chainId": ,
            "blockNumber": ,
            "from": "",
            "to": "",
            "gasLimit": "",
            "data": "",
            "value": "",
            "protocol": {
              "key": "",
              "name": "",
              "logoURI": ""
            }
          }
        ],
        "gasCostUSD": "",
        "fromChainId": ,
        "fromAmountUSD": ,
        "fromAmount": "",
        "fromToken": {
          "address": "",
          "chainId": ,
          "symbol": "",
          "decimals": ,
          "name": "",
          "coinKey": "",
          "logoURI": "",
          "priceUSD": ""
        },
        "fromAddress": "",
        "toChainId": ,
        "toAmountUSD": ,
        "toAmount": "",
        "toAmountMin": "",
        "toToken": {
          "address": "",
          "chainId": ,
          "symbol": "",
          "decimals": ,
          "name": "",
          "coinKey": "",
          "logoURI": "",
          "priceUSD": ""
        },
        "toAddress": "",
        "receiver": "",
        "protocol": {
          "key": "",
          "name": "",
          "logoURI": ""
        }
      }
      "extractedParams": {
        "action": "",
        "chain": "",
        "token1": "",
        "token2": "",
        "address": "",
        "amount": ""
      },
      "conversationHistory": [
        {
          "sender": "",
          "content": ""
        },
        {
          "sender": "",
          "content": ""
        }
      ]
    }
  ]
}
```

{% endtab %}

{% tab title="400: Bad Request." %}

```json
{
  "error": ",
  "extractedParams": [
    {
      "action": "",
      "chain": "",
      "token1": "",
      "token2": "",
      "address": "",
      "amount": "",
      ....
    }
  ],
  "conversationHistory": [
    {
      "sender": "",
      "content": ""
    },
    {
      "sender": "",
      "content": ""
    }
  ]
}
```

{% endtab %}

{% tab title="500: Internal Server Error Something went wrong!" %}

<pre class="language-json"><code class="lang-json"><strong>{
</strong>    "error": "internal server error."
}
</code></pre>

{% endtab %}
{% endtabs %}

## API examples

Some real examples of API calls

### EVM chains

#### Swap tokens

{% code overflow="wrap" %}

```bash
curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "I want to swap 10 USDC for ETH on base", "address": "0x9319b31838bba444CCeAeD025153a48AD6377471"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
```

{% endcode %}

<details>

<summary>Response</summary>

{% code overflow="wrap" %}

```json
{
  "result": [
    {
      "solver": "Enso",
      "action": "swap",
      "type": "write",
      "data": {
        "description": "You are about to swap 10.000000 USDC($10.00) for 0.002988 ETH ($9.96) on Base using Enso solver. The address receiver is 0x9319...7471.",
        "steps": [
          {
            "chainId": 8453,
            "blockNumber": 17822776,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "gasLimit": "80000",
            "data": "0x095ea7b300000000000000000000000080eba3855878739f4710233a8a19d89bdd2ffb8e0000000000000000000000000000000000000000000000000000000000989680",
            "value": "0"
          },
          {
            "chainId": 8453,
            "blockNumber": 17822776,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
            "gasLimit": "453028",
            "data": "0xb35d7e73000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda029130000000000000000000000000000000000000000000000000000000000989680000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000008a9059cbb010001ffffffffff833589fcd6edb6e08f4c7c32d4f71b54bda02913095ea7b3010203ffffffffff833589fcd6edb6e08f4c7c32d4f71b54bda0291319198595a30485ffffffff85def1c0ded9bec7f1a1670819833240f027b25eff9bd3b227018504ffffffff056675a323dedb77822fcf39eaa9d682f6abe72555ddcd52200105ffffffffff057e7d64d987cab6eed08a191c4c2459daf2f8ed0b19198595a30586ffffffffff9319b31838bba444cceaed025153a48ad63774716e7a43a3010507ffffffff057e7d64d987cab6eed08a191c4c2459daf2f8ed0b241c59120105ffffffffffff7e7d64d987cab6eed08a191c4c2459daf2f8ed0b000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000001c0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000002400000000000000000000000000000000000000000000000000000000000000aa00000000000000000000000000000000000000000000000000000000000000ac00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000129b480ad625bcd1a5c3a1c10d708114726fa467000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000027100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000def1c0ded9bec7f1a1670819833240f027b25eff00000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000986f70000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000828415565b0000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda02913000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000000000000000000000000000000000000000000000000000000000986f70000000000000000000000000000000000000000000000000000a4c14a690bf9d00000000000000000000000000000000000000000000000000000000000000a00000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000004600000000000000000000000000000000000000000000000000000000000000500000000000000000000000000000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000080000000000000000000000000000000000000000000000000000000000000040000000000000000000000000000000000000000000000000000000000000038000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000000000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda02913000000000000000000000000420000000000000000000000000000000000000600000000000000000000000000000000000000000000000000000000000001400000000000000000000000000000000000000000000000000000000000000340000000000000000000000000000000000000000000000000000000000000034000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000986f70000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000003400000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000012556e69737761705633000000000000000000000000000000000000000000000000000000000000000000000000986f70000000000000000000000000000000000000000000000000000a500a6d210dd7000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000e00000000000000000000000002626664c2603336e57b271c5c0b26f421741e481000000000000000000000000000000000000000000000000000000000000006000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000042833589fcd6edb6e08f4c7c32d4f71b54bda0291300006450c5725949a6f0c72e6c4a641f24049a917db0cb0001f442000000000000000000000000000000000000060000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000400000000000000000000000004200000000000000000000000000000000000006ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000003000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000a000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000000000001000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000000000000000000000000000000003f5c6904e3a000000000000000000000000ad01c20d5886137e056775af56915de824c8fce50000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000001000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda029130000000000000000000000000000000000000000000000000000000000000000869584cd000000000000000000000000100000000000000000000000000000000000001100000000000000000000000000000000000000005b210060dff63345919e860400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000a4c3321aed839",
            "value": "0"
          }
        ],
        "gasCostUSD": "",
        "fromChainId": 8453,
        "fromAmountUSD": "10",
        "fromAmount": "10000000",
        "fromToken": {
          "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
          "chainId": 8453,
          "symbol": "USDC",
          "decimals": 6,
          "name": "USD Coin",
          "coinKey": "USDC",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png",
          "priceUSD": "1"
        },
        "fromAddress": "0x9319b31838bba444CCeAeD025153a48AD6377471",
        "toChainId": 8453,
        "toAmountUSD": "9.957563936252797",
        "toAmount": "2988177586862245",
        "toAmountMin": "2988177586862245",
        "toToken": {
          "address": "0x0000000000000000000000000000000000000000",
          "chainId": 8453,
          "symbol": "ETH",
          "decimals": 18,
          "name": "ETH",
          "coinKey": "ETH",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2/logo.png",
          "priceUSD": "3332.32"
        },
        "toAddress": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
        "receiver": "0x9319b31838bba444CCeAeD025153a48AD6377471",
        "protocol": {
          "key": "enso",
          "name": "enso",
          "logoURI": ""
        }
      }
    }
  ]
}


```

{% endcode %}

</details>

{% hint style="info" %}
The steps array can contain a list of possible swap routes that the user can choose from. In some cases, it could return just one step.
{% endhint %}

#### Bridge tokens

{% code overflow="wrap" %}

```bash
curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "I want to bridge 10 USDC from Ethereum to Arbitrum", "address": "0x9319b31838bba444CCeAeD025153a48AD6377471"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
```

{% endcode %}

<details>

<summary>Response</summary>

{% code overflow="wrap" %}

```json
{
  "result": [
    {
      "solver": "Bungee",
      "action": "bridge",
      "type": "write",
      "data": {
        "description": "You are about to bridge 10.000000 USDC for 9.975330 USDC ($10.00) from Ethereum to Arbitrum one using Bungee solver. The address receiver is 0x9319...7471.",
        "steps": [
          {
            "chainId": 1,
            "blockNumber": 20427034,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
            "gasLimit": "80000",
            "data": "0x095ea7b30000000000000000000000003a23f943181408eac424116af7b7790c94cb97a50000000000000000000000000000000000000000000000000000000000989680",
            "value": "0"
          },
          {
            "chainId": 1,
            "blockNumber": 20427034,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0x3a23F943181408EAC424116Af7b7790c94Cb97a5",
            "gasLimit": "500000",
            "data": "0x000001ad792ebcb90000000000000000000000000000000000000000000000000000000000989680000000000000000000000000000000000000000000000000000000000000004000000000000000000000000000000000000000000000000000000000000000c00000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000001e0000000000000000000000000000000000000000000000000000000000000605c00000000000000000000000000000000000000000000000000000000000009ea00000000000000000000000000000000000000000000000000000000000000020000000000000000000000009319b31838bba444cceaed025153a48ad63774710000000000000000000000009319b31838bba444cceaed025153a48ad63774710000000000000000000000000000000000000000000000000000000000000002000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb48000000000000000000000000af88d065e77c8cc2239327c5edb3a432268e583100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000983624000000000000000000000000000000000000000000000000000000000000a4b100000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000066aa44c70000000000000000000000000000000000000000000000000000000066aa98cdd00dfeeddeadbeef765753be7f7a64d5509974b0d678e1e3149b02f4",
            "value": "0x00"
          }
        ],
        "gasCostUSD": "",
        "fromChainId": 1,
        "fromAmountUSD": "10",
        "fromAmount": "10000000",
        "fromToken": {
          "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
          "chainId": 1,
          "symbol": "USDC",
          "decimals": 6,
          "name": "USD Coin",
          "coinKey": "USDC",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png",
          "priceUSD": "1"
        },
        "fromAddress": "0x9319b31838bba444CCeAeD025153a48AD6377471",
        "toChainId": 42161,
        "toAmountUSD": "9.97533",
        "toAmount": "9975332",
        "toAmountMin": "9975332",
        "toToken": {
          "address": "0xaf88d065e77c8cC2239327C5EDb3A432268e5831",
          "chainId": 42161,
          "symbol": "USDC",
          "decimals": 6,
          "name": "USD Coin",
          "coinKey": "USDC",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png",
          "priceUSD": "1"
        },
        "toAddress": "0x3a23F943181408EAC424116Af7b7790c94Cb97a5",
        "receiver": "0x9319b31838bba444CCeAeD025153a48AD6377471",
        "protocol": {
          "key": "across",
          "name": "Across",
          "logoURI": "https://miro.medium.com/max/800/1*PN_F5yW4VMBgs_xX-fsyzQ.png"
        }
      }
    }
  ]
}
```

{% endcode %}

</details>

{% hint style="info" %}
The steps array can contain a list of possible swap routes that the user can choose from. In some cases, it could return just one step.
{% endhint %}

#### Deposit on DeFi protocol

{% code overflow="wrap" %}

```bash
curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "deposit 100 usdc to aave protocol on Ethereum", "address": "0xA9bC8A58B39935BA3D8D1Ce4b0d3383153F184E1"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
```

{% endcode %}

<details>

<summary>Response</summary>

{% code overflow="wrap" %}

```json
{
  "result": [
    {
      "solver": "Enso",
      "action": "deposit",
      "type": "write",
      "data": {
        "description": "You are about to deposit 100.000000 USDC ($100.00) into aave-v3 protocol, obtaining 99.900000 AETHUSDC on Ethereum. The address receiver is: 0x9319...7471.",
        "steps": [
          {
            "chainId": 1,
            "blockNumber": 20427040,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
            "gasLimit": "80000",
            "data": "0x095ea7b300000000000000000000000080eba3855878739f4710233a8a19d89bdd2ffb8e0000000000000000000000000000000000000000000000000000000005f5e100",
            "value": "0"
          },
          {
            "chainId": 1,
            "blockNumber": 20427040,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
            "gasLimit": "358072",
            "data": "0xb35d7e73000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001c00000000000000000000000000000000000000000000000000000000000000009a9059cbb010001ffffffffffa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48095ea7b3010203ffffffffffa0b86991c6218b36c1d19d4a2e9eb0ce3606eb4870a082310104ffffffffff0298c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5ce8eda9df0105030406ffffff87870bca3f3fd6335c3f4ce8392d69350b4fa4e270a082310104ffffffffff0498c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5cb67d77c5010402ffffffff04ca99eaa38e8f37a168214a3a57c9a45a58563ed5a9059cbb010704ffffffffff98c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c6e7a43a3010408ffffffff047e7d64d987cab6eed08a191c4c2459daf2f8ed0b241c59120104ffffffffffff7e7d64d987cab6eed08a191c4c2459daf2f8ed0b00000000000000000000000000000000000000000000000000000000000000090000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000001e00000000000000000000000000000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000026000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000002e000000000000000000000000000000000000000000000000000000000000003200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000129b480ad625bcd1a5c3a1c10d708114726fa467000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000186a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000005f45a6000000000000000000000000000000000000000000000000000000000000000200000000000000000000000007d585b0e27bbb3d981b7757115ec11f47c4769940000000000000000000000000000000000000000000000000000000000000020000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000009319b31838bba444cceaed025153a48ad637747100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000005c69f58",
            "value": "0"
          }
        ],
        "gasCostUSD": "",
        "fromChainId": 1,
        "fromAmountUSD": "100",
        "fromAmount": "100000000",
        "fromToken": {
          "address": "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48",
          "chainId": 1,
          "symbol": "USDC",
          "decimals": 6,
          "name": "USD Coin",
          "coinKey": "USDC",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png",
          "priceUSD": "1"
        },
        "fromAddress": "0x9319b31838bba444CCeAeD025153a48AD6377471",
        "toChainId": 1,
        "toAmountUSD": "99.9",
        "toAmount": "100000000",
        "toAmountMin": "100000000",
        "toToken": {
          "address": "0x98C23E9d8f34FEFb1B7BD6a91B7FF122F4e16F5c",
          "chainId": 1,
          "symbol": "aEthUSDC",
          "decimals": 6,
          "name": "Aave Ethereum USDC",
          "coinKey": "aEthUSDC",
          "logoURI": "https://static.debank.com/image/eth_token/logo_url/0x98c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c/d1e0d14800c1e4657fb8c25e0f073cf0.png",
          "priceUSD": "1"
        },
        "toAddress": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
        "receiver": "0x9319b31838bba444CCeAeD025153a48AD6377471",
        "protocol": {
          "key": "aave-v3",
          "name": "aave-v3",
          "logoURI": ""
        }
      }
    }
  ]
}
```

{% endcode %}

</details>

***

### Starknet

#### Transfer tokens

<pre class="language-bash"><code class="lang-bash"><strong>curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "transfer 10 usdc to 0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73 on starknet", "address": "0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
</strong></code></pre>

<details>

<summary>Response</summary>

```json
{
  "result": [
    {
      "solver": "Brian-Starknet",
      "action": "transfer",
      "type": "write",
      "data": {
        "description": "You are about to send 10 USDC ($10.0) to 0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73 on Starknet.",
        "steps": [
          {
            "contractAddress": "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
            "entrypoint": "transfer",
            "calldata": [
              "2333149233072038891240751670574223940282370554046219129156039053790278777971",
              "10000000",
              "0"
            ]
          }
        ],
        "fromChainId": "SN_MAINNET(custom chainId 4012)",
        "fromAmount": "10000000",
        "fromToken": {
          "address": "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
          "symbol": "usdc",
          "decimals": 6
        },
        "fromAddress": "0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54",
        "toChainId": "SN_MAINNET(custom chainId 4012)",
        "toAmount": "10000000",
        "toAmountMin": "10000000",
        "toToken": {
          "address": "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
          "symbol": "usdc",
          "decimals": 6
        },
        "toAddress": "0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73",
        "receiver": "0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73"
      },
      "extractedParams": {
        "action": "transfer",
        "token1": "usdc",
        "chain": "starknet",
        "address": "0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73",
        "amount": "10"
      },
      "conversationHistory": [
        {
          "sender": "user",
          "content": "transfer 10 usdc to 0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73 on starknet"
        },
        {
          "sender": "brian",
          "content": "You are about to send 10 USDC ($10.0) to 0x05288402db9a6260a5edfeeb6e5922fd103280e579d103106788a2a33b42fc73 on Starknet."
        }
      ]
    }
  ]
}
```

</details>

#### Swap tokens

<pre class="language-bash"><code class="lang-bash"><strong>curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "swap 10 usdc to eth on starknet", "address": "0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
</strong></code></pre>

<details>

<summary>Response</summary>

```json
{
  "result": [
    {
      "solver": "Avnu.fi",
      "action": "swap",
      "type": "write",
      "data": {
        "description": "You are about to swap 10.0 USDC ($9.9) for 0.0025 ETH ($10.0) on Starknet using Avnu.fi solver. The address receiver is 0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54.",
        "steps": [
          {
            "contractAddress": "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
            "entrypoint": "approve",
            "calldata": [
              "1878172929613570324457239593384623395652998589633516919063222269774660188943",
              "10000000",
              "0"
            ]
          },
          {
            "contractAddress": "0x4270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f",
            "entrypoint": "multi_route_swap",
            "calldata": [
              "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
              "0x989680",
              "0x0",
              "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
              "0x90ce50d6cc4bf",
              "0x0",
              "0x8c7634d05aa5d",
              "0x0",
              "0x309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54",
              "0x1",
              "0x129b480ad625bcd1a5c3a1c10d708114726fa467",
              "0x1",
              "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
              "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
              "0x5dd3d2f4429af886cd1a3b08289dbcea99a294197e9eb43b0e0325b4b",
              "0xe8d4a51000",
              "0x6",
              "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
              "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
              "0x68db8bac710cb4000000000000000",
              "0xc8",
              "0x0",
              "0x332bdbc767000276a4e6b4939a"
            ]
          }
        ],
        "amountToApprove": "10000000",
        "gasCostUSD": "",
        "fromChainId": "SN_MAINNET(custom chainId 4012)",
        "fromAmountUSD": "9.949725",
        "fromAmount": "10000000",
        "fromToken": {
          "address": "0x53c91253bc9682c04929ca02ed00b3e423f6710d2ee7e0d5ebb06f3ecf368a8",
          "symbol": "USDC",
          "decimals": 6
        },
        "fromAddress": "0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54",
        "toChainId": "SN_MAINNET(custom chainId 4012)",
        "toAmountUSD": "9.987543",
        "toAmount": "2547452702672063",
        "toToken": {
          "address": "0x49d36570d4e46f48e99674bd3fcc84644ddd6b96f7c741b1562b82f9e004dc7",
          "symbol": "ETH",
          "decimals": 18
        },
        "toAddress": "0x4270219d365d6b017231b52e92b3fb5d7c8378b05e9abc97724537a80e93b0f",
        "receiver": "0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54"
      },
      "extractedParams": {
        "action": "swap",
        "chain": "starknet",
        "token1": "usdc",
        "token2": "eth",
        "address": "",
        "amount": "10"
      },
      "conversationHistory": [
        {
          "sender": "user",
          "content": "swap 10 usdc to eth on starknet"
        },
        {
          "sender": "brian",
          "content": "You are about to swap 10.0 USDC ($9.9) for 0.0025 ETH ($10.0) on Starknet using Avnu.fi solver. The address receiver is 0x0309e6b209031362268d62d646a067365e6f6d6eb7f571b5212cbdfd5f26fe54."
        }
      ]
    }
  ]
}
```

</details>

***

### Solana

#### Transfer tokens

<pre class="language-bash"><code class="lang-bash"><strong>curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "transfer 2 sol to CnXMWB8W7bcnADsZsJAJYkcuu8jr392ZFvxDBiumW3ww on solana", "address": "53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
</strong></code></pre>

<details>

<summary>Response</summary>

```json
{
  "result": [
    {
      "solver": "Brian-Solana",
      "action": "transfer",
      "type": "write",
      "data": {
        "description": "You are about to transfer 2 sol to CnXMWB8W7bcnADsZsJAJYkcuu8jr392ZFvxDBiumW3ww on Solana.",
        "steps": [
          {
            "data": "gAEAAQM8LZeA9qBvRbVQG5heYfyIuwarnP0Gu9tInqEHyOcgla8aA27cGkJPxlgCjOuAxr2EFf+HIngbWdjMb4lANG/CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACTDmG4RDbxk5rt25m9qiHclTvVxLZxbKeDyW+6AW0SSAECAgABDAIAAABAQg8AAAAAAAA="
          }
        ],
        "fromChainId": 1151111081099710,
        "fromAmount": "2000000000",
        "fromTokenSymbol": "sol",
        "fromToken": "11111111111111111111111111111111",
        "fromAddress": "53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr",
        "toChainId": 1151111081099710,
        "toAmount": "2000000000",
        "toAmountMin": "2000000000",
        "toToken": "11111111111111111111111111111111",
        "toTokenSymbol": "sol",
        "toAddress": "11111111111111111111111111111111",
        "receiver": "CnXMWB8W7bcnADsZsJAJYkcuu8jr392ZFvxDBiumW3ww"
      },
      "extractedParams": {
        "action": "transfer",
        "token1": "sol",
        "chain": "solana",
        "address": "CnXMWB8W7bcnADsZsJAJYkcuu8jr392ZFvxDBiumW3ww",
        "amount": "2"
      },
      "conversationHistory": [
        {
          "sender": "user",
          "content": "transfer 2 sol to CnXMWB8W7bcnADsZsJAJYkcuu8jr392ZFvxDBiumW3ww on solana"
        },
        {
          "sender": "brian",
          "content": "You are about to transfer 2 sol to CnXMWB8W7bcnADsZsJAJYkcuu8jr392ZFvxDBiumW3ww on Solana."
        }
      ]
    }
  ]
}
```

</details>

#### Swap tokens

<pre class="language-bash"><code class="lang-bash"><strong>curl -XPOST "https://api.brianknows.org/api/v0/agent/transaction" -d '{"prompt": "swap 2 sol to usdc on solana", "address": "53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr"}' -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY"
</strong></code></pre>

<details>

<summary>Response</summary>

```json
{
  "result": [
    {
      "solver": "Jupiter",
      "action": "swap",
      "type": "write",
      "data": {
        "description": "You are about to swap 2000000000 sol for 427998127 usdc on [object Object] using Jupiter solver. The address receiver is 53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr.",
        "steps": [
          {
            "data": "AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAAQAGCTwtl4D2oG9FtVAbmF5h/Ii7Bquc/Qa720ieoQfI5yCVuyTAY0LGzNW3JsUn1WCmzitgoSRt4O5DFQ4mohw/AsvDuizr7JweMPVk7RuLPfzrfj9yS9TUC6qnDZt0jVJpCQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAwZGb+UhFzL/7K26csOb57yM5bvF9xJrLEObOkAAAAAEedVb8jHAbu50xW7OaBUH/bGy3qP0jlECsc2iVrwTjwbd9uHXZaGT2cvhRs7reawctIXtX1s3kTqM9YV+/wCpjJclj04kifG7PRApFI4NgwtaE5na/xCEBI572Nvp+Fm0P/on9df2SnTAmx8pWHneSwmrNt/J3VFLMhqns4zl6AaGHcvh7tvPVuJirOhrdz0uo/2pa9nVljQ7Ch7anDl2BwQABQLAXBUABAAJAwQXAQAAAAAABwYAAgAOAwYBAQMCAAIMAgAAAACUNXcAAAAABgECAREFFwYAAgEFEwUIBRAPDQACAQwJCgsGERESI+UXy5d6460qAQAAABlkAAEAlDV3AAAAAK+7ghkAAAAAMgAABgMCAAABCQHaPXgX4+NThv0V83XX6UI4/kChgKeZEox3sbxohfBHHwVSS0xRTgYaSlBNTzg="
          }
        ],
        "fromChainId": 1151111081099710,
        "fromAmount": "2000000000",
        "fromTokenSymbol": "sol",
        "fromToken": "So11111111111111111111111111111111111111112",
        "fromAddress": "53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr",
        "toChainId": 1151111081099710,
        "toAmount": "427998127",
        "toAmountMin": "427998127",
        "toToken": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        "toTokenSymbol": "usdc",
        "toAddress": [
          "Gkt4BpMRFxhhrrVMQsewM74ggriAbxyN2yUYDD9qt1NV"
        ],
        "receiver": "53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr"
      },
      "extractedParams": {
        "action": "swap",
        "chain": "solana",
        "token1": "sol",
        "token2": "usdc",
        "address": "",
        "amount": "2"
      },
      "conversationHistory": [
        {
          "sender": "user",
          "content": "swap 2 sol to usdc on solana"
        },
        {
          "sender": "brian",
          "content": "You are about to swap 2000000000 sol for 427998127 usdc on [object Object] using Jupiter solver. The address receiver is 53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr."
        }
      ]
    }
  ]
}
```

</details>

***

## Allowance and Approval management

**For EVMs and Starknet**, the `steps` array will contain an approve transaction as the first position when needed according to the transaction involved.

It first checks the existing allowance and returns a transaction approving the exact amount needed.

For example, if the transaction involves a native token as the input token, the steps array will not contain the approve transaction. If the transaction involves an ERC20 token as the input token and the existing allowance covers the amount to spend, the steps array will not contain the approve transaction. Finally, suppose the transaction involves an ERC20 token as the input token and the existing allowance doesn't cover the amount to spend. In that case, the steps array will contain the approve transaction in the first position.

Here is an example of a USDC swap:

```typescript
...
          "steps": [
          // Approve transaction first
          {
            "chainId": 1,
            "blockNumber": 20427040,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48",
            "gasLimit": "80000",
            "data": "0x095ea7b300000000000000000000000080eba3855878739f4710233a8a19d89bdd2ffb8e0000000000000000000000000000000000000000000000000000000005f5e100",
            "value": "0"
          },
          // Swap transaction in second place
          {
            "chainId": 1,
            "blockNumber": 20427040,
            "from": "0x9319b31838bba444CCeAeD025153a48AD6377471",
            "to": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
            "gasLimit": "358072",
            "data": "0xb35d7e73000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001c00000000000000000000000000000000000000000000000000000000000000009a9059cbb010001ffffffffffa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48095ea7b3010203ffffffffffa0b86991c6218b36c1d19d4a2e9eb0ce3606eb4870a082310104ffffffffff0298c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5ce8eda9df0105030406ffffff87870bca3f3fd6335c3f4ce8392d69350b4fa4e270a082310104ffffffffff0498c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5cb67d77c5010402ffffffff04ca99eaa38e8f37a168214a3a57c9a45a58563ed5a9059cbb010704ffffffffff98c23e9d8f34fefb1b7bd6a91b7ff122f4e16f5c6e7a43a3010408ffffffff047e7d64d987cab6eed08a191c4c2459daf2f8ed0b241c59120104ffffffffffff7e7d64d987cab6eed08a191c4c2459daf2f8ed0b00000000000000000000000000000000000000000000000000000000000000090000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000016000000000000000000000000000000000000000000000000000000000000001a000000000000000000000000000000000000000000000000000000000000001e00000000000000000000000000000000000000000000000000000000000000220000000000000000000000000000000000000000000000000000000000000026000000000000000000000000000000000000000000000000000000000000002a000000000000000000000000000000000000000000000000000000000000002e000000000000000000000000000000000000000000000000000000000000003200000000000000000000000000000000000000000000000000000000000000020000000000000000000000000129b480ad625bcd1a5c3a1c10d708114726fa467000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000186a0000000000000000000000000000000000000000000000000000000000000002000000000000000000000000087870bca3f3fd6335c3f4ce8392d69350b4fa4e200000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000005f45a6000000000000000000000000000000000000000000000000000000000000000200000000000000000000000007d585b0e27bbb3d981b7757115ec11f47c4769940000000000000000000000000000000000000000000000000000000000000020000000000000000000000000a0b86991c6218b36c1d19d4a2e9eb0ce3606eb480000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000009319b31838bba444cceaed025153a48ad637747100000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000005c69f58",
            "value": "0"
          }
        ],
...
```


# Actions, Networks, and Tokens supported

## Chains supported

**EVMs**:

* Ethereum&#x20;
* Base
* Optimism
* Arbitrum
* ZK Sync
* Polygon
* Blast
* Scroll
* Gnosis chain
* Taiko
* Binance Smart Chain
* Avalanche
* Mode
* Linea

Currently on the Brian App, only the EVM chains are supported.

**Non EVMs**:

* Starknet
* Solana

## Actions supported

Brian API supports the following actions:

* transfer
* swap
* bridge and cross-chain swap\*
* deposit°
* withdraw°
* borrow and repay (AAVE)
* ENS actions (registration, renewal, resolution, etc..)\*\*
* balance

***

\*the **bridge** action is currently not supported from/to Solana and Starknet

°the **deposit** and **withdraw** (from/to DeFi protocol) actions are only supported on:

* Ethereum mainnet
* Arbitrum
* Optimism
* Polygon
* Base
* Avalanche

Check [this page](/brian-api/apis/transaction/actions-networks-and-tokens-supported/deposit-and-withdraw-to-from-defi-protocols) to learn more.

\*\*the ENS-related actions are only supported on Ethereum mainnet, while any ENS subdomain (even L2 subdomains) resolution is supported both in the prompt and in the `address` body parameter.

***

## Solvers

For the swap, bridge, and cross-chain swap operations, Brian leverages the following solvers:

* [Enso](https://www.enso.finance/)&#x20;
* [Bungee](https://docs.bungee.exchange/)
* [LiFi](https://li.fi/)
* [Portals](https://build.portals.fi/)
* [Symbiosis](https://symbiosis.finance/)
* [Avnu.fi](https://www.avnu.fi/)
* [Jupiter](https://jup.ag/)

Offering best routes for swap, cross-swap, and bridge operations on different chains.&#x20;

***

## Tokens

The Brian-supported token list consists of internal token lists and external provider lists, such as:

* EVM tokens

{% embed url="<https://apidocs.li.fi/reference/get_v1-tokens>" %}

* Starknet tokens:

{% embed url="<https://doc.avnu.fi/avnu-spot/token-list/token-list-api>" %}

* Solana tokens:

{% embed url="<https://station.jup.ag/api-v6/get-tokens>" %}


# Deposit and Withdraw to/from DeFi protocols

For the deposit and withdraw operations, Brian leverages [Enso](https://www.enso.finance/) solver. We currently support the following protocols, tokens and chains:

* Ethereum mainnet
  * AAVE v3
  * Lido Finance
  * Frax Finance
  * Rocket Pool
  * Spark
  * Gearbox
  * Compound v2
* Arbitrum
  * AAVE v3
  * Compound v3
* Optimism
  * AAVE v3
  * Compound v3
* Polygon
  * AAVE v3
* Base
  * AAVE v3&#x20;
  * Compound v3
* Avalanche
  * AAVE v3

### Borrow and Repay from DeFi protocols (AAVE v3)

We currently support AAVE v3 for the borrow, repay, and check parameters (loan-to-value, health rate, liquidation threshold, borrowed amount, borrowable amount) on the following chains:

* Ethereum mainnet
* Arbitrum
* Optimism
* Base
* Polygon

AAVE is also supported for the deposit and withdraw actions as specified [above](#deposit-and-withdraw-to-from-defi-protocols).&#x20;


# Transactions flow

This page explains how to leverage the **Brian API/SDK** to prepare and execute blockchain transactions. The Brian API provides a flexible and agnostic approach to transaction handling, enabling developers to design workflows that best fit their application's architecture.

{% hint style="danger" %}
The Brian API and [ts SDK](/brian-sdk/brian-typescript-sdk) are meant to be used on the backend to not expose the Brian API key!
{% endhint %}

The transaction flow consists of two main steps:

1. **Transaction Request:** **Your application backend** interacts with the Brian API/SDK to generate one or more transaction objects. These objects include all necessary details, such as recipient addresses, values, calldata, and additional metadata for frontend/backend purposes.
2. **Transaction Execution:** Transactions can be executed in several ways, depending on your use case. The API is agnostic about execution, enabling flexibility:
   * **Backend Execution:** Your server signs and broadcasts the transaction using a wallet private key.
   * **Frontend Execution:** The transaction is sent to your frontend for user signing and execution through a wallet.
   * **Smart Contract Execution:** The transaction is forwarded to a smart contract call that handles execution.

***

## Example of Transaction Execution

The libraries and tools available for executing the transaction will depend on the type of chain you intend to use (EVM or Non-EVM, such as Solana/Starknet).&#x20;

In any case, the transactions returned by the Brian API are compatible with the most common development tools, such as Viem, Wagmi, Ethers for EVM chains, starknet.js, Starknet React for Starknet, and, Solana-Web3.js for Solana.

Examples:

* [EVM](/brian-api/apis/transaction/transactions-flow/evm)
* [Starknet](/brian-api/apis/transaction/transactions-flow/starknet)
* [Solana](/brian-api/apis/transaction/transactions-flow/solana)


# EVM

### Backend Execution (using Viem)

```typescript
  const walletClient = createWalletClient({
      chain: base,
      transport: http(),
  });

  const account = privateKeyToAccount(process.env.PRIVATE_KEY! as `0x${string}`);
  
  const brian = new BrianSDK(options);

  const request = await brian.transact({
    prompt: "swap 1 ETH for USDC on base",
    address: "vitalik.eth",
  });
  console.log("transaction result:", request);

  //Execute all the transactions in the steps array for each request returned
  for (const req of request) {
    for (const step of req.data.steps!) {
      const tx = await walletClient.sendTransaction({
        account: account,
        to: step.to,
        value: BigInt(step.value),
        data: step.data,
      });

      console.log(`Transaction for step ${step.chainId} sent:`, tx);
      await publicClient.waitForTransactionReceipt({ hash: tx }); // Wait for the transaction to be mined
      console.log(`Transaction for step ${step.chainId} confirmed.`);
    }
  }
}
```

### Frontend Execution (using Wagmi)

```typescript
// YOUR BACKEND


  ...
  const brianAPIUrl = "https://api.brianknows.org/api/v0/agent/transaction"
  const options = {
    method: 'POST',
    headers: {'Content-Type': 'application/json', 'X-Brian-Api-Key': 'your-api-key'},
    body: JSON.stringify({ // Convert the body object to a JSON string
    prompt: "I want to swap 10 MATIC to USDC on Polygon",
    address: "vitalik.eth"
    })
  };
  
  try {
    const response = await fetch(brianAPIUrl, options);
    const request = await response.json();
    console.log(request);
    // Respond with the transaction details
    res.status(200).json(request)
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: "Failed to create transaction" });
  }

  
```

```typescript
// YOUR FRONTEND  

// FRONTEND REACT TS

import { useWalletClient } from "wagmi";
import { useState } from "react";

export default function ExecuteTransaction() {
  const { data: walletClient } = useWalletClient();
  const [transactionResults, setTransactionResults] = useState<any[]>([]); // Store the array of transaction results
  const [loading, setLoading] = useState(false);

  // Function to fetch transaction details from the backend API
  const fetchTransactionDetails = async () => {
    setLoading(true);
    try {
      const response = await fetch("/api/create-transaction", { //your API
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          prompt: "swap 1 ETH for USDC on base",
          address: "vitalik.eth",
        }),
      });

      if (!response.ok) {
        throw new Error("Failed to fetch transaction details");
      }

      const data = await response.json();
      setTransactionResults(data); // Store the array of transaction results
      console.log("Fetched transaction details:", data);
    } catch (error) {
      console.error("Error fetching transaction details:", error);
    } finally {
      setLoading(false);
    }
  };

  // Function to execute all the transactions using Wagmi
  const handleTransaction = async () => {
    try {
      if (!walletClient) {
        console.error("Wallet client not found");
        return;
      }

      if (transactionResults.length === 0) {
        console.error("No transaction details available");
        return;
      }

      for (const result of transactionResults) {
        for (const step of result.data.steps) {
          const tx = await walletClient.sendTransaction({
            ...step, // Pass all required properties directly from the step
          });
          if (tx) {
            await publicClient?.waitForTransactionReceipt({
              hash: tx,
          })
          console.log(`Transaction for step ${step.chainId} confirmed.`);
        }
      }

      console.log("All transactions executed successfully.");
    } catch (error) {
      console.error("Error executing transactions:", error);
    }
  };

  return (
    <div>
      <button onClick={fetchTransactionDetails} disabled={loading}>
        {loading ? "Fetching..." : "Fetch Transaction Details"}
      </button>
      <button onClick={handleTransaction} disabled={transactionResults.length === 0}>
        Execute Transactions
      </button>
    </div>
  );
}
```


# Solana

The transactions returned by the Brian API are compatible with the most common development tools, such as Solana-Web3.js.

The transaction contained in the API response is a **serialized** transaction. The steps to be taken are:

1. deserialize and sign the transaction
2. execute the transaction

{% hint style="success" %}
The transaction returned in the API response follows the same format as the response from the **Jupiter API**. The deserialization, signing, and execution process are the same. \
👉 Check [here for more info](https://station.jup.ag/docs/apis/swap-api#6-deserialize-and-sign-the-transaction).
{% endhint %}

#### Deserialize, sign and execute the transaction(s)

Access the transaction object from the Brian API response (using the Brian ts SDK):

```typescript

const brian = new BrianSDK(options);

const request = await brian.transact({
  prompt: "swap 1 sol for USDC on solana",
  address: "53unSgGWqEWANcPYRF35B2Bgf8BkszUtcccKiXwGGLyr",
});
console.log("transaction result:", request);

// Create an empty array to store transactions
const txArray = [];

// Loop through the requests and their steps
for (const req of request) {
  for (const step of req.data.steps) {
    // Push the step's data into the txArray
    txArray.push(step.data);
  }
}

console.log("Transaction Array:", txArray);

```

Now, you can deserialize, sign, and execute the transaction(s)

```typescript
// Get the latest blockhash before processing transactions
  const latestBlockHash = await connection.getLatestBlockhash();

  // Loop through each transaction data in txArray
  for (const txData of txArray) {
    try {
      // Deserialize the transaction
      const swapTransactionBuf = Buffer.from(txData, "base64");
      const transaction = VersionedTransaction.deserialize(swapTransactionBuf);
      console.log("Deserialized transaction:", transaction);

      // Sign the transaction
      transaction.sign([wallet.payer]); // Ensure wallet.payer is a valid Keypair or signer
      console.log("Signed transaction:", transaction);

      // Execute the transaction
      const rawTransaction = transaction.serialize();
      const txid = await connection.sendRawTransaction(rawTransaction, {
        skipPreflight: true,
        maxRetries: 2,
      });
      await connection.confirmTransaction({
        blockhash: latestBlockHash.blockhash,
        lastValidBlockHeight: latestBlockHash.lastValidBlockHeight,
        signature: txid,
      });

      console.log(`Transaction successful: https://solscan.io/tx/${txid}`);
    } catch (error) {
      console.error("Error processing transaction:", error);
    }
  }
} catch (error) {
  console.error("Error during request or transaction:", error);
}
```


# Starknet

Examples c*oming soon.*

The transactions returned by the Brian API are compatible with the most common development tools, such as  starknet.js or Starknet React.


# /knowledge

{% hint style="success" %}
\*Check the [Knowledge Boxes](/brian-api/apis/knowledge/knowledge-boxes) page to find out about the various KBs you can use or create your own customized one.
{% endhint %}

## Ask a question to Brian

<mark style="color:green;">`POST`</mark> `https://api.brianknows.org/api/v0/agent/knowledge`

Allows you to send a prompt to Brian and receive a textual response along with the resources used to.

#### Headers

| Name                                              | Type             | Description        |
| ------------------------------------------------- | ---------------- | ------------------ |
| x-brian-api-key<mark style="color:red;">\*</mark> | String           | Brian API key.     |
| Content-Type<mark style="color:red;">\*</mark>    | application/json | Body content type. |

#### Request Body

| Name                                     | Type   | Description                                         |
| ---------------------------------------- | ------ | --------------------------------------------------- |
| prompt<mark style="color:red;">\*</mark> | String | Prompt used to generate the response.               |
| kb\*                                     | String | Knowledge box where you want to search information. |

{% tabs %}
{% tab title="200: OK OK." %}
{% code title="Response" overflow="wrap" fullWidth="true" %}

```json
{
  "result": {
    "input": "what is uniswap",
    "chat_history": [],
    "context": [
      {
        "pageContent": "...",
        "metadata": {
          "description": "...",
          "language": "...",
          "source": "...",
          "title": "..."
        }
      },
      ...
    ],
    "answer": "..."
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}

#### Requesting information

{% code overflow="wrap" %}

```bash
curl -XPOST "https://api.brianknows.org/api/v0/agent/knowledge" -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY" -d '{"prompt": "What is Uniswap?"}'
```

{% endcode %}

```json
{
  "result": {
    "input": "what is uniswap",
    "chat_history": [],
    "context": [
      {
        "pageContent": "Overview | Uniswap",
        "metadata": {
          "description": "Code",
          "language": "en",
          "source": "https://docs.uniswap.org/concepts/governance/overview",
          "title": "Overview | Uniswap"
        }
      },
      {
        "pageContent": "Glossary | Uniswap",
        "metadata": {
          "description": "Automated Market Maker",
          "language": "en",
          "source": "https://docs.uniswap.org/concepts/glossary",
          "title": "Glossary | Uniswap"
        }
      },
      {
        "pageContent": "Glossary | Uniswap",
        "metadata": {
          "description": "- UNI: An ERC-20 token that designates the weight of a user&#39;s voting rights. The more UNI a user has in their wallet, the more weight their delegation or vote on a proposal holds.",
          "language": "en",
          "source": "https://docs.uniswap.org/concepts/governance/glossary",
          "title": "Glossary | Uniswap"
        }
      },
      {
        "pageContent": "The Uniswap Protocol | Uniswap",
        "metadata": {
          "description": "Introduction",
          "language": "en",
          "source": "https://docs.uniswap.org/concepts/uniswap-protocol",
          "title": "The Uniswap Protocol | Uniswap"
        }
      }
    ],
    "answer": "Uniswap is a decentralized exchange (DEX) protocol built on the Ethereum blockchain that allows users to trade various ERC-20 tokens directly from their wallets without the need for an intermediary. It uses an automated market-making (AMM) model rather than a traditional order book, which facilitates liquidity provision and trading.\n\n\"\n\n### Key Features of Uniswap\n\n1. **Automated Market Making**:\n   - Uniswap employs liquidity pools instead of order books. Users can trade tokens by simply interacting with these pools, where prices are determined algorithmically based on the quantity of tokens in each pool.\n\n2. **Liquidity Pools**:\n   - Anyone can provide liquidity to Uniswap by depositing a pair of tokens into a pool. In return, liquidity providers earn a share of the trading fees generated by that pool, proportional to their contribution.\n\n3. **Smart Contracts**:\n   - All operations on Uniswap are handled by smart contracts on the Ethereum blockchain. This ensures that transactions are trustless and automated, making the process transparent and secure.\n\n4. **Permissionless and Composability**:\n   - Uniswap is permissionless, allowing anyone to create trading pairs and participate in the liquidity pools. Additionally, the protocol can integrate with other DeFi applications, enhancing its functionality and reach.\n\n5. **Token Swaps**:\n   - Users can swap one ERC-20 token for another seamlessly, with the protocol automatically calculating the optimal exchange rate based on the current liquidity in the pools.\n\n\"\n\n### Technical Architecture\n\n- Uniswap operates based on a mathematical formula known as the constant product formula (x * y = k). Here, x and y represent the quantities of two tokens in the pool, and k is a constant. This model ensures that the product of the quantities of the tokens remains unchanged during swaps.\n\n- Each liquidity pool holds reserves of two tokens and allows for trades between these tokens. The protocol dynamically adjusts the price through the reserves, reflecting supply and demand in real time.\n\n- Users can interact with Uniswap through its interface or programmatically using the [Uniswap SDK](https://uniswap.org/docs/v2/SDK/introduction/) or [Uniswap's smart contracts](https://github.com/Uniswap/uniswap-v2-core).\n\n\"\n\n### Governance\n\nUniswap operates under a decentralized governance model, where UNI token holders can propose and vote on changes to the protocol. This empowers the community to influence the future development and direction of Uniswap, ensuring it evolves in alignment with user interests.\n\n\"\n\n### Conclusion\n\nIn summary, Uniswap has revolutionized the way decentralized finance operates by providing a robust, user-friendly platform for token swapping and liquidity provisioning. Its AMM model stands out as an innovative approach to trading on the Ethereum blockchain, fostering growth and development in the DeFi sector.\n\nFor a deeper understanding, you can refer to [The Uniswap Protocol](https://uniswap.org/docs/v2/) and [Uniswap's Glossary](https://uniswap.org/docs/v2/glossary/)."
  }
}e
```


# Knowledge Boxes

The `/knowledge` API is designed to support Retrieval-Augmented Generation (RAG) across various knowledge bases. Want to read more about how Brian RAG works? Read this [article](https://medium.com/@BrianknowsAI/askbrian-rag-42d17fd91148).

If not specified, the KB used is the default one called `public-knowledge-box`.\
\
The public knowledge base has a good overview of the entire Web3 space, especially for the EVM ecosystem. We can, at any time, add new articles, videos or documentation of new protocols and blockchains.

## Available KBs

Other available KBs are:

* circle\_kb
* lido\_kb
* Polygon\_kb
* taiko\_kb
* near\_kb
* clave\_kb
* starknet\_kb
* consensys\_kb

## Create your KB

{% hint style="info" %}
Right now don't hesitate to get in touch with us ([info@brianknows.org](mail:info@brianknows.org) or [Brian on X](https://x.com/BrianknowsAI)) to create your knowledge box. We are working on a web app to facilitate the creation and management of KBs!
{% endhint %}


# Public Embeddings

Download and use the Brian public knowledge embeddings.

Public embeddings play a significant role in various fields and applications, and these are the reasons why we wanted to create such repository:

* **Knowledge Sharing**: Public embeddings facilitate the sharing of knowledge and information in a structured and computationally efficient way. They encode semantic information, making it easier to understand and utilize data across different applications;
* **Interoperability**: Public embeddings provide a common framework for interoperability among diverse systems, platforms, and languages. They enable data and models to be understood and used consistently across the AI and machine learning community;
* **Facilitating Research**: Researchers in natural language processing (NLP), computer vision, and other AI domains heavily rely on pre-trained embeddings. A repository of public embeddings can serve as a valuable resource for researchers to access and compare different embeddings for their experiments and models;
* **Reducing Redundancy**: Instead of reinventing the wheel and training embeddings from scratch, developers and researchers can use publicly available embeddings as a starting point. This reduces redundancy, saves computational resources, and accelerates the development of AI applications;
* **Enhancing Accessibility**: By making public embeddings readily accessible, the repository can democratize AI and make advanced technologies available to a wider audience. This inclusivity can foster innovation and creativity in various domains;
* **Open Data and Transparency**: Hosting public embeddings in a centralized repository promotes transparency and openness in AI research and development. It allows for scrutiny and peer review, fostering trust in the AI community;
* **Cross-Domain Applications**: Public embeddings are versatile and can be used across different domains and applications, from text analysis and recommendation systems to image recognition and sentiment analysis. This versatility enhances their value;
* **Community Collaboration**: A repository for public embeddings encourages collaboration within the AI community. Developers, researchers, and practitioners can contribute their embeddings, share their knowledge, and collectively improve the quality of available embeddings;
* **Education and Learning**: Public embeddings can be a valuable resource for educational purposes. Students, educators, and AI enthusiasts can access these embeddings to learn and experiment with AI techniques without the need for extensive computational resources.

Storing and retrieving public embeddings on [**Swarm**](https://www.ethswarm.org/) serves as a catalyst for advancing AI research, fostering collaboration, and making AI more accessible and transparent. It plays a pivotal role in the development of AI technologies with far-reaching implications across various industries and domains.

### Embeddings table

Here's a table containing the Swarm reference, when the embeddings were uploaded and their current size. You can download them using the [Swarm Gateway](https://gateway.ethswarm.org/), or any client of your choice. You can expect this table to be updated every month.

| Reference                                                                                                                                                                    | Date              | Size    |
| ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------- | ------- |
| [**abdb324d4e37a18220d7d3408c2dc281faf59c88df2bc81b0a9be1ea471aee14**](https://gateway.ethswarm.org/access/abdb324d4e37a18220d7d3408c2dc281faf59c88df2bc81b0a9be1ea471aee14) | 18th of May 2024  | 61.2 MB |
| [**18e950a2b50c5a01b988c343d8449cbb080ec5b93f2493a18569bb8e2984b6cf**](https://gateway.ethswarm.org/access/18e950a2b50c5a01b988c343d8449cbb080ec5b93f2493a18569bb8e2984b6cf) | 18th of June 2024 | 67.7 MB |
| [**c5c9229c0affcdb83d47b51475396e80429f3434f20932117ee5f76ea94eef2b**](https://gateway.ethswarm.org/access/c5c9229c0affcdb83d47b51475396e80429f3434f20932117ee5f76ea94eef2b) | 17th of July 2024 | 67.7 MB |


# /agent

The `/agent` endpoint is a new feature of the Brian API designed to build chat-like apps or integrate chat features within existing apps.

The `/agent` endpoint has the capabilities of `/transaction` and `/knowledge`, which means that you can ask for both transactions (`/transaction`) and web3 info (`/knowledge`).

{% hint style="success" %}
Have a look at [/transation](/brian-api/apis/transaction/transactions-flow) to understand the transaction flow from prompt request to execution.
{% endhint %}

## Understanding `/agent`&#x20;

The existing [`/transaction`](https://docs.brianknows.org/brian-api/apis/transaction) and [`/knowledge`](https://docs.brianknows.org/brian-api/apis/knowledge) endpoints allow users to send a single prompt and get a response (either a transaction or textual information). However, these endpoints do not maintain chat history context — each prompt is handled independently, without awareness of previous requests.

The new `/agent` endpoint introduces session-based context, allowing developers to maintain a conversation history between the user and Brian within the same session. This means that previous messages and responses generated by Brian can be "remembered", for more dynamic and powerful interactions.

### Why message history matters

Being able to have a message history significantly improves the capabilities of the Brian API by combining the functionalities of `/transaction` and `/knowledge`. With this, developers can build more powerful chat-like use cases, such as:

* user: “i want to swap 100 usdc on Base”
* brian: “ok, what is the token to buy for the swap operation?”
* user: “eth”
* brian: generates the executable transaction for swapping 100 usdc to eth on base

or:

* user: “when vitalik.eth expires on ethereum?”
* brian: “october 20 2040…”
* user: “got it, renew it for another 4 years on ethereum”
* brian: generates the executable transaction for renewing vitalik.eth for 4 years on ethereum

or users can ask both questions and transactions using the same `/agent` endpoint:

* user: “what is uniswap v4 hooks?”
* brian: “uniswap v4 is ……..”
* user: “ok now bridge 1 eth from arbitrum to zk sync”
* brian: generates the executable transaction for bridging 1 eth from arbitrum to zk sync

### How `/agent` works

<mark style="color:green;">`POST`</mark> `https://api.brianknows.org/api/v0/agent`

Allows you to send a chat history to Brian.

The currently available actions are those supported by [`/transaction`](/brian-api/apis/transaction) and [`/knowledge`](/brian-api/apis/knowledge).

**Headers**

| Name              | Type             | Description        |
| ----------------- | ---------------- | ------------------ |
| x-brian-api-key\* | String           | Brian API key.     |
| Content-Type\*    | application/json | Body content type. |

**Request Body**

| Name      | Type            | Description                                                                                           |
| --------- | --------------- | ----------------------------------------------------------------------------------------------------- |
| prompt\*  | String          | User input prompt.                                                                                    |
| address\* | String          | Address that will send the transactions.                                                              |
| chainId   | String          | Chain ID of the user. Can be specified here or in the messages parameter.                             |
| messages  | array object\[] | messages exchanged between the user and Brian (conversation history). It represents the chat history. |

*\*mandatory parameters*

{% hint style="success" %}
If you don't pass the `chainId` in the body, the source chain will be deducted from the chat history, if available. Otherwise, it will throw an error.
{% endhint %}

**Request Example**

```jsx
fetch('<https://api.brianknows.org/api/v0/agent>', {
  method: 'POST',
  headers: {
    'X-Brian-Api-Key': 'API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: 'ethereum',
    address: 'vitalik.eth',
    messages: [
      {
        sender: 'user',
        content: 'when vitalik.eth expires?'
      },
      {
        sender: 'brian',
        content: 'The ENS domain vitalik.eth.eth (0xd8dA...6045) expiration is Thu Nov 29 2040 08:36:18 GMT+0100 (Central European Standard Time).'
      },
      {
        sender: 'user',
        content: 'ok, renew it'
      },
      {
        sender: 'brian',
        content: 'What is the chain you would like to perform this operation on?'
      }
    ]
  })
})
```

**Response example**

```json
{
  "result": [
    {
      "solver": "Brian",
      "action": "ENS Renewal",
      "type": "write",
      "data": {
        "description": "You are about to renew the ENS domain \\"vitalik.eth\\" for 12 months. The ENS \\"vitalik.eth\\" renewal cost for 12 months is 0.0021 ETH ($5.006591677699126).",
        "steps": [
          {
            "chainId": 1,
            "blockNumber": 20734848,
            "from": "0x1358155a15930f89eBc787a34Eb4ccfd9720bC62",
            "to": "0x253553366Da8546fC250F225fe3d25d0C782303b",
            "value": "2347997171390886",
            "data": "0xacf1a84100000000000000000000000000000000000000000000000000000000000000400000000000000000000000000000000000000000000000000000000001e133800000000000000000000000000000000000000000000000000000000000000007766974616c696b00000000000000000000000000000000000000000000000000",
            "gasLimit": "200000"
          }
        ],
        "fromChainId": 1,
        "fromAmount": "2347997171390886",
        "fromToken": {
          "address": "0x0000000000000000000000000000000000000000",
          "chainId": 1,
          "symbol": "ETH",
          "decimals": 18,
          "name": "ETH",
          "coinKey": "ETH",
          "logoURI": "<https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2/logo.png>",
          "priceUSD": "2345.51"
        },
        "fromAddress": "0x1358155a15930f89eBc787a34Eb4ccfd9720bC62",
        "toChainId": 1,
        "finalEnsPriceString": "2347997171390886",
        "toAmountMin": "2347997171390886",
        "toToken": {
          "address": "0x0000000000000000000000000000000000000000",
          "chainId": 1,
          "symbol": "ETH",
          "decimals": 18,
          "name": "ETH",
          "coinKey": "ETH",
          "logoURI": "<https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2/logo.png>",
          "priceUSD": "2345.51"
        },
        "toAddress": "0x253553366Da8546fC250F225fe3d25d0C782303b"
      }
      "extractedParams": {
        "action": "ensrenewal",
        "address": "vitalik.eth",
        "duration": "365",
        "chain": "ethereum"
      },
      "conversationHistory": [
        {
          "sender": "user",
          "content": "when vitalik.eth expires?"
        },
        {
          "sender": "brian",
          "content": "The ENS domain vitalik.eth.eth (0xd8dA...6045) expiration is Thu Nov 29 2040 08:36:18 GMT+0100 (Central European Standard Time)."
        },
        {
          "sender": "user",
          "content": "ok, renew it"
        },
        {
          "sender": "brian",
          "content": "What is the chain you would like to perform this operation on?"
        },
        {
          "sender": "user",
          "content": "ethereum"
        },
        {
          "sender": "brian",
          "content": "You are about to renew the ENS domain \"vitalik.eth\" for 12 months. The ENS \"vitalik.eth\" renewal cost for 12 months is 0.0020 ETH ($5.010546811623313)."
        }
      ]
    }
  ]
}
```

## Integrating /agent

**Body request**

As shown in the example above, the `body` parameters are:

* `prompt`: the last user prompt request.
* `address`: the address (EOA/smart contract) requesting a transaction.
* `chainId`: optional chainId. If you don't provide it, the source chain will be deducted from the chat history, if available.
* `messages`: chat history between the user and Brian.

**Handle body requests in the session**

* First message of the session: In the first request, the `prompt` field should be populated with the user's input, while the `messages[]` array should be empty. This marks the beginning of the session, so there are no prior messages to include.

Example of how the session request should be built on the first message:

```json
{
  "prompt": "I want to swap 100 USDC on Base",
  "address": "0xYourAddressOrEns",
  "messages": []
}

```

* Subsequent messages in the session: From the second message onwards, the `messages[]` array should contain the conversation history between the user and Brian. In these cases, the `prompt` field will hold the new user request, while `messages[]` will include the previous exchanges between Brian and the user.

Example of how the session request should be built from the second message onwards:

```json
{
  "prompt": "ETH",
  "address": "0xYourAddressOrEns",
  "messages": [
    {
      "sender": "user",
      "content": "I want to swap 100 USDC on Base"
    },
    {
      "sender": "brian",
      "content": "OK, what is the token for the swap operation?"
    }
  ]
}

```

**Storing messages**

When integrating the `/agent` endpoint, developers have the flexibility to decide how to store the conversation history (`messages[]`) of a user session. Possible approaches include:

* In-memory storage: Store the messages in temporary memory (e.g., a JavaScript array) and reset them when the session ends.
* Database storage: Store messages in a database for long-term persistence and reset them when the session ends.
* Key-value storage: Store messages in a key-value store (eg. Redis), which can handle quick access to active sessions and reset them when the session ends.
* Other solutions: for example, when integrating `/agent` within an XMTP bot (try `brian-agent.eth` on Converse client), the messages are already stored as part of the XMTP chat history. In such a scenario, there's no need for additional storage, as the XMTP SDK can retrieve the messages at runtime.

{% hint style="success" %}
For the moment, we suggest to often clean the message history sent to the API for better performance or at least after a couple of sucesfull response from the API.&#x20;
{% endhint %}

### Step-by-step procedure on how to create body requests during the session

This paragraph explains step-by-step how to construct body requests for API calls to `/agent` during a chat session from a developer's point of view.&#x20;

It is fundamental to understand that the `/agent` endpoint returns:

* `200`: only when a transaction or info request can be generated from the prompt + messages (chat history).
* `400`: when a transaction or info request cannot be generated from the prompt + messages because certain parameters are missing. Consequently, the developer during the session must take the error message returned by Brian and add it to the `messages` array parameters for the next request

Let's make an example:

1\) User writes "swap 100 usdc".&#x20;

The request should be:

```typescript
fetch('<https://api.brianknows.org/api/v0/agent>', {
  method: 'POST',
  headers: {
    'X-Brian-Api-Key': 'API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: 'swap 100 usdc',
    address: 'limone.eth',
    messages: []
  })
})
```

The `/agent` response is a 400 with the following error:

{% tabs %}
{% tab title="400: Missing parameters" %}

```json
{
  "error": "Hey there! I see you're looking to make a swap. Could you let me know which token you'd like to buy? That way, I can help you out better. Thanks!",
  "extractedParams": [
    {
      "action": "swap",
      "chain": "",
      "token1": "usdc",
      "token2": "",
      "address": "",
      "amount": "100"
    }
  ],
  "conversationHistory": [
    {
      "sender": "user",
      "content": "swap 100 usdc"
    }
  ]
}
```

{% endtab %}
{% endtabs %}

2\) The user writes "to ETH".

The request should contain the new prompt along with the previous error message:

```typescript
fetch('<https://api.brianknows.org/api/v0/agent>', {
  method: 'POST',
  headers: {
    'X-Brian-Api-Key': 'API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: 'to ETH',
    address: 'limone.eth',
    messages: [
    {
      "sender": "user",
      "content": "I want to swap 100 usdc"
    },
    {
      "sender": "brian",
      "content": "Hey there! I see you're looking to make a swap. Could you let me know which token you'd like to buy? That way, I can help you out better. Thanks!"
    }
    ]
  })
})
```

The `/agent` response is a 400 with the following error:

{% tabs %}
{% tab title="400" %}

```json
{
  "error": "What is the chain you would like to perform this operation on?",
  "extractedParams": [
    {
      "action": "swap",
      "chain": "",
      "token1": "usdc",
      "token2": "eth",
      "address": "",
      "amount": "100"
    }
  ],
  "conversationHistory": [
    {
      "sender": "user",
      "content": "I want to swap 100 usdc"
    },
    {
      "sender": "brian",
      "content": "Hey there! I see you're looking to make a swap. Could you let me know which token you'd like to buy? That way, I can help you out better. Thanks!"
    },
    {
      "sender": "user",
      "content": "to ETH"
    },
    {
      "sender": "brian",
      "content": "What is the chain you would like to perform this operation on?"
    }
  ]
}
```

{% endtab %}
{% endtabs %}

3\) The user writes "on Base".

The request should contain the new prompt along with the previous error messages:

```typescript
fetch('<https://api.brianknows.org/api/v0/agent>', {
  method: 'POST',
  headers: {
    'X-Brian-Api-Key': 'API_KEY',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    prompt: 'on Base',
    address: 'limone.eth',
    messages: [
    {
      "sender": "user",
      "content": "I want to swap 100 usdc"
    },
    {
      "sender": "brian",
      "content": "Hey there! I see you're looking to make a swap. Could you let me know which token you'd like to buy? That way, I can help you out better. Thanks!"
    },
    {
      "sender": "user",
      "content": "to ETH"
    },
    {
      "sender": "brian",
      "content": "What is the chain you would like to perform this operation on?"
    }
    ]
  })
})
```

At this point, the `/agent` response is a 200 providing the requested swap transaction:

{% tabs %}
{% tab title="200" %}

```json
{
  "result": [
    {
      "solver": "Enso",
      "action": "swap",
      "type": "write",
      "data": {
        "description": "You are about to swap 100.0 USDC ($100.1) for 0.040 ETH ($99.9) on Base using Enso solver. The address receiver is 0x1358155a15930f89eBc787a34Eb4ccfd9720bC62.",
        "steps": [
          {
            "chainId": 8453,
            "blockNumber": 21625399,
            "from": "0x1358155a15930f89eBc787a34Eb4ccfd9720bC62",
            "to": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
            "gasLimit": "80000",
            "data": "0x095ea7b300000000000000000000000080eba3855878739f4710233a8a19d89bdd2ffb8e0000000000000000000000000000000000000000000000000000000005f5e100",
            "value": "0"
          },
          {
            "chainId": 8453,
            "blockNumber": 21625399,
            "from": "0x1358155a15930f89eBc787a34Eb4ccfd9720bC62",
            "to": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
            "gasLimit": "345347",
            "data": "0xb35d7e73000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda029130000000000000000000000000000000000000000000000000000000005f5e100000000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000001a00000000000000000000000000000000000000000000000000000000000000008a9059cbb010001ffffffffff833589fcd6edb6e08f4c7c32d4f71b54bda02913095ea7b3010203ffffffffff833589fcd6edb6e08f4c7c32d4f71b54bda0291319198595a30485ffffffff85111111125421ca6dc452d289314280a0f8842a659bd3b227018504ffffffff056675a323dedb77822fcf39eaa9d682f6abe72555ddcd52200105ffffffffff057e7d64d987cab6eed08a191c4c2459daf2f8ed0b19198595a30586ffffffffff1358155a15930f89ebc787a34eb4ccfd9720bc626e7a43a3010507ffffffff057e7d64d987cab6eed08a191c4c2459daf2f8ed0b241c59120105ffffffffffff7e7d64d987cab6eed08a191c4c2459daf2f8ed0b000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000001c000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000240000000000000000000000000000000000000000000000000000000000000084000000000000000000000000000000000000000000000000000000000000008600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000129b480ad625bcd1a5c3a1c10d708114726fa467000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000186a00000000000000000000000000000000000000000000000000000000000000020000000000000000000000000111111125421ca6dc452d289314280a0f8842a6500000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000000000005f45a600000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005c807ed2379000000000000000000000000e37e799d5077682fa0a244d46e5649f71457bd09000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda02913000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000e37e799d5077682fa0a244d46e5649f71457bd090000000000000000000000007d585b0e27bbb3d981b7757115ec11f47c4769940000000000000000000000000000000000000000000000000000000005f45a60000000000000000000000000000000000000000000000000008a43f6539a353e00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000120000000000000000000000000000000000000000000000000000000000000046e00000000000000000000000000000000000000000000045000043a0003f0512003c01acae3d0173a93d819efdc832c7c4f153b06833589fcd6edb6e08f4c7c32d4f71b54bda02913016452bbbe2900000000000000000000000000000000000000000000000000000000000000e0000000000000000000000000e37e799d5077682fa0a244d46e5649f71457bd090000000000000000000000000000000000000000000000000000000000000000000000000000000000000000e37e799d5077682fa0a244d46e5649f71457bd090000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000671e517cdef66c6c178087fd931514e99b04479e4d3d956c0002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda0291300000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000005f45a6000000000000000000000000000000000000000000000000000000000000000c0000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000625745d692b2400000000000000000000000000000000000000000000000000000000671e517c00000000000000000000000000000000000000000000000000000000000000e00000000000000000000000007d585b0e27bbb3d981b7757115ec11f47c47699400000000000000000000000000000000000000000000000000005af3107a40000000000000000086fb9011e2ff8b85700000000000000005784141ea082380000000000000001fa72a814595da483000000000000000000281967d8eade9f05f00000000000000000000000000000000000000000004a963b280a64b330bc48200000000000000004563918244f400000000000000000000006a94d74f430000000000000000000000000000671e51540000000000000000000044364c5bb000000000000000000000000000000000000000000000000000000000000000004128a9125558dbd81d9a74af9f04d915a7505757a7263f5f0f0ad350c2c24b117b612244009379d2ab449a8dd5bb815320719455db5b19a04408aae5bc0599534a1b0000000000000000000000000000000000000000000000000000000000000000a0f2fa6b66eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000000723184cdcc4fbc061111111125421ca6dc452d289314280a0f8842a6500000000000000000000000000000000000097864b9100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000000000000000000000000000008a3f4713a61b82",
            "value": "0"
          }
        ],
        "gasCostUSD": "",
        "fromChainId": 8453,
        "fromAmountUSD": "100.1201441730076",
        "fromAmount": "100000000",
        "fromToken": {
          "address": "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
          "chainId": 8453,
          "symbol": "USDC",
          "decimals": 6,
          "name": "USD Coin",
          "coinKey": "USDC",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png",
          "priceUSD": "1.001201441730076"
        },
        "fromAddress": "0x1358155a15930f89eBc787a34Eb4ccfd9720bC62",
        "toChainId": 8453,
        "toAmountUSD": "99.85106923258168",
        "toAmount": "40116619887578922",
        "toAmountMin": "40116619887578922",
        "toToken": {
          "address": "0x0000000000000000000000000000000000000000",
          "chainId": 8453,
          "symbol": "ETH",
          "decimals": 18,
          "name": "ETH",
          "coinKey": "ETH",
          "logoURI": "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2/logo.png",
          "priceUSD": "2489.02"
        },
        "toAddress": "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
        "receiver": "0x1358155a15930f89eBc787a34Eb4ccfd9720bC62",
        "protocol": {
          "key": "enso",
          "name": "enso",
          "logoURI": ""
        }
      },
      "extractedParams": {
        "action": "swap",
        "chain": "Base",
        "token1": "usdc",
        "token2": "eth",
        "address": "",
        "amount": "100"
      },
      "conversationHistory": [
        {
          "sender": "user",
          "content": "I want to swap 100 usdc"
        },
        {
          "sender": "brian",
          "content": "Hey there! I see you're looking to make a swap. Could you let me know which token you'd like to buy? That way, I can help you out better. Thanks!"
        },
        {
          "sender": "user",
          "content": "to ETH"
        },
        {
          "sender": "brian",
          "content": "What is the chain you would like to perform this operation on?"
        },
        {
          "sender": "user",
          "content": "on Base"
        },
        {
          "sender": "brian",
          "content": "You are about to swap 100.0 USDC ($100.1) for 0.040 ETH ($99.9) on Base using Enso solver. The address receiver is 0x1358155a15930f89eBc787a34Eb4ccfd9720bC62."
        }
      ]
    }
  ]
}
```

{% endtab %}
{% endtabs %}


# /parameters-extraction

## Extract parameters from a prompt.

<mark style="color:green;">`POST`</mark> `https://api.brianknows.org/api/v0/agent/parameters-extraction`

Allows you to send a prompt to Brian and return all the extracted parameters from the prompt.

You can implement your own custom logic and decide how to use the extracted parameters in you app. For example, you could take the swap parameters and build an integration on a chain that is not currently supported by Brian.

#### Headers

| Name                                              | Type             | Description        |
| ------------------------------------------------- | ---------------- | ------------------ |
| x-brian-api-key<mark style="color:red;">\*</mark> | String           | Brian API key.     |
| Content-Type<mark style="color:red;">\*</mark>    | application/json | Body content type. |

#### Request Body

| Name                                     | Type   | Description        |
| ---------------------------------------- | ------ | ------------------ |
| prompt<mark style="color:red;">\*</mark> | String | User input prompt. |

#### Requesting information

{% code overflow="wrap" %}

```bash
curl -XPOST "https://api.brianknows.org/api/v0/agent/parameters-extraction" -H "Content-Type: application/json" -H "x-brian-api-key: API_KEY" -d '{"prompt": "swap 1 eth to usdc on arbitrum"}'
```

{% endcode %}

{% tabs %}
{% tab title="200: OK OK." %}
{% code title="Response" overflow="wrap" fullWidth="true" %}

```json
{
  "result": {
    "prompt": "swap 1 eth to usdc on arbitrum",
    "completion": [
      {
        "action": "swap",
        "token1": "eth",
        "chain": "usdc",
        "amount": "1".
        ... // other parameters
      }
    ]
  }
}
```

{% endcode %}
{% endtab %}
{% endtabs %}


# /smart-contract (alpha)

## Generate solidity code from a prompt.

<mark style="color:green;">`POST`</mark> `https://api.brianknows.org/api/v0/agent/smart-contract`

Allows you to send a prompt to Brian and generate a Solidity Smart Contract. The code is encapsulated in a markdown code tag. You can also request the ABI and bytecode of the compiled smart contract in the same API call.

#### Headers

| Name                                              | Type             | Description        |
| ------------------------------------------------- | ---------------- | ------------------ |
| x-brian-api-key<mark style="color:red;">\*</mark> | String           | Brian API key.     |
| Content-Type<mark style="color:red;">\*</mark>    | application/json | Body content type. |

#### Request Body

<table><thead><tr><th width="205">Name</th><th>Type</th><th>Description</th></tr></thead><tbody><tr><td>prompt<mark style="color:red;">*</mark></td><td>String</td><td>User input prompt.</td></tr><tr><td>compile</td><td>Boolean</td><td>If true, it compiles the contract and returns the ABI and bytecode</td></tr><tr><td>messages</td><td>array object[]</td><td>messages exchanged between the user and Brian (conversation history).</td></tr></tbody></table>

#### Requesting information

{% code overflow="wrap" %}

```bash
curl https://api.brianknows.org/api/v0/agent/smart-contract \
  --request POST \
  --header 'Content-Type: application/json' \
  --header 'X-Brian-Api-Key: ' \
  --data '{
  "prompt": "",
  "compile": true,
}'
```

{% endcode %}

{% tabs %}
{% tab title="200: OK OK." %}
{% code title="Response" overflow="wrap" fullWidth="true" %}

````json

{
  "result": "```solidity\nCODE_HERE```",
  "abi": "abi_here",
  "bytecode": "bytecode_here"
}
````

{% endcode %}
{% endtab %}
{% endtabs %}


# /networks

## Get the list of supported networks

<mark style="color:green;">`GET`</mark> `https://api.brianknows.org/api/v0/utils/networks`

Returns the networks supported by Brian.

**Headers**

| Name         | Value              |
| ------------ | ------------------ |
| Content-Type | `application/json` |

**Body**

The body is empty.

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "result": [
    {
      "id": 1,
      "name": "Ethereum",
      "nativeCurrency": {
        "name": "Ether",
        "symbol": "ETH",
        "decimals": 18
      }
    },
    ...
  ]
}
```

{% endtab %}
{% endtabs %}


# /actions

## Get the list of supported actions

<mark style="color:green;">`GET`</mark> `https://api.brianknows.org/api/v0/utils/actions`

Returns all the actions supported by Brian with the related parameters and descriptions.

**Headers**

| Name         | Value              |
| ------------ | ------------------ |
| Content-Type | `application/json` |

**Body**

The body is empty.

**Response**

{% tabs %}
{% tab title="200" %}

```json
{
  "result": [
    {
      "name": "transfer",
      "description": "Movement of digital assets from one account to another within the blockchain network.",
      "parameters": [
        {
          "name": "receiver",
          "type": "string",
          "description": "The recipient address",
          "mandatory": true
        },
        {
          "name": "token1",
          "type": "string",
          "description": "The token to transfer",
          "mandatory": true
        },
        {
          "name": "amount",
          "type": "string",
          "description": "The amount of tokens to transfer",
          "mandatory": true
        },
        {
          "name": "chain",
          "type": "string",
          "description": "The blockchain network to use",
          "mandatory": false
        }
      ]
    },
    .....
    ]
```

{% endtab %}
{% endtabs %}


# What's New?

Here you can find updates among Brian's new updates. Follow [BrianknowsAI ](https://twitter.com/BrianknowsAI)on X to stay always updated!

## 📣 Update #6 - December 2024

New **API** release including the following updates:

### `/transaction`

* add Solana as a supported chain (swap, transfer and balance actions are currently available)
  * Integrated Jupiter solver for Solana swaps
* general bug fixing and minor improvements

## 📣 Update #5 - October 2024

New **API** release including the following updates:

### `/agent`

* release new `/agent` API endpoint for creating chat-like applications. Check [`/agent`](/brian-api/apis/agent) page.

### `/transaction`

* add Mode as supported chain
* the API response now contains the parameter extracted for the prompt and the user request and error (in case of errors)
* update how the `balance` action response is formatted
* general bug fixing and minor improvements

## 📣 Update #4 - August 2024

New **API** release including the following updates:

### `/transaction`

* add Taiko and Starknet as supported chains
* add Bungee, Avnu.fi, and Symbiosis as supported solvers
* add an `approve` transaction object as the first step in the `steps` array if needed. The `approve` transaction already considers the eventual existing allowance
* remove `amountToApprove` parameter in API response
* general bug fixing and minor improvements

### `/knowledge`

* **BREAKING CHANGE**: changed the API response format, check [#knowledge](#knowledge "mention") for more info
* New Polygon Knowledge Box

### `/networks`

* new endpoint for checking all the availables networks in the Brian APIs and their `chainId`

## 📣 Update #3 - July 2024

New **API** release including the following updates:

### `/transaction`

* `fromAmountUsd`  in the description for swap and bridge operations
* new `amountToApprove` parameter in API response. This parameter represents the eventual amount to approve before executing the requested transaction
* custom error if the destination chain of a bridge is not currently supported
* general bug fixing and minor improvements

## 📣 Update #2 - June 2024

New **API** release including the following updates:

### `/transaction`

* new chain: *Blast*
* the token `amount` for `withdraw` operation can be a percentage of the user position too. Such as "withdraw half of my steth from lido on ethereum"
* the token `amount` for `repay` operation can be a percentage of the user position too. Such as "repay half of my usdc debt on aave on arbitrum"
* new supported actions:
  * AAVE actions (on on Ethereum, Optimism, Arbitrum, Polygon and Base):&#x20;
    * borrow tokens from aave v3 . Such as "borrow 2 usdc from aave" or "borrow 5 dollars of eth from aave"
    * reapy debt on aave v3 . Such as "repay 2 usdc debt on aave on polygon" or "repay half of my eth debt on aave on base "
    * Check loan-to-value, liquidation threshold, total debt, borrowed amount, borrowable amount and other info from aave-v3
* general bug fixing and minor improvements

***

## 📣 Update #1 - May 2024

New **API** release including the following updates:

### `/transaction`

* new chain: *Scroll*
* chain extraction from the text prompt such as *swap 10 usdc to dai on **Base***. `chainId` in the body is now an optional parameter
* `address` parameter in the body can now be an ENS (.eth) domain
* the token `amount` can be expressed as a number ( *swap 10 usdc to da*i), as a dollar amount (*swap 10 dollars of eth to dai*), or as a percentage of the address balance passed into the body (*swap half of my usdc to dai*)
* new supported actions:
  * DeFi actions:&#x20;
    * direct deposit on Lido finance protocol
    * deposit to DeFi protocols using Enso solver&#x20;
    * withdraw from DeFi protocols using Enso solver&#x20;
  * ENS actions:&#x20;
    * check ENS availability
    * check ENS expiration
    * ENS forward resolution
    * ENS reverse resolution
    * ENS registration cost
    * ENS registration and renewal
* parallelization of solvers for swap and bridge, we now support Enso and LiFi for swap and bridge operations to provide an answer in case one of them fails or does not support the requested route
* general bug fixing and minor improvements


# API key

Create your Brian API key!

*The steps of creating your Brian API key are really simple!*

{% hint style="danger" %}
Each address can create just one API key right now!
{% endhint %}

The first step is to connect your wallet in the [Brian app](https://www.brianknows.org/app) and enter the **Settings** page. There you'll find an according named **API Keys**: click to open it.

<figure><img src="/files/ZTxBoYGwfbHjiLg8Pcid" alt=""><figcaption><p>Brian app settings page</p></figcaption></figure>

Once you're there, you just need to click on the **Add new +** button. This will open the following modal:

<figure><img src="/files/5G1HgVuoJalrdoZS6tWT" alt=""><figcaption><p>Brian app create api key modal</p></figcaption></figure>

Click on the **Create** button to get your API key! Copy it to your clipboard and save it somewhere safe.

### Some notes on the API key

* At the current stage, **you can only have one API key per address**. Multiple API keys will be added soon;
* The current limit is **1000 requests per month**. The count is reset every month the first day at midnight (CET timezone). In case you find yourself needing more requests, please contact us at [info@brianknows.org](mail:info@brianknows.org). We'll get in touch with you ASAP to find what solution best finds your needs.


# Brian Typescript SDK

{% hint style="success" %}
Do you need an API key? [Discover how to get one!](/brian-api/api-key)
{% endhint %}

Use the **@brian-ai/sdk** for interacting with [Brian APIs](/brian-api/apis) in your Typescript project! **The SDK is a wrapper of the Brian API.**

If you're building a Typescript project and want to interact with the Brian APIs in a type-safe way, you can use our npm package [**@brian-ai/sdk**](https://www.npmjs.com/package/@brian-ai/sdk). Make sure to always use the **latest** production version of the SDK in order to avoid any breaking changes.

You can install it using your package manager of choice:

#### 📦 Installation

```bash
# Using npm
npm install @brian-ai/sdk

# Using yarn
yarn add @brian-ai/sdk

# Using pnpm
pnpm add @brian-ai/sdk

# Using bun
bun add @brian-ai/sdk
```

⚒️ **Usage**

```typescript
// Using ES6 imports
import { BrianSDK } from "@brian-ai/sdk";

const options = {
  apiKey: process.env.BRIAN_API_KEY,
};

const brian = new BrianSDK(options);

// Using CommonJS imports
const { BrianSDK } = require("@brian-ai/sdk");

const brian = new BrianSDK(options);
```

{% hint style="danger" %}
The Brian ts SDK is meant to be used on the backend to not expose the Brian API key!
{% endhint %}

#### ⚙️ SDK initialization options

The `BrianSDK` constructor accepts an object with the following properties:

| Property     | Type   | Description                                                                                                                                                                        | Required |
| ------------ | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------- |
| `apiUrl`     | string | The API url you'll be calling. Default is `https://api.brianknows.org` for EU based projects. YOu can change it with `https://us-api.brianknows.org` for better latency in the US. | ❌        |
| `apiKey`     | string | The API key used to call the Brian APIs.                                                                                                                                           | ✅        |
| `apiVersion` | v0     | The API version. Only `v0` is available right now.                                                                                                                                 | ❌        |

#### 📚 SDK methods

| Method Name    | Description                                                                                                                            |
| -------------- | -------------------------------------------------------------------------------------------------------------------------------------- |
| `ask`          | Calls the Brian API /agent/knowledge method. Returns an AI-generated for the given prompt.                                             |
| `extract`      | Calls the Brian API /agent/parameters-extraction method. Returns the extracted parameters from the given prompt.                       |
| `generateCode` | Calls the Brian API /agent/smart-contracts method. Returns an AI-generated Solidity Smart Contract based on the prompt.                |
| `transact`     | Calls the Brian API /agent/transaction method. Returns one or more transactions ready to be executed, generated from the given prompt. |

## 📖 Usage Examples

### transact

```typescript
const brian = new BrianSDK(options);

const request = await brian.transact({
    prompt: "swap 1 ETH for USDC on base",
    address: "vitalik.eth",
});
console.log("transaction result:", request);

/*
transaction result: [
  {
    solver: "Enso",
    action: "swap",
    type: "write",
    data: {
      description: "You are about to swap 1.0 ETH ($3693.6) for 3695.0 USDC ($3693.9) on Base using Enso solver. The address receiver is 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045.",
      steps: [
        {
          chainId: 8453,
          blockNumber: 23526521,
          from: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
          to: "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
          gasLimit: "652920",
          data: "0xb35d7e73000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee0000000000000000000000000000000000000000000000000de0b6b3a764000000000000000000000000000000000000000000000000000000000000000000800000000000000000000000000000000000000000000000000000000000000180000000000000000000000000000000000000000000000000000000000000000719198595a30081ffffffffff129b480ad625bcd1a5c3a1c10d708114726fa46719198595a30283ffffffff83111111125421ca6dc452d289314280a0f8842a659bd3b227018304ffffffff036675a323dedb77822fcf39eaa9d682f6abe72555ddcd52200103ffffffffff037e7d64d987cab6eed08a191c4c2459daf2f8ed0ba9059cbb010503ffffffffff833589fcd6edb6e08f4c7c32d4f71b54bda029136e7a43a3010306ffffffff037e7d64d987cab6eed08a191c4c2459daf2f8ed0b241c59120103ffffffffffff7e7d64d987cab6eed08a191c4c2459daf2f8ed0b000000000000000000000000000000000000000000000000000000000000000700000000000000000000000000000000000000000000000000000000000000e000000000000000000000000000000000000000000000000000000000000001200000000000000000000000000000000000000000000000000000000000000140000000000000000000000000000000000000000000000000000000000000018000000000000000000000000000000000000000000000000000000000000005e000000000000000000000000000000000000000000000000000000000000006200000000000000000000000000000000000000000000000000000000000000660000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000038d7ea4c68000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000200000000000000000000000000000000000000000000000000ddd2935029d8000000000000000000000000000000000000000000000000000000000000000042807ed2379000000000000000000000000e37e799d5077682fa0a244d46e5649f71457bd09000000000000000000000000eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee000000000000000000000000833589fcd6edb6e08f4c7c32d4f71b54bda02913000000000000000000000000e37e799d5077682fa0a244d46e5649f71457bd090000000000000000000000007d585b0e27bbb3d981b7757115ec11f47c4769940000000000000000000000000000000000000000000000000ddd2935029d800000000000000000000000000000000000000000000000000000000000d595674f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000012000000000000000000000000000000000000000000000000000000000000002d00000000000000000000000000000000000000000000000000000000002b200a0c9e75c4800000000000011110f010000000000000000000000000000000000000002840001e30001420000a100a007e5c0d200000000000000000000000000000000000000000000000000007d00001a40414200000000000000000000000000000000000006d0e30db000a0fbb7cd06804c42b5057a8663e2b1ac21685d1502c937a0381700020000000000000000019c4200000000000000000000000000000000000006833589fcd6edb6e08f4c7c32d4f71b54bda02913111111125421ca6dc452d289314280a0f8842a6500a007e5c0d200000000000000000000000000000000000000000000000000007d00001a40414200000000000000000000000000000000000006d0e30db002a0000000000000000000000000000000000000000000000000000000004011f510ee63c1e58172ab388e2e2f6facef59e3c3fa2c4e29011c2d384200000000000000000000000000000000000006111111125421ca6dc452d289314280a0f8842a6500a007e5c0d200000000000000000000000000000000000000000000000000007d00001a40414200000000000000000000000000000000000006d0e30db002a000000000000000000000000000000000000000000000000000000000489c2714ee63c1e58157713f7716e0b0f65ec116912f834e49805480d24200000000000000000000000000000000000006111111125421ca6dc452d289314280a0f8842a6500a007e5c0d200000000000000000000000000000000000000000000000000007d00001a40414200000000000000000000000000000000000006d0e30db002a00000000000000000000000000000000000000000000000000000000048a1b3faee63c1e581482fe995c4a52bc79271ab29a53591363ee30a894200000000000000000000000000000000000006111111125421ca6dc452d289314280a0f8842a650000000000000000000000000000000097864b91000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000020000000000000000000000000d8da6bf26964af9d7eed9e03e53415d37aa96045000000000000000000000000000000000000000000000000000000000000002000000000000000000000000000000000000000000000000000000000d5a20080",
          value: "1000000000000000000",
        }
      ],
      gasCostUSD: "",
      fromChainId: 8453,
      fromAmountUSD: "3693.6",
      fromAmount: "1000000000000000000",
      fromToken: {
        address: "0x0000000000000000000000000000000000000000",
        chainId: 8453,
        symbol: "ETH",
        decimals: 18,
        name: "ETH",
        coinKey: "ETH",
        logoURI: "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2/logo.png",
        priceUSD: "3693.6",
      },
      fromAddress: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
      toChainId: 8453,
      toAmountUSD: "3693.9062281315605",
      toAmount: "3695014400",
      toAmountMin: "3695014400",
      toToken: {
        address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",
        chainId: 8453,
        symbol: "USDC",
        decimals: 6,
        name: "USD Coin",
        coinKey: "USDC",
        logoURI: "https://raw.githubusercontent.com/trustwallet/assets/master/blockchains/ethereum/assets/0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48/logo.png",
        priceUSD: "0.9997000899730081",
      },
      toAddress: "0x80EbA3855878739F4710233A8a19d89Bdd2ffB8E",
      receiver: "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045",
      protocol: {
        key: "enso",
        name: "enso",
        logoURI: "",
      },
    },
    extractedParams: {
      action: "swap",
      chain: "base",
      token1: "eth",
      token2: "usdc",
      address: "",
      amount: "1",
    },
    conversationHistory: [
      {
        sender: "user",
        content: "swap 1 ETH for USDC on base",
      }, {
        sender: "brian",
        content: "You are about to swap 1.0 ETH ($3693.6) for 3695.0 USDC ($3693.9) on Base using Enso solver. The address receiver is 0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045.",
      }
    ],
  }
]
*/
```

### How to execute a transaction

{% hint style="success" %}
[Here](/brian-api/apis/transaction/transactions-flow) you can find a page explaining the transaction flow using Brian API. It is an extended version of what is explained in this next paragraph for the SDK.
{% endhint %}

In the SDK response, you have:

* one or more standard `transaction` object, in the `steps` array of the response
* multiple parameters for info/frontend/backend purpose

The libraries and tools available for executing the transaction will depend on the type of chain you intend to use (EVM or Non-EVM, such as Solana/Starknet).&#x20;

In any case, the transactions returned by the Brian API are compatible with the most common development tools, such as Viem, Wagmi, Ethers for EVM chains, starknet.js, Starknet React for Starknet, and, Solana-Web3.js for Solana.

Check transaction execution examples from the API:

* [EVM](/brian-api/apis/transaction/transactions-flow/evm)
* [Starknet](/brian-api/apis/transaction/transactions-flow/starknet)
* [Solana](/brian-api/apis/transaction/transactions-flow/solana)

### ask

<pre class="language-typescript"><code class="lang-typescript">const brian = new BrianSDK(options);

  const request = await brian.ask({
    prompt: "explain uniswap v4 compared to v3",
    kb: "public-knowledge-box"
  });
  console.log("Knowledge result:", request);
  /*
<strong>  Knowledge result: {
</strong>    input: "explain uniswap v4 compared to v3",
    chat_history: [],
    context: [
      {
        pageContent: "Two years ago, we released Uniswap v3, a watershed moment for onchain liquidity and DeFi. Today, the Uniswap Protocol is the largest decentralized exchange protocol, processing over $1.5 trillion in trading volume. As public infrastructure, it's a vital part of the crypto ecosystem.\nAs technology and markets evolve, so must the Uniswap Protocol. That's why we're thrilled to introduce our vision for Uniswap v4, which we believe will open up a world of possibilities for how liquidity is created and how tokens are traded onchain.\nWe are releasing the draft code now so that v4 can be built in public, with open feedback and meaningful community contribution. We expect this will be a months-long process. You can read the open-sourced, early version of the Uniswap v4 core and periphery repositories, read the draft technical whitepaper here, and learn more about how to contribute here.\nUniswap v3 took a powerful, opinionated approach to liquidity provision, balancing an incredibly complex tradeoff space. New features come at the expense of higher fees and code complexity.  For example, v3 enshrined oracles, allowing builders to integrate real-time, onchain pricing data, but at the expense of some increased costs for swappers.\nOur vision with Uniswap v4 is to allow anyone to make these tradeoff decisions through the introduction of \"hooks.\" Hooks are contracts that run at various points of a pool action's lifecycle. Pools can make the same tradeoffs as v3, or they can add totally new functionality. For example, v4 will allow pools that natively support dynamic fees, add onchain limit orders, or act as a time-weighted average market maker (TWAMM) to spread out large orders over time.",
        metadata: {
          description: "All about our vision for Uniswap v4 and why we're building in public.",
          language: "en",
          source: "https://blog.uniswap.org/uniswap-v4",
          title: "Our Vision for Uniswap v4 ",
        },
      }, {
        pageContent: "License and Governance\nAs always, we strongly believe that core financial infrastructure should be open and transparent. We also believe that the Uniswap community — the people and teams that support, use, and build on the Protocol — should govern v4 of the Protocol, just as they govern prior versions.\nThe code will be released under a Business Source License 1.1, which limits the use of the v4 source code in a commercial or production setting for up to four years, at which point it will convert to a GPL license into perpetuity. Like v3, Uniswap Governance and Uniswap Labs can grant exceptions to the license.\nThe Protocol fee mechanism will also be modeled after v3. Governance will be able to vote to add a Protocol fee to any pool, up to a capped amount. More details on the fee mechanism can be found in the whitepaper.What is Uniswap v4Hooks &#x26; custom poolsImproved architecture and gas savingsLicense and GovernanceRelated posts  March 23, 2021Introducing Uniswap v3  October 19, 2023Community Contributions to Uniswap v4  May 05, 2021Uniswap v3 Mainnet launch",
        metadata: {
          description: "All about our vision for Uniswap v4 and why we're building in public.",
          language: "en",
          source: "https://blog.uniswap.org/uniswap-v4",
          title: "Our Vision for Uniswap v4 ",
        },
      }, {
        pageContent: "Along with this customization, Uniswap v4's architecture reduces costs and ensures efficiency. It introduces a new \"singleton\" contract, where all pools live within a single smart contract. We believe the combination of hooks and singleton architecture creates an incredibly powerful platform ⸺ fast, safe pool customization and efficient routing across many pools. Uniswap v4 brings fast, expressive AMM innovation within one powerful ecosystem.\nWhat is Uniswap v4\nHooks &#x26; custom pools\nEach Uniswap liquidity pool has a lifecycle. During a pool’s lifecycle, several things happen. A pool is created with a default fee tier. Liquidity is added, removed, or readjusted. And, of course, users swap tokens. In Uniswap v3, these lifecycle events are tightly coupled and executed in a very strict sequence.\nTo create room for customizable liquidity in Uniswap v4, we want to create a way for pool deployers to introduce code that performs a designated action at key points throughout the pool’s lifecycle – like before or after a swap, or before or after an LP position is changed.\nEnter hooks, which are plugins to customize how pools, swaps, fees, and LP positions interact. Developers can innovate on top of the Uniswap Protocol’s liquidity and security to create customized AMM pools through hooks that integrate with v4’s smart contracts.\nSome experiments we’re excited about include:",
        metadata: {
          description: "All about our vision for Uniswap v4 and why we're building in public.",
          language: "en",
          source: "https://blog.uniswap.org/uniswap-v4",
          title: "Our Vision for Uniswap v4 ",
        },
      }, {
        pageContent: "Improved architecture and gas savings\nIn Uniswap v3, we deploy a new contract for every pool, making creating pools and performing multi-pool swaps more expensive. In v4, we hold all the pools in one singleton contract, which will provide important gas savings because swaps will no longer need to transfer tokens between pools held in different contracts. Early estimates show that v4 reduces pool creation gas costs by 99%. Hooks introduce a world with endless options and singleton allows you to efficiently route across all of them.\nThis singleton architecture is complemented by a new \"flash accounting\" system. Instead of transferring assets in and out of pools at the end of every swap in v3, this system transfers only on net balances -- meaning a far more efficient system that provides additional gas savings in Uniswap v4.\nWe believe the best design for flash accounting uses \"transient storage,\" which would be enabled by EIP-1153. This EIP is being considered as part of the Ethereum Cancun hardfork and will bring even bigger gas improvements and cleaner contract designs across a wide variety of applications.\nWith the efficiency of singleton and flash accounting, fee tiers no longer need to be limited. Pool creators can set them at the level that makes them most competitive or customize them with a dynamic fee hook. v4 also brings back support for native ETH, which offers additional gas savings.",
        metadata: {
          description: "All about our vision for Uniswap v4 and why we're building in public.",
          language: "en",
          source: "https://blog.uniswap.org/uniswap-v4",
          title: "Our Vision for Uniswap v4 ",
        },
      }
    ],
    answer: "Uniswap v4 represents a significant evolution from v3, allowing developers greater customization and efficiency while maintaining the core liquidity provision functionality. Here’s a structured comparison of Uniswap v4 and v3:\n\n\"\n\n### 1. **Core Architecture**\n\n- **Uniswap v3**: Each liquidity pool operates as a separate smart contract, which leads to higher costs for deploying new pools and conducting multi-pool swaps due to multiple contract interactions.\n  \n- **Uniswap v4**: Introduces a **singleton architecture**, where all pools are managed under a single smart contract. This design dramatically reduces the gas fees associated with creating new pools and executing swaps, estimated to reduce pool creation gas costs by 99%.\n\n\"\n\n### 2. **Customizability Through Hooks**\n\n- **Uniswap v3**: Liquidities are managed in a tightly coupled manner with limited customization. The lifecycle of pools and swaps follows a strict sequence, constraining developers in terms of pool functionalities.\n\n- **Uniswap v4**: Implements **hooks**, which are plugins that allow developers to execute custom logic at various points in the pool's lifecycle, such as before and after swaps or liquidity changes. This opens a plethora of innovative possibilities, allowing for customized AMM functionality and improved interaction between swaps and LP positions.\n\n\"\n\n### 3. **Dynamic Fee Structures**\n\n- **Uniswap v3**: Introduces fee tiers, but these are set initially and not easily adjustable post-deployment. While LPs could theoretically offer different fees, making them competitive would require deploying multiple pools.\n\n- **Uniswap v4**: Enhances fee customization by allowing pools to support **dynamic fees** with hooks, enabling the fee structure to adapt more responsively to market conditions or specific trading strategies.\n\n\"\n\n### 4. **Flash Accounting Efficiency**\n\n- **Uniswap v3**: Transfers assets at the end of every swap, resulting in significant transaction overhead and gas costs.\n\n- **Uniswap v4**: Employs a new **flash accounting** system that transfers only net balances after transactions, significantly improving efficiency. This is complemented by the anticipated benefits of **EIP-1153**, which may further streamline contract interactions and reduce operational overhead.\n\n\"\n\n### 5. **Gas Savings and Native Token Support**\n\n- **Uniswap v3**: Lacks substantial gas optimization features and does not support native ETH for liquidity provision, limiting options for LPs looking to minimize transaction costs.\n\n- **Uniswap v4**: Reintroduces support for **native ETH**, offering additional gas savings and providing LPs with an opportunity to optimize their capital efficiency.\n\n\"\n\n### 6. **License and Governance**\n\n- **Uniswap v3**: Governed by Uniswap governance procedures; the protocol fee mechanism allows for some fee adjustments based on community votes.\n\n- **Uniswap v4**: Continues the principle of decentralized governance under a **Business Source License 1.1**, which permits the community to effectively govern the protocol while restricting commercial use for a transitional period before converting to a GPL license.\n\n\"\n\n### Conclusion\n\nIn summary, Uniswap v4 is designed to empower developers and liquidity providers by enhancing customized features while optimizing overall gas efficiency and operational costs. The introduction of hooks and a singleton architecture not only paves the way for novel AMM functionalities but also supports a more sustainable economic ecosystem within decentralized finance.\n\nFor further information, you can access the open-source version of the [Uniswap v4 core and periphery repositories](https://github.com/Uniswap) or read the accompanying [draft technical whitepaper](https://uniswap.org/docs/v4).",
  }
  
  */

</code></pre>

### extract

```typescript
const brian = new BrianSDK(options);

const request = await brian.extract({
    prompt: "swap 1 ETH for USDC",
});
console.log("Parameter extraction result:", request);
/*
Parameter extraction result: {
  prompt: "swap 1 ETH for USDC",
  completion: [
    {
      action: "swap",
      chain: "",
      token1: "ETH",
      token2: "USDC",
      address: "",
      amount: "1",
    }
  ],
}
*/

```

### generateCode

````typescript
const brian = new BrianSDK(options);

const request = await brian.generateCode({
    prompt: "give me the code of an erc20 token called BRIANNOOO",
    compile: true,
});
console.log("code result:", request);
  /*
  contract: "\n// SPDX-License-Identifier: MIT\npragma solidity 0.8.26;\n\nimport {ERC20} from \"@openzeppelin/contracts@5.1.0/token/ERC20/ERC20.sol\";\nimport {Ownable} from \"@openzeppelin/contracts@5.1.0/access/Ownable.sol\";\n\ncontract BriannoooToken is ERC20, Ownable {\n    constructor() ERC20(\"BRIANNOOO\", \"BRIAN\") Ownable(msg.sender) {\n        _mint(msg.sender, 1000000 * 10 ** decimals());\n    }\n\n    function mint(address to, uint256 amount) public onlyOwner {\n        _mint(to, amount);\n    }\n}\n",
  contractName: "BriannoooToken",
  abi: [
    {
      inputs: [],
      stateMutability: "nonpayable",
      type: "constructor",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        }, {
          internalType: "uint256",
          name: "allowance",
          type: "uint256",
        }, {
          internalType: "uint256",
          name: "needed",
          type: "uint256",
        }
      ],
      name: "ERC20InsufficientAllowance",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "sender",
          type: "address",
        }, {
          internalType: "uint256",
          name: "balance",
          type: "uint256",
        }, {
          internalType: "uint256",
          name: "needed",
          type: "uint256",
        }
      ],
      name: "ERC20InsufficientBalance",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "approver",
          type: "address",
        }
      ],
      name: "ERC20InvalidApprover",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "receiver",
          type: "address",
        }
      ],
      name: "ERC20InvalidReceiver",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "sender",
          type: "address",
        }
      ],
      name: "ERC20InvalidSender",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        }
      ],
      name: "ERC20InvalidSpender",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "owner",
          type: "address",
        }
      ],
      name: "OwnableInvalidOwner",
      type: "error",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "account",
          type: "address",
        }
      ],
      name: "OwnableUnauthorizedAccount",
      type: "error",
    }, {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "owner",
          type: "address",
        }, {
          indexed: true,
          internalType: "address",
          name: "spender",
          type: "address",
        }, {
          indexed: false,
          internalType: "uint256",
          name: "value",
          type: "uint256",
        }
      ],
      name: "Approval",
      type: "event",
    }, {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "previousOwner",
          type: "address",
        }, {
          indexed: true,
          internalType: "address",
          name: "newOwner",
          type: "address",
        }
      ],
      name: "OwnershipTransferred",
      type: "event",
    }, {
      anonymous: false,
      inputs: [
        {
          indexed: true,
          internalType: "address",
          name: "from",
          type: "address",
        }, {
          indexed: true,
          internalType: "address",
          name: "to",
          type: "address",
        }, {
          indexed: false,
          internalType: "uint256",
          name: "value",
          type: "uint256",
        }
      ],
      name: "Transfer",
      type: "event",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "owner",
          type: "address",
        }, {
          internalType: "address",
          name: "spender",
          type: "address",
        }
      ],
      name: "allowance",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "spender",
          type: "address",
        }, {
          internalType: "uint256",
          name: "value",
          type: "uint256",
        }
      ],
      name: "approve",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        }
      ],
      stateMutability: "nonpayable",
      type: "function",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "account",
          type: "address",
        }
      ],
      name: "balanceOf",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [],
      name: "decimals",
      outputs: [
        {
          internalType: "uint8",
          name: "",
          type: "uint8",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "to",
          type: "address",
        }, {
          internalType: "uint256",
          name: "amount",
          type: "uint256",
        }
      ],
      name: "mint",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    }, {
      inputs: [],
      name: "name",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [],
      name: "owner",
      outputs: [
        {
          internalType: "address",
          name: "",
          type: "address",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [],
      name: "renounceOwnership",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    }, {
      inputs: [],
      name: "symbol",
      outputs: [
        {
          internalType: "string",
          name: "",
          type: "string",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [],
      name: "totalSupply",
      outputs: [
        {
          internalType: "uint256",
          name: "",
          type: "uint256",
        }
      ],
      stateMutability: "view",
      type: "function",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "to",
          type: "address",
        }, {
          internalType: "uint256",
          name: "value",
          type: "uint256",
        }
      ],
      name: "transfer",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        }
      ],
      stateMutability: "nonpayable",
      type: "function",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "from",
          type: "address",
        }, {
          internalType: "address",
          name: "to",
          type: "address",
        }, {
          internalType: "uint256",
          name: "value",
          type: "uint256",
        }
      ],
      name: "transferFrom",
      outputs: [
        {
          internalType: "bool",
          name: "",
          type: "bool",
        }
      ],
      stateMutability: "nonpayable",
      type: "function",
    }, {
      inputs: [
        {
          internalType: "address",
          name: "newOwner",
          type: "address",
        }
      ],
      name: "transferOwnership",
      outputs: [],
      stateMutability: "nonpayable",
      type: "function",
    }
  ],
  bytecode: "0x608060405234801561000f575f80fd5b503360405180604001604052806009815260200168425249414e4e4f4f4f60b81b81525060405180604001604052806005815260200164212924a0a760d91b81525081600390816100609190610316565b50600461006d8282610316565b5050506001600160a01b03811661009e57604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b6100a7816100cf565b506100ca336100b86012600a6104c9565b6100c590620f42406104de565b610120565b610508565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b0382166101495760405163ec442f0560e01b81525f6004820152602401610095565b6101545f8383610158565b5050565b6001600160a01b038316610182578060025f82825461017791906104f5565b909155506101f29050565b6001600160a01b0383165f90815260208190526040902054818110156101d45760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401610095565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b03821661020e5760028054829003905561022c565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef8360405161027191815260200190565b60405180910390a3505050565b634e487b7160e01b5f52604160045260245ffd5b600181811c908216806102a657607f821691505b6020821081036102c457634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111561031157805f5260205f20601f840160051c810160208510156102ef5750805b601f840160051c820191505b8181101561030e575f81556001016102fb565b50505b505050565b81516001600160401b0381111561032f5761032f61027e565b6103438161033d8454610292565b846102ca565b6020601f821160018114610375575f831561035e5750848201515b5f19600385901b1c1916600184901b17845561030e565b5f84815260208120601f198516915b828110156103a45787850151825560209485019460019092019101610384565b50848210156103c157868401515f19600387901b60f8161c191681555b50505050600190811b01905550565b634e487b7160e01b5f52601160045260245ffd5b6001815b600184111561041f57808504811115610403576104036103d0565b600184161561041157908102905b60019390931c9280026103e8565b935093915050565b5f82610435575060016104c3565b8161044157505f6104c3565b816001811461045757600281146104615761047d565b60019150506104c3565b60ff841115610472576104726103d0565b50506001821b6104c3565b5060208310610133831016604e8410600b84101617156104a0575081810a6104c3565b6104ac5f1984846103e4565b805f19048211156104bf576104bf6103d0565b0290505b92915050565b5f6104d760ff841683610427565b9392505050565b80820281158282048414176104c3576104c36103d0565b808201808211156104c3576104c36103d0565b610881806105155f395ff3fe608060405234801561000f575f80fd5b50600436106100cb575f3560e01c806370a082311161008857806395d89b411161006357806395d89b41146101a4578063a9059cbb146101ac578063dd62ed3e146101bf578063f2fde38b146101f7575f80fd5b806370a0823114610159578063715018a6146101815780638da5cb5b14610189575f80fd5b806306fdde03146100cf578063095ea7b3146100ed57806318160ddd1461011057806323b872dd14610122578063313ce5671461013557806340c10f1914610144575b5f80fd5b6100d761020a565b6040516100e491906106f1565b60405180910390f35b6101006100fb366004610741565b61029a565b60405190151581526020016100e4565b6002545b6040519081526020016100e4565b610100610130366004610769565b6102b3565b604051601281526020016100e4565b610157610152366004610741565b6102d6565b005b6101146101673660046107a3565b6001600160a01b03165f9081526020819052604090205490565b6101576102ec565b6005546040516001600160a01b0390911681526020016100e4565b6100d76102ff565b6101006101ba366004610741565b61030e565b6101146101cd3660046107c3565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b6101576102053660046107a3565b61031b565b606060038054610219906107f4565b80601f0160208091040260200160405190810160405280929190818152602001828054610245906107f4565b80156102905780601f1061026757610100808354040283529160200191610290565b820191905f5260205f20905b81548152906001019060200180831161027357829003601f168201915b5050505050905090565b5f336102a781858561035d565b60019150505b92915050565b5f336102c085828561036f565b6102cb8585856103ea565b506001949350505050565b6102de610447565b6102e88282610474565b5050565b6102f4610447565b6102fd5f6104a8565b565b606060048054610219906107f4565b5f336102a78185856103ea565b610323610447565b6001600160a01b03811661035157604051631e4fbdf760e01b81525f60048201526024015b60405180910390fd5b61035a816104a8565b50565b61036a83838360016104f9565b505050565b6001600160a01b038381165f908152600160209081526040808320938616835292905220545f1981146103e457818110156103d657604051637dc7a0d960e11b81526001600160a01b03841660048201526024810182905260448101839052606401610348565b6103e484848484035f6104f9565b50505050565b6001600160a01b03831661041357604051634b637e8f60e11b81525f6004820152602401610348565b6001600160a01b03821661043c5760405163ec442f0560e01b81525f6004820152602401610348565b61036a8383836105cb565b6005546001600160a01b031633146102fd5760405163118cdaa760e01b8152336004820152602401610348565b6001600160a01b03821661049d5760405163ec442f0560e01b81525f6004820152602401610348565b6102e85f83836105cb565b600580546001600160a01b038381166001600160a01b0319831681179093556040519116919082907f8be0079c531659141344cd1fd0a4f28419497f9722a3daafe3b4186f6b6457e0905f90a35050565b6001600160a01b0384166105225760405163e602df0560e01b81525f6004820152602401610348565b6001600160a01b03831661054b57604051634a1406b160e11b81525f6004820152602401610348565b6001600160a01b038085165f90815260016020908152604080832093871683529290522082905580156103e457826001600160a01b0316846001600160a01b03167f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b925846040516105bd91815260200190565b60405180910390a350505050565b6001600160a01b0383166105f5578060025f8282546105ea919061082c565b909155506106659050565b6001600160a01b0383165f90815260208190526040902054818110156106475760405163391434e360e21b81526001600160a01b03851660048201526024810182905260448101839052606401610348565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b0382166106815760028054829003905561069f565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516106e491815260200190565b60405180910390a3505050565b602081525f82518060208401528060208501604085015e5f604082850101526040601f19601f83011684010191505092915050565b80356001600160a01b038116811461073c575f80fd5b919050565b5f8060408385031215610752575f80fd5b61075b83610726565b946020939093013593505050565b5f805f6060848603121561077b575f80fd5b61078484610726565b925061079260208501610726565b929592945050506040919091013590565b5f602082840312156107b3575f80fd5b6107bc82610726565b9392505050565b5f80604083850312156107d4575f80fd5b6107dd83610726565b91506107eb60208401610726565b90509250929050565b600181811c9082168061080857607f821691505b60208210810361082657634e487b7160e01b5f52602260045260245ffd5b50919050565b808201808211156102ad57634e487b7160e01b5f52601160045260245ffdfea26469706673582212204ceb436b1acd9f67ef19938d493a71aa230432de358d96a08d230e5e93fdee3e64736f6c634300081a0033",
  version: "0.8.26+commit.8a97fa7a.Emscripten.clang",
  standardJsonInput: "{\"language\":\"Solidity\",\"sources\":{\"BriannoooToken.sol\":{\"content\":\"\\n// SPDX-License-Identifier: MIT\\npragma solidity 0.8.26;\\n\\nimport \\\"ERC20.sol\\\";\\nimport \\\"Ownable.sol\\\";\\n\\ncontract BriannoooToken is ERC20, Ownable {\\n    constructor() ERC20(\\\"BRIANNOOO\\\", \\\"BRNO\\\") Ownable(msg.sender) {\\n        _mint(msg.sender, 1000000 * 10 ** decimals());\\n    }\\n\\n    function mint(address to, uint256 amount) public onlyOwner {\\n        _mint(to, amount);\\n    }\\n\\n    function burn(uint256 amount) public {\\n        _burn(msg.sender, amount);\\n    }\\n\\n    function burnFrom(address account, uint256 amount) public {\\n        _spendAllowance(account, msg.sender, amount);\\n        _burn(account, amount);\\n    }\\n}\\n\"},\"IERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/IERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Interface of the ERC-20 standard as defined in the ERC.\\n */\\ninterface IERC20 {\\n    /**\\n     * @dev Emitted when `value` tokens are moved from one account (`from`) to\\n     * another (`to`).\\n     *\\n     * Note that `value` may be zero.\\n     */\\n    event Transfer(address indexed from, address indexed to, uint256 value);\\n\\n    /**\\n     * @dev Emitted when the allowance of a `spender` for an `owner` is set by\\n     * a call to {approve}. `value` is the new allowance.\\n     */\\n    event Approval(address indexed owner, address indexed spender, uint256 value);\\n\\n    /**\\n     * @dev Returns the value of tokens in existence.\\n     */\\n    function totalSupply() external view returns (uint256);\\n\\n    /**\\n     * @dev Returns the value of tokens owned by `account`.\\n     */\\n    function balanceOf(address account) external view returns (uint256);\\n\\n    /**\\n     * @dev Moves a `value` amount of tokens from the caller's account to `to`.\\n     *\\n     * Returns a boolean value indicating whether the operation succeeded.\\n     *\\n     * Emits a {Transfer} event.\\n     */\\n    function transfer(address to, uint256 value) external returns (bool);\\n\\n    /**\\n     * @dev Returns the remaining number of tokens that `spender` will be\\n     * allowed to spend on behalf of `owner` through {transferFrom}. This is\\n     * zero by default.\\n     *\\n     * This value changes when {approve} or {transferFrom} are called.\\n     */\\n    function allowance(address owner, address spender) external view returns (uint256);\\n\\n    /**\\n     * @dev Sets a `value` amount of tokens as the allowance of `spender` over the\\n     * caller's tokens.\\n     *\\n     * Returns a boolean value indicating whether the operation succeeded.\\n     *\\n     * IMPORTANT: Beware that changing an allowance with this method brings the risk\\n     * that someone may use both the old and the new allowance by unfortunate\\n     * transaction ordering. One possible solution to mitigate this race\\n     * condition is to first reduce the spender's allowance to 0 and set the\\n     * desired value afterwards:\\n     * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729\\n     *\\n     * Emits an {Approval} event.\\n     */\\n    function approve(address spender, uint256 value) external returns (bool);\\n\\n    /**\\n     * @dev Moves a `value` amount of tokens from `from` to `to` using the\\n     * allowance mechanism. `value` is then deducted from the caller's\\n     * allowance.\\n     *\\n     * Returns a boolean value indicating whether the operation succeeded.\\n     *\\n     * Emits a {Transfer} event.\\n     */\\n    function transferFrom(address from, address to, uint256 value) external returns (bool);\\n}\\n\"},\"IERC20Metadata.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/extensions/IERC20Metadata.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport \\\"IERC20.sol\\\";\\n\\n/**\\n * @dev Interface for the optional metadata functions from the ERC-20 standard.\\n */\\ninterface IERC20Metadata is IERC20 {\\n    /**\\n     * @dev Returns the name of the token.\\n     */\\n    function name() external view returns (string memory);\\n\\n    /**\\n     * @dev Returns the symbol of the token.\\n     */\\n    function symbol() external view returns (string memory);\\n\\n    /**\\n     * @dev Returns the decimals places of the token.\\n     */\\n    function decimals() external view returns (uint8);\\n}\\n\"},\"Context.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.1) (utils/Context.sol)\\n\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Provides information about the current execution context, including the\\n * sender of the transaction and its data. While these are generally available\\n * via msg.sender and msg.data, they should not be accessed in such a direct\\n * manner, since when dealing with meta-transactions the account sending and\\n * paying for execution may not be the actual sender (as far as an application\\n * is concerned).\\n *\\n * This contract is only required for intermediate, library-like contracts.\\n */\\nabstract contract Context {\\n    function _msgSender() internal view virtual returns (address) {\\n        return msg.sender;\\n    }\\n\\n    function _msgData() internal view virtual returns (bytes calldata) {\\n        return msg.data;\\n    }\\n\\n    function _contextSuffixLength() internal view virtual returns (uint256) {\\n        return 0;\\n    }\\n}\\n\"},\"draft-IERC6093.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.1.0) (interfaces/draft-IERC6093.sol)\\npragma solidity ^0.8.20;\\n\\n/**\\n * @dev Standard ERC-20 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-20 tokens.\\n */\\ninterface IERC20Errors {\\n    /**\\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n     * @param sender Address whose tokens are being transferred.\\n     * @param balance Current balance for the interacting account.\\n     * @param needed Minimum amount required to perform a transfer.\\n     */\\n    error ERC20InsufficientBalance(address sender, uint256 balance, uint256 needed);\\n\\n    /**\\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\\n     * @param sender Address whose tokens are being transferred.\\n     */\\n    error ERC20InvalidSender(address sender);\\n\\n    /**\\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n     * @param receiver Address to which tokens are being transferred.\\n     */\\n    error ERC20InvalidReceiver(address receiver);\\n\\n    /**\\n     * @dev Indicates a failure with the `spender`’s `allowance`. Used in transfers.\\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\\n     * @param allowance Amount of tokens a `spender` is allowed to operate with.\\n     * @param needed Minimum amount required to perform a transfer.\\n     */\\n    error ERC20InsufficientAllowance(address spender, uint256 allowance, uint256 needed);\\n\\n    /**\\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n     * @param approver Address initiating an approval operation.\\n     */\\n    error ERC20InvalidApprover(address approver);\\n\\n    /**\\n     * @dev Indicates a failure with the `spender` to be approved. Used in approvals.\\n     * @param spender Address that may be allowed to operate on tokens without being their owner.\\n     */\\n    error ERC20InvalidSpender(address spender);\\n}\\n\\n/**\\n * @dev Standard ERC-721 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-721 tokens.\\n */\\ninterface IERC721Errors {\\n    /**\\n     * @dev Indicates that an address can't be an owner. For example, `address(0)` is a forbidden owner in ERC-20.\\n     * Used in balance queries.\\n     * @param owner Address of the current owner of a token.\\n     */\\n    error ERC721InvalidOwner(address owner);\\n\\n    /**\\n     * @dev Indicates a `tokenId` whose `owner` is the zero address.\\n     * @param tokenId Identifier number of a token.\\n     */\\n    error ERC721NonexistentToken(uint256 tokenId);\\n\\n    /**\\n     * @dev Indicates an error related to the ownership over a particular token. Used in transfers.\\n     * @param sender Address whose tokens are being transferred.\\n     * @param tokenId Identifier number of a token.\\n     * @param owner Address of the current owner of a token.\\n     */\\n    error ERC721IncorrectOwner(address sender, uint256 tokenId, address owner);\\n\\n    /**\\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\\n     * @param sender Address whose tokens are being transferred.\\n     */\\n    error ERC721InvalidSender(address sender);\\n\\n    /**\\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n     * @param receiver Address to which tokens are being transferred.\\n     */\\n    error ERC721InvalidReceiver(address receiver);\\n\\n    /**\\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\\n     * @param tokenId Identifier number of a token.\\n     */\\n    error ERC721InsufficientApproval(address operator, uint256 tokenId);\\n\\n    /**\\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n     * @param approver Address initiating an approval operation.\\n     */\\n    error ERC721InvalidApprover(address approver);\\n\\n    /**\\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\\n     */\\n    error ERC721InvalidOperator(address operator);\\n}\\n\\n/**\\n * @dev Standard ERC-1155 Errors\\n * Interface of the https://eips.ethereum.org/EIPS/eip-6093[ERC-6093] custom errors for ERC-1155 tokens.\\n */\\ninterface IERC1155Errors {\\n    /**\\n     * @dev Indicates an error related to the current `balance` of a `sender`. Used in transfers.\\n     * @param sender Address whose tokens are being transferred.\\n     * @param balance Current balance for the interacting account.\\n     * @param needed Minimum amount required to perform a transfer.\\n     * @param tokenId Identifier number of a token.\\n     */\\n    error ERC1155InsufficientBalance(address sender, uint256 balance, uint256 needed, uint256 tokenId);\\n\\n    /**\\n     * @dev Indicates a failure with the token `sender`. Used in transfers.\\n     * @param sender Address whose tokens are being transferred.\\n     */\\n    error ERC1155InvalidSender(address sender);\\n\\n    /**\\n     * @dev Indicates a failure with the token `receiver`. Used in transfers.\\n     * @param receiver Address to which tokens are being transferred.\\n     */\\n    error ERC1155InvalidReceiver(address receiver);\\n\\n    /**\\n     * @dev Indicates a failure with the `operator`’s approval. Used in transfers.\\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\\n     * @param owner Address of the current owner of a token.\\n     */\\n    error ERC1155MissingApprovalForAll(address operator, address owner);\\n\\n    /**\\n     * @dev Indicates a failure with the `approver` of a token to be approved. Used in approvals.\\n     * @param approver Address initiating an approval operation.\\n     */\\n    error ERC1155InvalidApprover(address approver);\\n\\n    /**\\n     * @dev Indicates a failure with the `operator` to be approved. Used in approvals.\\n     * @param operator Address that may be allowed to operate on tokens without being their owner.\\n     */\\n    error ERC1155InvalidOperator(address operator);\\n\\n    /**\\n     * @dev Indicates an array length mismatch between ids and values in a safeBatchTransferFrom operation.\\n     * Used in batch transfers.\\n     * @param idsLength Length of the array of token identifiers\\n     * @param valuesLength Length of the array of token amounts\\n     */\\n    error ERC1155InvalidArrayLength(uint256 idsLength, uint256 valuesLength);\\n}\\n\"},\"ERC20.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.1.0) (token/ERC20/ERC20.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport \\\"IERC20.sol\\\";\\nimport \\\"IERC20Metadata.sol\\\";\\nimport \\\"Context.sol\\\";\\nimport \\\"draft-IERC6093.sol\\\";\\n\\n/**\\n * @dev Implementation of the {IERC20} interface.\\n *\\n * This implementation is agnostic to the way tokens are created. This means\\n * that a supply mechanism has to be added in a derived contract using {_mint}.\\n *\\n * TIP: For a detailed writeup see our guide\\n * https://forum.openzeppelin.com/t/how-to-implement-erc20-supply-mechanisms/226[How\\n * to implement supply mechanisms].\\n *\\n * The default value of {decimals} is 18. To change this, you should override\\n * this function so it returns a different value.\\n *\\n * We have followed general OpenZeppelin Contracts guidelines: functions revert\\n * instead returning `false` on failure. This behavior is nonetheless\\n * conventional and does not conflict with the expectations of ERC-20\\n * applications.\\n */\\nabstract contract ERC20 is Context, IERC20, IERC20Metadata, IERC20Errors {\\n    mapping(address account => uint256) private _balances;\\n\\n    mapping(address account => mapping(address spender => uint256)) private _allowances;\\n\\n    uint256 private _totalSupply;\\n\\n    string private _name;\\n    string private _symbol;\\n\\n    /**\\n     * @dev Sets the values for {name} and {symbol}.\\n     *\\n     * All two of these values are immutable: they can only be set once during\\n     * construction.\\n     */\\n    constructor(string memory name_, string memory symbol_) {\\n        _name = name_;\\n        _symbol = symbol_;\\n    }\\n\\n    /**\\n     * @dev Returns the name of the token.\\n     */\\n    function name() public view virtual returns (string memory) {\\n        return _name;\\n    }\\n\\n    /**\\n     * @dev Returns the symbol of the token, usually a shorter version of the\\n     * name.\\n     */\\n    function symbol() public view virtual returns (string memory) {\\n        return _symbol;\\n    }\\n\\n    /**\\n     * @dev Returns the number of decimals used to get its user representation.\\n     * For example, if `decimals` equals `2`, a balance of `505` tokens should\\n     * be displayed to a user as `5.05` (`505 / 10 ** 2`).\\n     *\\n     * Tokens usually opt for a value of 18, imitating the relationship between\\n     * Ether and Wei. This is the default value returned by this function, unless\\n     * it's overridden.\\n     *\\n     * NOTE: This information is only used for _display_ purposes: it in\\n     * no way affects any of the arithmetic of the contract, including\\n     * {IERC20-balanceOf} and {IERC20-transfer}.\\n     */\\n    function decimals() public view virtual returns (uint8) {\\n        return 18;\\n    }\\n\\n    /**\\n     * @dev See {IERC20-totalSupply}.\\n     */\\n    function totalSupply() public view virtual returns (uint256) {\\n        return _totalSupply;\\n    }\\n\\n    /**\\n     * @dev See {IERC20-balanceOf}.\\n     */\\n    function balanceOf(address account) public view virtual returns (uint256) {\\n        return _balances[account];\\n    }\\n\\n    /**\\n     * @dev See {IERC20-transfer}.\\n     *\\n     * Requirements:\\n     *\\n     * - `to` cannot be the zero address.\\n     * - the caller must have a balance of at least `value`.\\n     */\\n    function transfer(address to, uint256 value) public virtual returns (bool) {\\n        address owner = _msgSender();\\n        _transfer(owner, to, value);\\n        return true;\\n    }\\n\\n    /**\\n     * @dev See {IERC20-allowance}.\\n     */\\n    function allowance(address owner, address spender) public view virtual returns (uint256) {\\n        return _allowances[owner][spender];\\n    }\\n\\n    /**\\n     * @dev See {IERC20-approve}.\\n     *\\n     * NOTE: If `value` is the maximum `uint256`, the allowance is not updated on\\n     * `transferFrom`. This is semantically equivalent to an infinite approval.\\n     *\\n     * Requirements:\\n     *\\n     * - `spender` cannot be the zero address.\\n     */\\n    function approve(address spender, uint256 value) public virtual returns (bool) {\\n        address owner = _msgSender();\\n        _approve(owner, spender, value);\\n        return true;\\n    }\\n\\n    /**\\n     * @dev See {IERC20-transferFrom}.\\n     *\\n     * Skips emitting an {Approval} event indicating an allowance update. This is not\\n     * required by the ERC. See {xref-ERC20-_approve-address-address-uint256-bool-}[_approve].\\n     *\\n     * NOTE: Does not update the allowance if the current allowance\\n     * is the maximum `uint256`.\\n     *\\n     * Requirements:\\n     *\\n     * - `from` and `to` cannot be the zero address.\\n     * - `from` must have a balance of at least `value`.\\n     * - the caller must have allowance for ``from``'s tokens of at least\\n     * `value`.\\n     */\\n    function transferFrom(address from, address to, uint256 value) public virtual returns (bool) {\\n        address spender = _msgSender();\\n        _spendAllowance(from, spender, value);\\n        _transfer(from, to, value);\\n        return true;\\n    }\\n\\n    /**\\n     * @dev Moves a `value` amount of tokens from `from` to `to`.\\n     *\\n     * This internal function is equivalent to {transfer}, and can be used to\\n     * e.g. implement automatic token fees, slashing mechanisms, etc.\\n     *\\n     * Emits a {Transfer} event.\\n     *\\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\\n     */\\n    function _transfer(address from, address to, uint256 value) internal {\\n        if (from == address(0)) {\\n            revert ERC20InvalidSender(address(0));\\n        }\\n        if (to == address(0)) {\\n            revert ERC20InvalidReceiver(address(0));\\n        }\\n        _update(from, to, value);\\n    }\\n\\n    /**\\n     * @dev Transfers a `value` amount of tokens from `from` to `to`, or alternatively mints (or burns) if `from`\\n     * (or `to`) is the zero address. All customizations to transfers, mints, and burns should be done by overriding\\n     * this function.\\n     *\\n     * Emits a {Transfer} event.\\n     */\\n    function _update(address from, address to, uint256 value) internal virtual {\\n        if (from == address(0)) {\\n            // Overflow check required: The rest of the code assumes that totalSupply never overflows\\n            _totalSupply += value;\\n        } else {\\n            uint256 fromBalance = _balances[from];\\n            if (fromBalance < value) {\\n                revert ERC20InsufficientBalance(from, fromBalance, value);\\n            }\\n            unchecked {\\n                // Overflow not possible: value <= fromBalance <= totalSupply.\\n                _balances[from] = fromBalance - value;\\n            }\\n        }\\n\\n        if (to == address(0)) {\\n            unchecked {\\n                // Overflow not possible: value <= totalSupply or value <= fromBalance <= totalSupply.\\n                _totalSupply -= value;\\n            }\\n        } else {\\n            unchecked {\\n                // Overflow not possible: balance + value is at most totalSupply, which we know fits into a uint256.\\n                _balances[to] += value;\\n            }\\n        }\\n\\n        emit Transfer(from, to, value);\\n    }\\n\\n    /**\\n     * @dev Creates a `value` amount of tokens and assigns them to `account`, by transferring it from address(0).\\n     * Relies on the `_update` mechanism\\n     *\\n     * Emits a {Transfer} event with `from` set to the zero address.\\n     *\\n     * NOTE: This function is not virtual, {_update} should be overridden instead.\\n     */\\n    function _mint(address account, uint256 value) internal {\\n        if (account == address(0)) {\\n            revert ERC20InvalidReceiver(address(0));\\n        }\\n        _update(address(0), account, value);\\n    }\\n\\n    /**\\n     * @dev Destroys a `value` amount of tokens from `account`, lowering the total supply.\\n     * Relies on the `_update` mechanism.\\n     *\\n     * Emits a {Transfer} event with `to` set to the zero address.\\n     *\\n     * NOTE: This function is not virtual, {_update} should be overridden instead\\n     */\\n    function _burn(address account, uint256 value) internal {\\n        if (account == address(0)) {\\n            revert ERC20InvalidSender(address(0));\\n        }\\n        _update(account, address(0), value);\\n    }\\n\\n    /**\\n     * @dev Sets `value` as the allowance of `spender` over the `owner` s tokens.\\n     *\\n     * This internal function is equivalent to `approve`, and can be used to\\n     * e.g. set automatic allowances for certain subsystems, etc.\\n     *\\n     * Emits an {Approval} event.\\n     *\\n     * Requirements:\\n     *\\n     * - `owner` cannot be the zero address.\\n     * - `spender` cannot be the zero address.\\n     *\\n     * Overrides to this logic should be done to the variant with an additional `bool emitEvent` argument.\\n     */\\n    function _approve(address owner, address spender, uint256 value) internal {\\n        _approve(owner, spender, value, true);\\n    }\\n\\n    /**\\n     * @dev Variant of {_approve} with an optional flag to enable or disable the {Approval} event.\\n     *\\n     * By default (when calling {_approve}) the flag is set to true. On the other hand, approval changes made by\\n     * `_spendAllowance` during the `transferFrom` operation set the flag to false. This saves gas by not emitting any\\n     * `Approval` event during `transferFrom` operations.\\n     *\\n     * Anyone who wishes to continue emitting `Approval` events on the`transferFrom` operation can force the flag to\\n     * true using the following override:\\n     *\\n     * ```solidity\\n     * function _approve(address owner, address spender, uint256 value, bool) internal virtual override {\\n     *     super._approve(owner, spender, value, true);\\n     * }\\n     * ```\\n     *\\n     * Requirements are the same as {_approve}.\\n     */\\n    function _approve(address owner, address spender, uint256 value, bool emitEvent) internal virtual {\\n        if (owner == address(0)) {\\n            revert ERC20InvalidApprover(address(0));\\n        }\\n        if (spender == address(0)) {\\n            revert ERC20InvalidSpender(address(0));\\n        }\\n        _allowances[owner][spender] = value;\\n        if (emitEvent) {\\n            emit Approval(owner, spender, value);\\n        }\\n    }\\n\\n    /**\\n     * @dev Updates `owner` s allowance for `spender` based on spent `value`.\\n     *\\n     * Does not update the allowance value in case of infinite allowance.\\n     * Revert if not enough allowance is available.\\n     *\\n     * Does not emit an {Approval} event.\\n     */\\n    function _spendAllowance(address owner, address spender, uint256 value) internal virtual {\\n        uint256 currentAllowance = allowance(owner, spender);\\n        if (currentAllowance != type(uint256).max) {\\n            if (currentAllowance < value) {\\n                revert ERC20InsufficientAllowance(spender, currentAllowance, value);\\n            }\\n            unchecked {\\n                _approve(owner, spender, currentAllowance - value, false);\\n            }\\n        }\\n    }\\n}\\n\"},\"Ownable.sol\":{\"content\":\"// SPDX-License-Identifier: MIT\\n// OpenZeppelin Contracts (last updated v5.0.0) (access/Ownable.sol)\\n\\npragma solidity ^0.8.20;\\n\\nimport \\\"Context.sol\\\";\\n\\n/**\\n * @dev Contract module which provides a basic access control mechanism, where\\n * there is an account (an owner) that can be granted exclusive access to\\n * specific functions.\\n *\\n * The initial owner is set to the address provided by the deployer. This can\\n * later be changed with {transferOwnership}.\\n *\\n * This module is used through inheritance. It will make available the modifier\\n * `onlyOwner`, which can be applied to your functions to restrict their use to\\n * the owner.\\n */\\nabstract contract Ownable is Context {\\n    address private _owner;\\n\\n    /**\\n     * @dev The caller account is not authorized to perform an operation.\\n     */\\n    error OwnableUnauthorizedAccount(address account);\\n\\n    /**\\n     * @dev The owner is not a valid owner account. (eg. `address(0)`)\\n     */\\n    error OwnableInvalidOwner(address owner);\\n\\n    event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);\\n\\n    /**\\n     * @dev Initializes the contract setting the address provided by the deployer as the initial owner.\\n     */\\n    constructor(address initialOwner) {\\n        if (initialOwner == address(0)) {\\n            revert OwnableInvalidOwner(address(0));\\n        }\\n        _transferOwnership(initialOwner);\\n    }\\n\\n    /**\\n     * @dev Throws if called by any account other than the owner.\\n     */\\n    modifier onlyOwner() {\\n        _checkOwner();\\n        _;\\n    }\\n\\n    /**\\n     * @dev Returns the address of the current owner.\\n     */\\n    function owner() public view virtual returns (address) {\\n        return _owner;\\n    }\\n\\n    /**\\n     * @dev Throws if the sender is not the owner.\\n     */\\n    function _checkOwner() internal view virtual {\\n        if (owner() != _msgSender()) {\\n            revert OwnableUnauthorizedAccount(_msgSender());\\n        }\\n    }\\n\\n    /**\\n     * @dev Leaves the contract without owner. It will not be possible to call\\n     * `onlyOwner` functions. Can only be called by the current owner.\\n     *\\n     * NOTE: Renouncing ownership will leave the contract without an owner,\\n     * thereby disabling any functionality that is only available to the owner.\\n     */\\n    function renounceOwnership() public virtual onlyOwner {\\n        _transferOwnership(address(0));\\n    }\\n\\n    /**\\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n     * Can only be called by the current owner.\\n     */\\n    function transferOwnership(address newOwner) public virtual onlyOwner {\\n        if (newOwner == address(0)) {\\n            revert OwnableInvalidOwner(address(0));\\n        }\\n        _transferOwnership(newOwner);\\n    }\\n\\n    /**\\n     * @dev Transfers ownership of the contract to a new account (`newOwner`).\\n     * Internal function without access restriction.\\n     */\\n    function _transferOwnership(address newOwner) internal virtual {\\n        address oldOwner = _owner;\\n        _owner = newOwner;\\n        emit OwnershipTransferred(oldOwner, newOwner);\\n    }\\n}\\n\"}},\"settings\":{\"optimizer\":{\"enabled\":true,\"runs\":200},\"outputSelection\":{\"*\":{\"*\":[\"*\"]}}}}"
}
  */

````

***

**💻 Check out the** [**Github Repo**](https://github.com/brian-knows/brian-sdk) **to learn how to use the SDK.**


# LangChain<>Brian SDK

Check the [@brian-ai/langchain](https://langchain.brianknows.org/) TypeScript SDK for creating web3 Langchain agents.


# Overview

{% hint style="warning" %}
Use Brian at your own risk. Always check the transaction you are confirming, because as it is a non-custodial solution, we are not responsible if you end up losing money!
{% endhint %}

**Brian App** is the first application built on the Brian API. You can:

* [Ask Brian](/brian-app/ask-brian): ask for information about supported protocols and chains. Brian will generate a response and indicate the resources used to generate it. Such as "What is Swarm?"
* [Send Transaction](/brian-app/send-transactions): build the transaction for the user by simply prompting in English.&#x20;
* [Deploy Smart Contracts](/brian-app/deploy-smart-contracts): Here you can ask Brian to write, compile, deploy a smart contract for you by simply prompting in English


# Send Transactions

The **Send Transactions** feature allows users to perform transactions by prompting in plain English such as "Hey Brian, can you swap 100 usdc for eth on Polygon?".

{% hint style="success" %}
The **Send Transactions** feature is **non-custodial**.&#x20;

You still have to sign the transaction with your wallet, **Brian is not** a custodial solution managing your private key.

**Please read carefully the transaction you're executing!**
{% endhint %}

## How to send a transaction

1\) <mark style="color:red;">**Connect your EOA Wallet**</mark>. We suggest using Rabby Wallet for a smoother UX, and you can check the transaction simulation within the wallet extension.

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

2\) <mark style="color:red;">**Sign the**</mark> [<mark style="color:red;">**Terms and Conditions**</mark>](https://brianknows.org/terms-and-conditions) <mark style="color:red;">**message**</mark>. Read carefully the [terms and conditions](https://brianknows.org/terms-and-conditions) related to using real funds on the Brian App and the prompt-to-earn program.

3\) <mark style="color:red;">**Check the available networks**</mark>**,** by clicking on the button on the bottom-left. On the Brian App we support Ethereum and the other main networks in the EVM ecosystem.

<figure><img src="/files/YwukAiyymobRAPBmNSVp" alt="" width="375"><figcaption></figcaption></figure>

4\) <mark style="color:red;">**Check the supported actions actions**</mark>. For each chain, we support specific actions (for example, the ENS registration is only supported on Ethereum). By clicking on one action, you have an example of the prompt for that action. For the same action, you can write it in so many different ways!

<figure><img src="/files/02t9rqMTb6uaaV9JDSzm" alt="" width="318"><figcaption></figcaption></figure>

5\) <mark style="color:red;">**Prompt your intent**</mark>. When you confirm the prompt, you're not executing the TX! Brian will first extract your intent into parameters and then build the TX via a series of solvers/aggregators like LIFI, Enso Finance, or Bungee Exchange.

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

6\) <mark style="color:red;">**Read the transaction description and review everything in the TX info box**</mark>. When you have reviewed everything, you can confirm the TX, and, as in any dapp, the EOA wallet extension will pop up.

{% hint style="warning" %}
Read the transaction description carefully and review all the parameters before executing the TX. **You're aware that you're solely responsible for what happens to your funds after the TX executio**n.
{% endhint %}

a) <mark style="color:orange;">**Transaction description**</mark>: a human-readable description of the TX you are executing.

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

b) <mark style="color:orange;">**Transaction info**</mark>: you can manually check each of the parameters involved in the transaction. For example, for a swap, the involved tokens, protocols, and the sender and receiver addresses.

<figure><img src="/files/IGIxT8MgF3Y2NQmSn9aG" alt="" width="375"><figcaption></figcaption></figure>

&#x20;7\) <mark style="color:red;">**Sign the transaction in your EOA wallet**</mark>**.** This will normally imply an approve + execute in the case of an ERC20-related action (like a swap or bridge) or just one TX in the case of using ETH.

Let's make the example with a swap of an ERC20:\
7.1) <mark style="color:orange;">**Approve**</mark>

<figure><img src="/files/GhDC07OuKG8lpgdbkEol" alt="" width="375"><figcaption></figcaption></figure>

7.2) <mark style="color:orange;">**Swap**</mark>: on Rabby, you can easily see, thanks to the TX simulation, the tokens that I'm sending and the ones I'll receive. Plus, there is a lot of other info for the transaction.

<figure><img src="/files/FpRwpJG8RZosqtLx3pWW" alt="" width="375"><figcaption></figcaption></figure>

8\) <mark style="color:yellow;">**Congrats, you have performed your first swap on the Brian app!🎉**</mark> Now, by clicking on the "block explorer" button, you open the block explorer on that chain and can see that the transaction has been executed correctly.

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


# Ask Brian

The **Ask Brian** feature allows users to ask for information about web3 protocols and chains. Brian will generate an answer and the link to the docs used to generate it.

Try something like `"What is Uniswap?"`.

## How to ask for information

1\) Prompt the question you want to ask and click on the **Search** button

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

2\) You can have a look at the docs used to generate the answer and open the links

![](/files/OfFNO88h0G7pWZXP4dsW)


# Deploy Smart Contracts

{% hint style="warning" %}
This functionality is currently disabled in the Brian App due to getting an update to reflect the latest API changes.&#x20;

You can still access it via our APIs!
{% endhint %}

The **Deploy Smart Contracts** feature allows users to generate, compile, deploy, and interact with smart contracts by prompting in English.

Try something like `"write an ERC20 named Test with symbol TST and supply 100000"`.

## How to deploy a Smart Contract

1\) Prompt the description of a smart contract you'd like to generate

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

2\) Brian will generate the solidity smart contract code

<figure><img src="/files/98Uol08jMd76iECO72LI" alt=""><figcaption></figcaption></figure>

3\) Click the edit button to manually edit the smart contract code

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

4\) Click the Explain this button to have an AI text generated explaining the smart contract code

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

5\) Click the Deploy button to compile and deploy the smart contract generated

![](/files/tYHX28jGPrwh08pmqVom)

## How to interact with a deployed Smart Contract

1\) Go to **Deployed Smart Contracts** on the **Settings** page. Here you can find all the smart contract deployed through Brian

<figure><img src="/files/6EHL5LB21EkxnH5BSlku" alt=""><figcaption></figcaption></figure>

2\) Click on the **Interact** button and the Interaction page will open

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

3\) Clicking on the **info button (i)** you can see the info of the deployed smart contract you're interacting with such as the methods available in the contract, the ABI and the smart contract code

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

4\) Prompt in English how you want to interact with the smart contract

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

4\) Click the Execute button to execute the transaction


