npm package: @gasfree-kit/react
Description: React hooks for gasless USDT transfers — powered by gasfree-kit
Latest version: 0.2.2

# @gasfree-kit/react

React hooks for gasless USDT transfers across EVM and TON networks.

Wrap your app in a provider, call a hook, and get multi-chain balance discovery, gasless transfers, cross-chain bridging, and payment links — all with zero gas costs for your users.

## How It Works

```
 ┌──────────────────────────────────────────────────────────┐
 │                    Your React App                        │
 │                                                          │
 │   <GasfreeProvider config={...}>                         │
 │     <App />                                              │
 │   </GasfreeProvider>                                     │
 └────────────────────────────┬─────────────────────────────┘
                              │
        ┌─────────────────────┼─────────────────────┐
        │                     │                     │
        v                     v                     v
 ┌──────────────┐   ┌─────────────────┐   ┌────────────────┐
 │ useBalance() │   │ useIntent()     │   │useTonTransfer()│
 │              │   │ useGasless      │   │                │
 │ EVM + TON    │   │   Transfer()    │   │ TON gasless    │
 │ combined     │   │ usePayment      │   │ relay          │
 │ balances     │   │   Link()        │   │                │
 └──────┬───────┘   └────────┬────────┘   └───────┬────────┘
        │                    │                     │
        v                    v                     v
 ┌──────────────┐   ┌────────────────┐   ┌────────────────┐
 │ @gasfree-kit │   │ @gasfree-kit/  │   │ @gasfree-kit/  │
 │ /intent      │   │ intent         │   │ ton-gasless    │
 │ (discovery)  │   │ (plan+execute) │   │ (relay)        │
 └──────────────┘   └────────────────┘   └────────────────┘
```

## Prerequisites

This package depends on:

- [`@gasfree-kit/core`](../core/README.md) for chain metadata, types, and errors
- [`@gasfree-kit/intent`](../intent/README.md) for EVM balance discovery, route planning, and execution
- [`@gasfree-kit/ton-gasless`](../ton-gasless/README.md) for TON gasless transfers

All are installed automatically as dependencies.

## Installation

```bash
npm install @gasfree-kit/react
```

Required peer dependencies:

```bash
npm install react @tanstack/react-query
```

Optional peer dependencies (for wagmi wallet integration):

```bash
npm install wagmi viem
```

## Quick Start

### EVM — gasless transfer in 10 lines

```tsx
import { GasfreeProvider, useGaslessTransfer } from '@gasfree-kit/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

function PayButton() {
  const { transfer, isLoading, receipt } = useGaslessTransfer();

  return (
    <button
      disabled={isLoading}
      onClick={() => transfer({ to: '0xRecipient...', amount: '50.00' })}
    >
      {isLoading ? 'Sending...' : 'Pay 50 USDT'}
    </button>
  );
}

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      <GasfreeProvider
        address="0xSender..."
        config={{
          evm: {
            chains: ['base', 'arbitrum', 'optimism'],
            signer: { type: 'seedPhrase', seedPhrase: 'your seed phrase ...' },
            bundlerUrl: 'https://your-bundler.example.com',
            paymasterUrl: 'https://your-paymaster.example.com',
            isSponsored: true,
            sponsorshipPolicyId: 'your-policy-id',
          },
        }}
      >
        <PayButton />
      </GasfreeProvider>
    </QueryClientProvider>
  );
}
```

### TON — gasless transfer

```tsx
import { GasfreeProvider, useTonTransfer } from '@gasfree-kit/react';

function TonPayButton() {
  const { transfer, isLoading, result } = useTonTransfer();

  return (
    <button
      disabled={isLoading}
      onClick={() => transfer({ to: 'UQRecipient...', amount: '25.00' })}
    >
      {isLoading ? 'Sending...' : 'Pay 25 USDT (TON)'}
    </button>
  );
}

// In your provider setup:
<GasfreeProvider
  config={{
    ton: {
      clientConfig: {
        tonCenterUrl: 'https://toncenter.com/api/v2/jsonRPC',
        tonCenterApiKey: 'your-key',
        tonApiUrl: 'https://tonapi.io',
        tonApiSecretKey: 'your-secret',
      },
      seedPhrase: 'your ton seed phrase ...',
    },
  }}
>
  <TonPayButton />
</GasfreeProvider>;
```

