# Air Kit

This SDK is part of the [Moca Network](https://moca.network/) offering and provides a convenient way to add Air Account Login, Air Id Minting and Air Account Management to your DApp.

## ⚡ Quick Start

```shell
npm install @mocanetwork/airkit
```

### Initialize & Login

```ts
import AirService, { BUILD_ENV } from "@mocanetwork/airkit";

const service = new AirService({
  partnerId: YOUR_PARTNER_ID,
});
await service.init({
  buildEnv: BUILD_ENV.SANDBOX,
  enableLogging: true,
});
await embed.login();
```

The AirService creates an iframe that loads the login flow and sets up communication streams between
the iframe and the DApp's javascript context.

## 🔗 Installation

### Bundling

This module is distributed in 3 formats

- `esm` build `dist/airkit.esm.js` is es6 format
- `commonjs` build `dist/airkit.cjs.js` in es5 format
- `umd` build `dist/airkit.umd.min.js` in es5 format without polyfilling corejs minified

By default, the appropriate format is used for your specified use case.
You can use a different format (if you know what you're doing) by referencing the correct file.

### Dynamic Import

If not already, some node libraries need to be polyfilled.

<details>
  <summary>Webpack</summary>
  Install dev packages:

```shell
npm install --save-dev node-polyfill-webpack-plugin
```
Add following to your Webpack config:

```js
const NodePolyfillPlugin = require("node-polyfill-webpack-plugin");

module.exports = {
  webpack: {
    plugins: [
      new NodePolyfillPlugin({
        additionalAliases: [
          "buffer",
          "crypto",
          "assert",
          "http",
          "https",
          "os",
          "url",
          "zlib",
          "stream",
          "_stream_duplex",
          "_stream_passthrough",
          "_stream_readable",
          "_stream_writable",
          "_stream_transform",
          "process",
        ],
      }),
    ],
  },
};
```
</details>

<details>
  <summary>Vite</summary>
Install dev packages:

```shell
npm install --save-dev vite-plugin-node-polyfills
```
Add following to your Vite config:

```js
import react from "@vitejs/plugin-react";
import { defineConfig } from "vite";
import { nodePolyfills } from "vite-plugin-node-polyfills";

// https://vitejs.dev/config/
export default defineConfig({
  plugins: [
    react(),
    nodePolyfills({
      include: [
        "buffer",
        "crypto",
        "assert",
        "http",
        "https",
        "os",
        "url",
        "zlib",
        "stream",
        "_stream_duplex",
        "_stream_passthrough",
        "_stream_readable",
        "_stream_writable",
        "_stream_transform",
      ],
    }),
  ],
});
```
</details>

## Usage
Once the SDK is installed and the `AirService` successfully initialized, it can be used to authenticate users. Further, the native provider given by the embed instance can be used to let users interact with the blockchain.

### Live Examples

- **[Deployed Example App](https://developers.sandbox.air3.com/example)** - See Air Kit in action with wagmi integration
- **[Source Code](https://github.com/MocaNetwork/airkit-example)** - Complete React + TypeScript example

### Signing Example

<details open>
  <summary>Using ethers</summary>

```ts
const ethProvider = new BrowserProvider(service.provider, 'any');
const signer = await ethProvider.getSigner();
const signedMessage = await signer.signMessage('Your message');
```
</details>

<details>
  <summary>Using web3</summary>

```ts
const web3 = new Web3(service.provider);
const signedMessage = await web3.eth.personal.sign(
    'Your message',
    eoaAccount,
    'password',
);
```
</details>

### Sending Transaction Example

<details open>
  <summary>Using ethers</summary>

```ts
const transactionParams: TransactionRequest = {...};
const ethProvider = new BrowserProvider(service.provider, 'any');
const signer = await ethProvider.getSigner();
const response = signer.sendTransaction(transactionParams);
```
</details>

<details>
  <summary>Using web3</summary>

```ts
const transactionParams: Transaction = {...};
const web3 = new Web3(service.provider);
const response = await web3.eth.sendTransaction(transactionParams);
```
</details>

## Errors

Every `AirService` method rejects with an `AirKitError`:

| Field | Meaning |
|---|---|
| `code` | stable `domain/reason` string to switch on, e.g. `"auth/user-cancelled"` |
| `category` | `"user"` · `"session"` · `"config"` · `"network"` · `"internal"`, for coarse handling |
| `message` | developer-facing English; don't show it to users, and expect it to change |
| `eventId` | quote it to Air support to locate the failure |
| `data` | structured details for some codes (`credential/verification-failed` → `{ status }`) |

```ts
import { AirKitError } from "@mocanetwork/airkit";

try {
  await service.login();
} catch (err) {
  if (!(err instanceof AirKitError)) throw err;
  switch (err.category) {
    case "user":    // cancelled, rejected, or input the Air UI already explained
      if (err.code === "auth/user-cancelled") return;
      break;
    case "session": // mint a fresh partner token / sign in again
      break;
    case "config":  // an integration problem — fix the call or partner settings
    case "network": // retryable
    case "internal":
      console.error(err.code, err.eventId);
  }
}
```

**Codes by category**

- **user** — `auth/user-cancelled`, `auth/account-deletion-pending`, `wallet/user-rejected`, `wallet/insufficient-funds`, `wallet/smart-account-not-deployed`, `wallet/mfa-required`, `wallet/swap-to-onramp`, `wallet/pin-recovery-started`, `wallet/quote-unavailable`, `credential/revoked`, `credential/paused`, `credential/identity-not-derivable`, `credential/not-eligible`, `credential/program-not-found`, `credential/verification-failed`, `recovery/lock-exceeded`, `user/input-rejected`, `user/unsupported-environment`, `window/blocked`, `window/closed`
- **session** — `sdk/not-logged-in`, `auth/partner-token-expired`, `auth/unauthorized`, `credential/session-expired`
- **config** — `sdk/not-initialized`, `sdk/already-initializing`, `config/invalid`, `wallet/unsupported-chain`, `wallet/method-not-supported`, `wallet/invalid-params`, `wallet/permission-not-enabled`, `wallet/unauthorized`, `credential/invalid-request`, `recovery/not-configured`
- **network** — `credential/issuer-not-ready`, `network/channel-closed`, `network/timeout`, `network/unavailable`
- **internal** — `wallet/transaction-rejected`, `credential/issue-failed`, `credential/verify-failed`, `internal/unknown`

New codes may be added in minor releases; always keep a `default` / category fallback.

**Provider errors.** `service.provider.request(...)` rejects with an EIP-1193 `ProviderRpcError` (`code` 4001 user rejected, 4100 unauthorized, 4200 unsupported method, 4900 disconnected, 4902 unsupported chain, -32602 invalid params, -32603 internal, …), so wagmi / viem / ethers handle it as usual. When the failure came from Air, `error.data.air` holds the same `{ code, category, message, eventId }` as above.

**Migrating from `AirServiceError` / `err.name`.** `AirServiceError` is a deprecated alias of `AirKitError`, and `err.name` still returns the previous name (`"USER_CANCELLED"`, `"CLIENT_ERROR"`, …), so existing checks keep working. Switch to `code` / `category`; the alias and the legacy `name` values are removed in the next major. Like every other `show*UI()` method, `showReceiveUI()` now rejects with `auth/user-cancelled` when the user closes it (it used to resolve).
