# 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>
  );
}
```


---

# Agent Instructions: Querying This Documentation

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

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

```
GET https://docs.brianknows.org/brian-api/apis/transaction/transactions-flow/evm.md?ask=<question>
```

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

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