# Events and Function chaining

This page shows how to link your Mimic functions by **emitting and listening to custom events**. You’ll learn the full flow:

1. **Emitting an event** from a function
2. Creating an event trigger to **trigger another function** from the event
3. **Reading the event data** in the triggered function

> Pre-reqs: You’ve already read the basic function guide and can `mimic codegen`, `mimic compile`, and `mimic deploy`.

***

### Emit a custom event

**Goal:** Add an event with arbitrary information to an operation so it's emitted on-chain when the intent is executed.

Events are attached to **operations** (not to the intent itself), so you call `.addEvent()` on any operation builder — `EvmCallBuilder`, `SwapBuilder`, or `TransferBuilder` — before calling `.send()`.

```typescript
import { Address, Bytes, ChainId, Ethereum, EvmCallBuilder, evm, EvmEncodeParam, TokenAmount } from '@mimicprotocol/lib-ts'

export default function main(): void {
  const topic = evm.keccak('First function')
  const data = evm.encode([EvmEncodeParam.fromValue('address', '0xSomeAddress')])
  const fee = TokenAmount.fromStringDecimal(Ethereum.USDC, '1')

  EvmCallBuilder.forChain(ChainId.ETHEREUM)
    .addCall(Address.fromString('0xContractAddress'), callData)
    .addEvent(Bytes.fromHexString(topic), Bytes.fromHexString(data))
    .addUser('0xSmartAccountAddress')
    .send(fee)
}
```

The same `.addEvent()` method is available on `SwapBuilder` and `TransferBuilder`:

```typescript
SwapBuilder.forChains(ChainId.ETHEREUM, ChainId.OPTIMISM)
  .addTokenInFromStringDecimal(Ethereum.USDC, '1000')
  .addTokenOutFromStringDecimal(Optimism.USDC, '990', recipient)
  .addEvent(Bytes.fromHexString(topic), Bytes.fromHexString(data))
  .send()
```

***

### Trigger a function from a custom event

**Goal:** Automatically execute a second function every time an intent from the first function is executed.

```typescript
import { Chains, Client, TriggerType } from '@mimicprotocol/sdk'
import { AbiCoder, keccak256, toUtf8Bytes } from 'ethers'

async function main(): Promise<void> {
  const MIMIC_PROTOCOL_SETTLER = '0xSettlerAddress'
  const INTENT_EXECUTED_TOPIC = '0xee2c98c99b683f71058b8744fea294a411482f07d55c98b392917e9286f22f13'
  const USER_TOPIC = AbiCoder.defaultAbiCoder().encode(['address'], ['0xUserAddress'])
  const FIRST_FUNCTION_TOPIC = keccak256(toUtf8Bytes('First function'))

  const config = {
    type: TriggerType.Event
    chainId: Chains.SomeChain,
    contract: MIMIC_PROTOCOL_SETTLER,
    topics: [
      [INTENT_EXECUTED_TOPIC],
      [USER_TOPIC],
      [FIRST_FUNCTION_TOPIC],
    ],
  }

  const client = new Client({ signer })
  await client.triggers.signAndCreate({ SECOND_FUNCTION_CID, config, ... })
}
```

**Notes**

* The code above is a backend script, not a function.
* This section shows how to trigger a function from a custom event. However, it's also possible to **trigger functions from any smart contract event**, such as ERC-20 token transfers.

***

### Read event data

**Goal:** Access information included in the event.

```typescript
import { Address, environment, evm } from '@mimicprotocol/lib-ts'
import { IntentExecutedEvent } from './types/Settler'

export default function main(): void {
  const trigger = environment.getContext().triggerPayload.getEventData()
  const event = IntentExecutedEvent.decode(trigger.topics, trigger.eventData)
  const str = evm.decode(new EvmDecodeParam('address', event.data.toHexString()))
  const someAddress = Address.fromString(str) // 0xSomeAddress
}
```

***

### Use case

For a complete use case using custom events, see [Bridge and invest in Aave](/use-cases/bridge-and-invest-in-aave.md), where one function transfers tokens between chains and emits an event, and another function reacts to that event by investing the bridged tokens.


---

# 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.mimic.fi/examples/events-and-function-chaining.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.