### Multi-network — EVM + TON together

```tsx
<GasfreeProvider
  address="0xEvmAddress..."
  config={{
    evm: {
      chains: ['base', 'arbitrum'],
      signer: { type: 'passkey', credential },
      bundlerUrl: '...',
      paymasterUrl: '...',
      isSponsored: true,
      sponsorshipPolicyId: '...',
    },
    ton: {
      clientConfig: { tonCenterUrl, tonCenterApiKey, tonApiUrl, tonApiSecretKey },
      seedPhrase: '...',
    },
  }}
>
  <App />
</GasfreeProvider>
```

## Hooks

### useBalance

Discover USDT balances across all configured networks. Works in read-only mode — no signer required for EVM balance discovery.

```tsx
const { balances, isLoading, error, refetch } = useBalance();

if (balances) {
  console.log(balances.total); // "130.00" (grand total across all networks)
  console.log(balances.evm?.total); // "100.00" (EVM total)
  console.log(balances.evm?.chains); // [{ chain: 'base', balance: '75.00', ... }, ...]
  console.log(balances.ton?.balance); // "30.00"
}
```

Accepts an optional address override: `useBalance('0xOtherAddress...')`.

Automatically refetches based on `balanceCacheTTL` (default 15 seconds).

### useIntent

Full EVM intent lifecycle — plan, execute, or one-shot send. Requires a signer in the provider config.

```tsx
const {
  planIntent,
  executeIntent,
  sendIntent,
  plan,
  receipt,
  events,
  isPlanning,
  isExecuting,
  error,
  reset,
} = useIntent();

// Two-step: plan then confirm
const plan = await planIntent({ to: '0x...', amount: '50.00' });
console.log(plan.route); // "direct" | "bridge" | "aggregate"
console.log(plan.estimatedFee); // "0" (sponsored)

const receipt = await executeIntent(plan);
console.log(receipt.status); // "completed"

// Or one-shot
const receipt = await sendIntent({ to: '0x...', amount: '50.00' });
```

The `from` address is auto-filled from the provider context.

Track execution progress via the `events` array — events are appended in real-time as steps start, complete, or fail.

### useGaslessTransfer

Simplified wrapper around `useIntent().sendIntent()`. The happy-path hook for one-shot EVM transfers.

```tsx
const { transfer, receipt, isLoading, error, events, reset } = useGaslessTransfer();

const receipt = await transfer({ to: '0x...', amount: '25.00' });
if (receipt.status === 'completed') {
  alert('Payment sent!');
}
```

### useTonTransfer

Gasless USDT transfers on the TON network. Requires TON configuration in the provider.

```tsx
const { transfer, estimateFee, checkBalance, result, isLoading, error, reset } = useTonTransfer();

// Estimate fee first
const fee = await estimateFee({ to: 'UQ...', amount: '10.00' });
console.log(`Fee: ${fee} USDT`);

// Check balance
const { balance } = await checkBalance();
console.log(`Balance: ${balance} USDT`);

// Execute transfer
const result = await transfer({ to: 'UQ...', amount: '10.00' });
if (result.success) {
  console.log(`TX: ${result.transactionHash}`);
}
```

### usePaymentLink

Generate, parse, and execute payment links. Supports both EVM and TON networks.

Pass your app's payment page URL as the base URL — the hook appends query params to it.

```tsx
const { generateLink, parseLink, pay, receipt, isLoading, error } =
  usePaymentLink('https://myapp.com/pay');

// Merchant side — generate a link
const url = generateLink({
  to: '0xMerchant...',
  amount: '50.00',
  metadata: { orderId: 'order-123' },
});
// https://myapp.com/pay?to=0xMerchant...&amount=50.00&meta=eyJvcmRlcklkIjoib3JkZXItMTIzIn0=

// TON payment link
const tonUrl = generateLink({
  to: 'UQRecipient...',
  amount: '25.00',
  network: 'ton',
});

// Payer side — parse and pay
const params = parseLink(window.location.href);
if (params) {
  const receipt = await pay(params);
}
```

