# Code walkthrough · GOAT chat agent for native Chromia transactions · Learn Chromia

> You can point the project at testnet or mainnet. The CHROMIA_CONFIG object supplies predefined constants for whichever network you pick:

Source: https://chromia.com/learn/chromia-goat-chat-agent/codebase-overview/

GOAT chat agent for native Chromia transactionsLesson 4 of 4

1. [01An AI chat agent that sends Chromia transactions](https://chromia.com/learn/chromia-goat-chat-agent/introduction/)
2. [02Set up your project](https://chromia.com/learn/chromia-goat-chat-agent/setup/)
3. [03Explore the chat agent](https://chromia.com/learn/chromia-goat-chat-agent/explore-agent/)
4. [04Code walkthrough](https://chromia.com/learn/chromia-goat-chat-agent/codebase-overview/)

[Learn](https://chromia.com/learn/)[GOAT chat agent for native Chromia transactions](https://chromia.com/learn/chromia-goat-chat-agent/)

04 / 04Advanced

# Code walkthrough

The project consists of two main files:

1. **`index.ts`: Entry point**

   * Handles environment configuration, blockchain connections, tool setup, and interaction with the user.
   * Shows how to run blockchain operations securely, with MetaMask signing transactions and the GOAT SDK handling blockchain management.
2. **`tools.ts`: Helper functions**

   * Holds reusable tools, such as fetching the live CHR price and configuring how the assistant behaves.

## Key components

### 1. **Environment and network setup**

You can point the project at **testnet** or **mainnet**. The `CHROMIA_CONFIG` object supplies predefined constants for whichever network you pick:

typescript

```
const chromiaNetwork = "testnet"; // Switch to "mainnet" for mainnet operations
console.log(chalk.green("✔ Using Chromia network:"), chromiaNetwork);

const config = CHROMIA_CONFIG[chromiaNetwork];
```

**Key points:**

* **Predefined configurations:** `CHROMIA_CONFIG` includes ready-made constants for both testnet and mainnet:
  + `NODE_URL_POOL`: The node URLs used to communicate with the blockchain.
  + `ECONOMY_CHAIN_BRID`: The identifier of the Economy Chain.
  + `CHR_ASSET_ID`: The identifier of the CHR token.
* **Dynamic targeting:** Pass `"testnet"` or `"mainnet"` to load the matching values from `CHROMIA_CONFIG`.
* **Customization:** `CHROMIA_CONFIG` is only a convenience. For advanced cases, skip it and provide your own values.

### 2. **Connect to Chromia and enable transactions**

Next, the project opens a connection to the Chromia blockchain and sets up transactions. You can adjust this setup to work with other chains and tokens.

typescript

```
const chromiaClient = await createClient({
    nodeUrlPool: config.NODE_URL_POOL,
    blockchainRid: config.ECONOMY_CHAIN_BRID, // Specifies the target chain
});
const connection = createConnection(chromiaClient);
const evmKeyStore = await createWeb3ProviderEvmKeyStore(window.ethereum);
const keystoreInteractor = createKeyStoreInteractor(chromiaClient, evmKeyStore);

const baseTools = await getOnChainTools({
    wallet: chromia({
        client: chromiaClient,
        accountAddress,
        keystoreInteractor,
        assetId: config.CHR_ASSET_ID, // Specifies the token for transfer
        connection,
    }),
    plugins: [sendCHR()], // Adds token transfer functionality
});
```

**Key points:**

* **Network targeting:** `NODE_URL_POOL` determines which network you connect to. For a current list of testnet nodes, see the [Chromia Explorer](https://explorer.chromia.com/testnet/cluster/system).
* **Custom configuration:**
  + **Chains:** To connect to a particular chain or dapp, swap out `blockchainRid`. You can look up a chain’s `brid` in the [Chromia Explorer](https://explorer.chromia.com/testnet).
  + **Tokens:** To use a different token, set `assetId` to that token’s unique identifier. For instance, the `assetId` of tCHR on the Economy Chain is listed under 'Assets' in the [Economy Chain Explorer](https://explorer.chromia.com/testnet/090BCD47149FBB66F02489372E88A454E7A5645ADDE82125D40DF1EF0C76F874).
* **MetaMask integration:** MetaMask takes care of signing transactions securely, and the Chromia tools handle communication with the blockchain.

### 3. **Extend tools for real-time price fetching**

The `getLiveTokenPrice` helper retrieves live price data from CoinGecko. `index.ts` then wraps it so the assistant can call it.

* **Helper function in `tools.ts`:**

  typescript

  ```
  export const getLiveTokenPrice = async () => {
      const response = await fetch("https://api.coingecko.com/api/v3/simple/price?vs_currencies=usd&ids=chromaway&include_market_cap=true&include_24hr_vol=true&include_24hr_change=true");
      return await response.json();
  };
  ```
* **Integration in `index.ts`:**

  typescript

  ```
  const enhancedTools = {
      ...baseTools,
      getLiveTokenPrice: {
          name: "getLiveTokenPrice",
          description: "Fetches the current CHR price in USD.",
          parameters: z.object({}),
          execute: async () => formatPriceData(await getLiveTokenPrice()),
      },
  };
  ```

**Key points:**

* The **helper function** retrieves price data and is written to be reused.
* The **extended tool** exposes it to the assistant at runtime so users can ask about prices.

### 4. **Setting up the AI assistant and configuring its behavior**

The assistant answers user questions and carries out blockchain actions. You configure it through environment variables and shape its behavior with `MASTER_PROMPT` in `tools.ts`.

* **Assistant setup in `index.ts`:**

  typescript

  ```
  const openai = createOpenAI({
      baseURL: import.meta.env.VITE_AI_BASE_URL,
      apiKey: import.meta.env.VITE_AI_API_KEY,
  });
  ```
* **Behavior configuration in `tools.ts`:**

  typescript

  ```nolines
  export const MASTER_PROMPT = (priceData: string) => `You are CHRA, a helpful assistant for CHR tokens...
  `;
  ```

**Key points:**

* **Flexibility:** Any AI service compatible with the OpenAI client standard works with the assistant.
* **Customization:** Edit `MASTER_PROMPT` to give the assistant the style and tone your project needs.

The Chromia GOAT demo combines blockchain functionality and an AI assistant in a single application. Its modular design separates the blockchain tools from the configurable assistant, so you can reuse either part. Use it as a reference when you need secure transaction signing, blockchain asset handling, or a conversational AI interface in your own project.

Written for this site from Chromia’s public course. Code samples are the course’s own.

[← Previous**Explore the chat agent**](https://chromia.com/learn/chromia-goat-chat-agent/explore-agent/)[Course done →**Start building**](https://chromia.com/developers/#start)

On this page

* [Key components](#key-components)
