> ## Documentation Index
> Fetch the complete documentation index at: https://docs.goldsky.com/llms.txt
> Use this file to discover all available pages before exploring further.

# On-chain FX & multi-currency corridors

> Index Circle StableFX settlement activity on Arc with Turbo, and publish FX rates and exposure controls with Compose.

The first wave of stablecoins was dollar-only. The next is multi-currency. [Circle's Arc](https://docs.goldsky.com/chains/supported-networks.md?chain=arc) ships with [Circle StableFX](https://www.circle.com/blog/introducing-circle-stablefx-and-circle-partner-stablecoins), an FX engine for USDC, EURC, and regional partner stablecoins. Quotes are priced offchain through RFQ. Trades settle onchain through Circle's **FxEscrow** contract on Arc.

Onchain settlement gives a treasury something it has never had: every trade's funding and payout, for every currency pair, as a queryable event stream. This guide turns that stream into FX flow analytics, a published rate oracle, and exposure controls.

## What you'll build

```mermaid theme={"dark"}
flowchart LR
    A[Circle StableFX FxEscrow on Arc] -->|trade events + token transfers| B[Turbo pipeline]
    B --> C[(FX warehouse)]
    C --> D[Flows per currency,<br/>corridor analytics]
    C --> E[Compose: publish FX rate oracle]
    C --> F[Compose: exposure / limit monitor]
```

## Step 1: Index settlement activity

FxEscrow's events record each trade's lifecycle: `TradeRecorded`, `TakerFunded`, `MakerDelegateFunded`, and `TradeStatusChanged`. They carry the trade ID and the parties, but not the currencies or amounts. The money moves as ordinary ERC-20 `Transfer` events into and out of FxEscrow. The pipeline below captures both and writes them to two ClickHouse tables that you join on `transaction_hash`.

FxEscrow addresses (from [Arc's contract addresses](https://docs.arc.io/arc/references/contract-addresses)):

| Network | FxEscrow |
| :- | :- |
| Arc mainnet | `0xe2E5F173576B513d994073CCbDaCBE027d43DFe6` |
| Arc testnet | `0xd68256f4D69C6BbEcB873D8588AE0Dc6B8E22E10` |

```yaml stablefx-settlements.yaml expandable theme={"dark"}
name: stablefx-settlements
resource_size: s

sources:
  fx_escrow_logs:
    type: dataset
    dataset_name: arc_testnet.raw_logs
    version: 1.0.0
    start_at: latest
    filter: address = '0xd68256f4d69c6bbecb873d8588ae0dc6b8e22e10'

  # ERC-20 Transfer events where FxEscrow is the sender or the receiver
  escrow_transfer_logs:
    type: dataset
    dataset_name: arc_testnet.raw_logs
    version: 1.0.0
    start_at: latest
    filter: topics LIKE '0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef%' AND topics LIKE '%d68256f4d69c6bbecb873d8588ae0dc6b8e22e10%'

transforms:
  fx_decoded:
    type: sql
    primary_key: id
    sql: |
      SELECT
        id,
        _gs_log_decode(
          '[{"type":"event","anonymous":false,"name":"TradeRecorded","inputs":[{"name":"id","type":"uint256","indexed":true},{"name":"quoteId","type":"bytes32","indexed":true}]},{"type":"event","anonymous":false,"name":"TakerFunded","inputs":[{"name":"id","type":"uint256","indexed":true},{"name":"taker","type":"address","indexed":true}]},{"type":"event","anonymous":false,"name":"MakerDelegateFunded","inputs":[{"name":"id","type":"uint256","indexed":true},{"name":"makerDelegatedFunder","type":"address","indexed":true},{"name":"makerDelegatedRecipient","type":"address","indexed":true}]},{"type":"event","anonymous":false,"name":"TradeStatusChanged","inputs":[{"name":"id","type":"uint256","indexed":true},{"name":"actor","type":"address","indexed":true},{"name":"newStatus","type":"uint8","indexed":false}]}]',
          topics,
          data
        ) AS decoded,
        block_timestamp,
        transaction_hash,
        _gs_op
      FROM fx_escrow_logs

  fx_trade_events:
    type: sql
    primary_key: id
    sql: |
      SELECT
        id,
        decoded.event_signature AS event,
        decoded.event_params[1] AS trade_id,
        decoded.event_params[2] AS party,        -- taker, funder, actor, or quoteId
        decoded.event_params[3] AS detail,       -- delegated recipient or new status
        to_timestamp(block_timestamp) AS at,
        transaction_hash,
        _gs_op
      FROM fx_decoded
      WHERE decoded IS NOT NULL

  transfer_decoded:
    type: sql
    primary_key: id
    sql: |
      SELECT
        id,
        address AS token,
        _gs_log_decode(
          '[{"type":"event","anonymous":false,"name":"Transfer","inputs":[{"name":"from","type":"address","indexed":true},{"name":"to","type":"address","indexed":true},{"name":"value","type":"uint256","indexed":false}]}]',
          topics,
          data
        ) AS decoded,
        block_timestamp,
        transaction_hash,
        _gs_op
      FROM escrow_transfer_logs
      -- Arc mirrors every USDC transfer as an 18-decimal native-balance event from this address; skip it to avoid double counting
      WHERE address <> '0xfffffffffffffffffffffffffffffffffffffffe'
        AND SPLIT_INDEX(topics, ',', 3) IS NULL  -- ERC-20 only; ERC-721 Transfer has a 4th topic

  fx_escrow_transfers:
    type: sql
    primary_key: id
    sql: |
      SELECT
        id,
        token,
        decoded.event_params[1] AS from_address,
        decoded.event_params[2] AS to_address,
        CAST(decoded.event_params[3] AS DECIMAL(38, 0)) AS amount,  -- raw token units
        to_timestamp(block_timestamp) AS at,
        transaction_hash,
        _gs_op
      FROM transfer_decoded
      WHERE decoded IS NOT NULL

sinks:
  trade_events_out:
    type: clickhouse
    from: fx_trade_events
    table: fx_trade_events
    secret_name: MY_CLICKHOUSE
    primary_key: id
  escrow_transfers_out:
    type: clickhouse
    from: fx_escrow_transfers
    table: fx_escrow_transfers
    secret_name: MY_CLICKHOUSE
    primary_key: id
```

For mainnet, change `arc_testnet` to `arc_mainnet` and use the mainnet FxEscrow address, in lowercase, in both filters.

> [!NOTE]
>
> The ABI covers the four events FxEscrow emits during a trade. The decoder drops any event that isn't in it, so add new events to the ABI if Circle adds them. Amounts are raw token units. Divide by the token's `decimals()`: USDC and EURC use 6.

## Step 2: Analyze FX flows

With trade events and token movements in your warehouse, flows per currency are SQL:

```sql theme={"dark"}
-- Funding into and payouts out of FxEscrow per token, last hour
SELECT
  token,
  sumIf(amount, to_address   = '0xd68256f4d69c6bbecb873d8588ae0dc6b8e22e10') AS funded_in,
  sumIf(amount, from_address = '0xd68256f4d69c6bbecb873d8588ae0dc6b8e22e10') AS paid_out,
  count()                                                                    AS transfers
FROM fx_escrow_transfers
WHERE at > now() - INTERVAL 1 HOUR
GROUP BY token;
```

To tie a token movement to a trade, join on the transaction hash. Funding transfers share a transaction with the `TakerFunded` or `MakerDelegateFunded` event for that trade:

```sql theme={"dark"}
SELECT e.trade_id, e.event, t.token, t.from_address, t.amount
FROM fx_escrow_transfers AS t
JOIN fx_trade_events AS e USING (transaction_hash)
WHERE e.event IN ('TakerFunded', 'MakerDelegateFunded');
```

From the same tables you get **corridor flows** (net USDC→EURC movement), **counterparty league tables**, and the funding legs of each trade, grouped by `trade_id`. Maintain live per-token totals with the [PostgreSQL aggregate sink](https://docs.goldsky.com/turbo-pipelines/sinks/postgres-aggregate.md).

## Step 3: Publish an FX rate oracle

Other contracts and apps need an FX rate. A scheduled [Compose](https://docs.goldsky.com/compose/introduction.md) task reads the rate your desk computes from these flows and publishes it onchain, the same mechanism as the [NAV oracle](https://docs.goldsky.com/compose/guides/build-a-nav-oracle.md), pointed at an FX pair.

```typescript src/tasks/publish-fx-rate.ts theme={"dark"}
import type { TaskContext, Chain } from "compose";

// Publish to the same network your StableFX pipeline reads from (Arc). Arc
// isn't a built-in Edge RPC chain yet, so define it as a custom chain; swap for
// evm.chains.<name> once it's available on Edge. Note Arc pays gas in USDC.
const ARC_CHAIN: Chain = {
  id: 5042002, // Arc testnet
  name: "Arc Testnet",
  testnet: true,
  nativeCurrency: { name: "USD Coin", symbol: "USDC", decimals: 6 },
  rpcUrls: {
    default: { http: ["https://rpc.testnet.arc.io"] },
    public: { http: ["https://rpc.testnet.arc.io"] },
  },
  blockExplorers: { default: { name: "Arc Explorer", url: "https://explorer.testnet.arc.io" } },
};

export async function main(context: TaskContext) {
  const { fetch, evm } = context;

  const rate = await fetch<{ pair: string; rate: number; asOf: string }>(
    "https://fx.example.com/rate?pair=USDC-EURC",
  );

  const wallet = await evm.wallet({ name: "fx-oracle", sponsorGas: true });
  await wallet.writeContract(
    ARC_CHAIN,
    "0xFX_ORACLE",
    "updateRate(bytes32,uint256,uint64)",
    [
      "0x555344432d45555243", // "USDC-EURC"
      BigInt(Math.round(rate.rate * 1e18)),
      BigInt(Math.floor(new Date(rate.asOf).getTime() / 1000)),
    ],
  );

  return { pair: rate.pair, rate: rate.rate };
}
```

## Step 4: Monitor exposure and enforce limits

FX desks live and die by position limits. Because you have every funding and payout, net exposure per currency is a running sum, and a [Compose](https://docs.goldsky.com/compose/introduction.md) task can watch it and act (alert, hedge, or halt quoting) when a limit is breached. Compose's [durable execution](https://docs.goldsky.com/compose/introduction.md) guarantees the control fires, and every decision is [traced](https://docs.goldsky.com/compose/debugging.md) for the desk's risk review. This is a live version of the [circuit-breaker pattern](https://docs.goldsky.com/solutions/treasury-and-reserves.md#circuit-breaker-pattern).

## Business outcomes

* **Every settlement is data**: funding and payout flows per currency and corridor, not a dealer's end-of-day summary.
* **Multi-currency treasury**: real-time positions across USD, EUR, and regional stablecoins in one warehouse.
* **A rate you can publish and defend**: an onchain FX oracle sourced from actual settlements, with an audit trail.
* **Automated limit enforcement**: exposure breaches trigger controls in seconds.

## Resources

* [Circle StableFX](https://www.circle.com/blog/introducing-circle-stablefx-and-circle-partner-stablecoins)
* [StableFX technical guide](https://developers.circle.com/stablefx/concepts/technical-guide)
* [Arc contract addresses](https://docs.arc.io/arc/references/contract-addresses)
* [Build a multi-chain NAV oracle](https://docs.goldsky.com/compose/guides/build-a-nav-oracle.md)
* [ClickHouse sink](https://docs.goldsky.com/turbo-pipelines/sinks/clickhouse.md)

Can't find what you're looking for? Reach out to us at [support@goldsky.com](mailto:support@goldsky.com) for help.


## Related topics

- [Payments & fintech on Goldsky](https://docs.goldsky.com/solutions/payments-fintech.md)
- [Build a multi-chain NAV oracle](https://docs.goldsky.com/compose/guides/build-a-nav-oracle.md)
- [Feeds: ready-made onchain datasets](https://docs.goldsky.com/feeds.md)
- [Balances](https://docs.goldsky.com/feeds/api/balances.md)
- [Build a binary prediction market](https://docs.goldsky.com/compose/guides/build-a-prediction-market.md)