### useGasfree

Access the raw provider context. Useful for building custom hooks or checking capabilities.

```tsx
const { intent, config, address, canExecuteEvm, tonConfig, canExecuteTon } = useGasfree();
```

## Provider Configuration

```tsx
<GasfreeProvider
  address="0x..."        // EVM wallet address (required for EVM hooks)
  config={{
    evm: { ... },        // EVM config (optional — omit to disable EVM)
    ton: { ... },        // TON config (optional — omit to disable TON)
    balanceCacheTTL: 15000,  // balance cache TTL in ms (default: 15s)
  }}
>
```

### EVM Config

| Parameter             | Type                                   | Default  | Description                                    |
| --------------------- | -------------------------------------- | -------- | ---------------------------------------------- |
| `chains`              | `EvmChain[]`                           | Required | EVM chains to operate on                       |
| `signer`              | `IntentSigner`                         | -        | Omit for read-only mode (balance queries only) |
| `bundlerUrl`          | `string`                               | Required | ERC-4337 bundler endpoint                      |
| `paymasterUrl`        | `string`                               | Required | Paymaster endpoint                             |
| `isSponsored`         | `boolean`                              | Required | Whether gas is sponsored                       |
| `sponsorshipPolicyId` | `string`                               | -        | Required when `isSponsored` is `true`          |
| `paymasterAddress`    | `string`                               | -        | Paymaster contract (non-sponsored mode)        |
| `chainOverrides`      | `Partial<Record<EvmChain, overrides>>` | -        | Per-chain RPC, bundler, paymaster overrides    |
| `bridgeConfig`        | `{ enabled: boolean, ... }`            | disabled | Must be `{ enabled: true }` for bridge routes  |

### TON Config

| Parameter        | Type                     | Default    | Description                      |
| ---------------- | ------------------------ | ---------- | -------------------------------- |
| `clientConfig`   | `TonGaslessClientConfig` | Required   | TON network client configuration |
| `seedPhrase`     | `string`                 | Required   | Seed phrase for the TON wallet   |
| `derivationPath` | `string`                 | `"0'/0/0"` | Custom derivation path           |

## Signer Types

The EVM hooks support two signer types:

| Signer type | `type` value   | Frontend-friendly? | Supports bridge? |
| ----------- | -------------- | ------------------ | ---------------- |
| Passkey     | `'passkey'`    | Yes (biometric)    | No               |
| Seed phrase | `'seedPhrase'` | Custodial only     | Yes              |

For frontend apps, prefer passkey signing (WebAuthn / biometric). Seed phrase signers should only be used in custodial backends or server-side rendering.

## Main Exports

| Export               | What it does                                                                                                |
| -------------------- | ----------------------------------------------------------------------------------------------------------- |
| `GasfreeProvider`    | React context provider for SDK configuration                                                                |
| `useGasfree`         | Access raw provider context (intent instance, config, status)                                               |
| `useBalance`         | Combined EVM + TON balance discovery via react-query                                                        |
| `useIntent`          | Full EVM intent lifecycle (plan, execute, send)                                                             |
| `useGaslessTransfer` | Simplified one-shot EVM transfer                                                                            |
| `useTonTransfer`     | TON gasless transfer, fee estimation, balance check                                                         |
| `usePaymentLink`     | Payment link generation, parsing, and execution                                                             |
| Types                | `GasfreeProviderConfig`, `EvmConfig`, `TonConfig`, `CombinedBalances`, `PaymentLinkParams`, etc.            |
| Re-exported types    | `IntentRequest`, `ExecutionPlan`, `IntentReceipt`, `BalanceMap`, `EvmChain`, `TonGaslessClientConfig`, etc. |

## License

MIT