<div align="center">
  <a href="https://flare.network/" target="blank">
    <img src="https://content.flare.network/Flare-2.svg" width="300" alt="Flare Logo" />
  </a>
  <br />
  <strong>Typed periphery contract ABIs and wagmi hooks for Flare Network</strong><br />
  Auto-generated TypeScript helpers for seamless React, wagmi, and viem integration.
  <br />
  <a href="#overview">Overview</a>
  ·
  <a href="#installation">Installation</a>
  ·
  <a href="#usage">Usage</a>
  ·
  <a href="CONTRIBUTING.md">Contributing</a>
  ·
  <a href="SECURITY.md">Security</a>
  ·
  <a href="CHANGELOG.md">Changelog</a>
</div>
<br />

# Flare Periphery Wagmi Types

TypeScript contract types and React hooks for Flare periphery contracts, generated using the [wagmi CLI](https://wagmi.sh/cli).

This package is maintained as part of the official Flare developer tooling.
It provides a **safe, typed, and ergonomic** way to interact with Flare smart contracts from modern TypeScript and React applications.


## Overview

This package provides:

- **Typed contract ABIs**  
  Use directly with `viem` or wagmi’s generic hooks such as `useReadContract`.

- **Generated wagmi React hooks**  
  Contract-specific hooks (for example, `useReadIAssetManager`) generated via the wagmi CLI.

- **Network-scoped modules**  
  Contracts are grouped by [Flare networks](https://dev.flare.network/network/overview):
  - `flare` – Flare Mainnet
  - `songbird` – Songbird Canary Network
  - `coston2` – Flare Testnet
  - `coston` – Songbird Testnet

This enables strong typing, IDE autocompletion, and safer refactors across Flare-based dApps.

## Installation

```bash
npm install @flarenetwork/flare-wagmi-periphery-package
```

(Or `yarn add`, `pnpm add`, `bun add`.)

> ⚠️ This package is **ESM-only** (`"type": "module"`).  
> Ensure your tooling supports package exports.

## Package Structure

Generated files are published under `dist/contracts/**` and exposed via `package.json#exports`.

```
@flarenetwork/flare-wagmi-periphery-package/      # Root npm package directory
└── dist/                                         # Compiled output (ES modules)
    └── contracts/                                # Generated contract modules
        ├── index.(js|d.ts)                       # Root entry: re-exports all chains
        ├── flare/                                # Flare Mainnet contracts
        │   ├── index.(js|d.ts)                   # Re-exports all Flare contracts
        │   └── *.(js|d.ts)                       # Individual contract ABIs & types
        ├── songbird/                             # Songbird Canary Network contracts
        │   ├── index.(js|d.ts)                   # Re-exports all Songbird contracts
        │   └── *.(js|d.ts)                       # Individual contract ABIs & types
        ├── coston/                               # Songbird Testnet (Coston) contracts
        │   ├── index.(js|d.ts)                   # Re-exports all Coston contracts
        │   └── *.(js|d.ts)                       # Individual contract ABIs & types
        └── coston2/                              # Flare Testnet (Coston2) contracts
            ├── index.(js|d.ts)                   # Re-exports all Coston2 contracts
            └── *.(js|d.ts)                       # Individual contract ABIs & types
```

## Usage

### Import a single contract module

Each contract module typically exports at least a contract-specific ABI constant (e.g. `<contractNameAbi>`) plus derived TypeScript types.

```ts
import { <contractNameAbi> } from '@flarenetwork/flare-wagmi-periphery-package/contracts/<chain>/<ContractName>'
```

Replace `<chain>` with a supported network (e.g. `flare`, `songbird`, `coston`, `coston2`), `<ContractName>` with the generated filename (e.g. `IFtsoRegistry`), and `<contractNameAbi>` with the ABI export from that module (e.g. `IFtsoRegistryAbi`).

For example, if you want to import the FTSOV2 contract:

```ts
import { iFtsoV2Abi } from '@flarenetwork/flare-wagmi-periphery-package/contracts/coston2/IFtsoV2';
```

### Import contracts by network

You can import one of the Flare chains and get the contract ABI using it:

```ts
import { <chain> } from '@flarenetwork/flare-wagmi-periphery-package';

console.log(<chain>.<contractNameAbi>);
```

For example, if you want to import the FTSO contract interface ABI:

```ts
import { coston2 } from '@flarenetwork/flare-wagmi-periphery-package';

console.log(coston2.iFtsoAbi);
```

### Use with Wagmi (generic hooks)

This example illustrates how to use the Wagmi React hook to read the contract.
Similarly, you can interact with write functions.
Change the `<contractNameAbi>`, `<chain>`, `<contractAddress>`, `<readFunctionName>` and `<readFunctionArguments>` to the appropriate values.

```tsx
import { useReadContract } from 'wagmi'
import { <contractNameAbi> } from '@flarenetwork/flare-wagmi-periphery-package/contracts/<chain>/<ContractName>'

function MyComponent() {
  const { data, isLoading, isError } = useReadContract({
    address: <contractAddress>,
    abi: <contractNameAbi>,
    functionName: '<readFunctionName>',
    args: [<readFunctionArguments>],
  })

  if (isLoading) return <div>Loading...</div>
  if (isError) return <div>Error reading contract</div>
  
  return <div>{data?.toString()}</div>
}
```

For instance, here is an example reading lot size from the `AssetManagerFXRP`:

```tsx
import { useReadContract } from 'wagmi'
import { iAssetManagerAbi } from '@flarenetwork/flare-wagmi-periphery-package/contracts/coston2/IAssetManager'

function LotSizeReader() {
  const { data, isLoading, isError } = useReadContract({
    address: "0xc1Ca88b937d0b528842F95d5731ffB586f4fbDFA",
    abi: iAssetManagerAbi,
    functionName: 'lotSize',
    args: [],
  })

  if (isLoading) return <div>Loading...</div>
  if (isError) return <div>Error reading contract</div>
  
  return <div>{data?.toString()}</div>
}
```

### Use with Viem

This example shows how to set up a Viem client and use it to read data from a smart contract.
Similarly, you can interact with write functions.

**1. Create the Viem client configuration:**

```ts
// viem-client.ts
import { createPublicClient, http } from 'viem'
import { <viemChain> } from 'viem/chains'

export const publicClient = createPublicClient({
  chain: <viemChain>,
  transport: http(),
})
```

Note that [`viem/chains`](https://github.com/wevm/viem/blob/main/src/chains/index.ts) includes Flare network exports like this:

- `flare`: Flare Mainnet
- `flareTestnet`: Flare Testnet Coston2
- `songbird`: Songbird Canary Network
- `songbirdTestnet`: Songbird Testnet Coston

```ts
import { flare, flareTestnet, songbird, songbirdTestnet } from 'viem/chains'
```

**2. Use the client to read contract data:**

```ts
// read-contract.ts
import { publicClient } from '@/lib/viem-client'
import { <contractNameAbi> } from '@flarenetwork/flare-wagmi-periphery-package/contracts/<chain>/<ContractName>'

const CONTRACT_ADDRESS = '<contractAddress>'

const data = await publicClient.readContract({
  address: CONTRACT_ADDRESS,
  abi: <contractNameAbi>,
  functionName: '<readFunctionName>',
  args: [<readFunctionArguments>],
})

console.log('Contract data:', data)
```

For example, here is an example reading lot size from the `AssetManagerFXRP`:

```ts
// read-lot-size.ts
import { createPublicClient, http } from 'viem'
import { flareTestnet } from 'viem/chains'
import { iAssetManagerAbi } from '@flarenetwork/flare-wagmi-periphery-package/contracts/coston2/IAssetManager'

const client = createPublicClient({
  chain: flareTestnet,
  transport: http(),
})

const lotSize = await client.readContract({
  address: '0xc1Ca88b937d0b528842F95d5731ffB586f4fbDFA',
  abi: iAssetManagerAbi,
  functionName: 'lotSize',
  args: [],
})

console.log('Lot size:', lotSize.toString())
```

### Use with generated Wagmi hooks

This example shows how to set up wagmi config and use contract-specific hooks generated by the Wagmi CLI.

**1. Create the wagmi configuration file:**

```ts
// wagmi.ts
import { createConfig, http } from 'wagmi'
import { <wagmiChain> } from 'viem/chains'

export const config = createConfig({
  chains: [<wagmiChain>],
  transports: {
    [<wagmiChain>.id]: http(),
  },
})
```

**2. Set up the React providers:**

```tsx
// providers.tsx
'use client'

import { WagmiProvider } from 'wagmi'
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { config } from '@/lib/wagmi'
import { ReactNode, useState } from 'react'

export function Providers({ children }: { children: ReactNode }) {
  const [queryClient] = useState(() => new QueryClient())

  return (
    <WagmiProvider config={config}>
      <QueryClientProvider client={queryClient}>
        {children}
      </QueryClientProvider>
    </WagmiProvider>
  )
}
```

**3. Use the generated contract-specific hook in a component:**

```tsx
// LotSizeComponent.tsx
'use client'

import { useReadIAssetManager } from '@flarenetwork/flare-wagmi-periphery-package/contracts/coston2/IAssetManager'

const CONTRACT_ADDRESS = '0xc1Ca88b937d0b528842F95d5731ffB586f4fbDFA'

export default function LotSizeComponent() {
  const { data, isError, isLoading, error } = useReadIAssetManager({
    address: CONTRACT_ADDRESS,
    functionName: 'lotSize',
  })

  if (isLoading) {
    return <div>Loading lotSize...</div>
  }

  if (isError) {
    return (
      <div style={{ color: 'red' }}>
        Error reading lotSize: {error?.message || 'Unknown error'}
      </div>
    )
  }

  return (
    <div>
      <p><strong>Address:</strong> {CONTRACT_ADDRESS}</p>
      <p><strong>lotSize:</strong> {data?.toString() || 'N/A'}</p>
    </div>
  )
}
```

### Example with Flare Contracts Registry

```ts
import { createPublicClient, http } from 'viem'
import { flare } from 'viem/chains'
import { flareContractRegistryAbi } from '@flarenetwork/flare-wagmi-periphery-package/contracts/flare/FlareContractRegistry'

// Flare Contracts Registry https://dev.flare.network/network/guides/flare-contracts-registry/
const FLARE_CONTRACT_REGISTRY_ADDRESS = '0xaD67FE66660Fb8dFE9d6b1b4240d8650e30F6019';

const client = createPublicClient({
  chain: flare,
  transport: http(),
});

const ftsov2Address = await client.readContract({
  address: FLARE_CONTRACT_REGISTRY_ADDRESS,
  abi: flareContractRegistryAbi,
  functionName: 'getContractAddressByName',
  args: ['FtsoV2'],
});

console.log('FTSOV2 address:', ftsov2Address);
```

## Contributing / Security

- See [CONTRIBUTING.md](CONTRIBUTING.md)
- See [SECURITY.md](SECURITY.md)
- See [CHANGELOG.md](CHANGELOG.md)
