# @quantabit/sdk-config

QuantaBit SDK unified config management. All SDKs share this config — **modify once, apply everywhere**.

## Features

- 🔧 **Unified Configuration** - All SDKs share API URL, timeout, and other settings
- 🌍 **Environment Presets** - One-click switching between dev, staging, and production
- 🔄 **Dynamic Updates** - Runtime configuration changes supported
- ⚛️ **React Hook** - Convenient `useSDKConfig` Hook
- 🔐 **Token Management** - Unified authentication token storage and management
- 📝 **Logging System** - Configurable log levels

## Installation

```bash
npm install @quantabit/sdk-config
# or
yarn add @quantabit/sdk-config
```

## Quick Start

### 1. Initialize Configuration at App Startup

```javascript
// app/layout.tsx or main.jsx
import { initConfig } from "@quantabit/sdk-config";

// Use custom configuration
initConfig({
  apiBaseUrl: "https://api.yoursite.com/api/v1",
  timeout: 15000,
  debug: process.env.NODE_ENV !== "production",
});

// Or use environment preset
import { initWithEnvironment } from "@quantabit/sdk-config";
initWithEnvironment("production");
```

### 2. Using Hooks in Components

```jsx
import { useSDKConfig } from "@quantabit/sdk-config";

function SettingsPanel() {
  const { config, setApiBaseUrl } = useSDKConfig();

  return (
    <div>
      <p>Current API: {config.apiBaseUrl}</p>
      <button onClick={() => setApiBaseUrl("https://new-api.com")}>
        Switch API
      </button>
    </div>
  );
}
```

### 3. Using in Other SDKs

```javascript
// Internal use by other SDKs
import { getConfig, buildApiUrl, getToken } from "@quantabit/sdk-config";

async function fetchData() {
  const config = getConfig();
  const url = buildApiUrl("/users/me");
  const token = getToken();

  const response = await fetch(url, {
    headers: {
      Authorization: `Bearer ${token}`,
    },
    timeout: config.timeout,
  });

  return response.json();
}
```

## API Reference

### Configuration Functions

| Function                              | Description                             |
| ------------------------------------- | --------------------------------------- |
| `getConfig()`                         | Get current config object               |
| `initConfig(options)`                 | Initialize config (call at app startup) |
| `setApiBaseUrl(url)`                  | Set API base URL                        |
| `setWsBaseUrl(url)`                   | Set WebSocket URL                       |
| `setDebug(debug)`                     | Set debug mode                          |
| `resetConfig()`                       | Reset to default config                 |
| `subscribeConfig(listener)`           | Subscribe to config changes             |
| `initWithEnvironment(env, overrides)` | Initialize with environment preset      |

### Token Management

| Function                      | Description            |
| ----------------------------- | ---------------------- |
| `getToken()`                  | Get access token       |
| `getRefreshToken()`           | Get refresh token      |
| `saveTokens(access, refresh)` | Save tokens            |
| `clearTokens()`               | Clear all tokens       |
| `isAuthenticated()`           | Check if authenticated |

### Utility Functions

| Function                            | Description        |
| ----------------------------------- | ------------------ |
| `buildApiUrl(endpoint, useFullUrl)` | Build full API URL |
| `logger.debug/info/warn/error`      | Log output         |

## Configuration

| Option       | Type    | Default         | Description          |
| ------------ | ------- | --------------- | -------------------- |
| `apiBaseUrl` | string  | `/api/v1`       | API base path        |
| `apiFullUrl` | string  | `''` (required) | Full API URL         |
| `timeout`    | number  | `30000`         | Request timeout (ms) |
| `retryCount` | number  | `3`             | Retry count          |
| `debug`      | boolean | `false`         | Debug mode           |
| `logLevel`   | string  | `info`          | Log level            |
| `wsBaseUrl`  | string  | `''` (required) | WebSocket URL        |

## Environment Presets

```javascript
import { initWithEnvironment } from "@quantabit/sdk-config";

// Development
initWithEnvironment("development");

// Staging
initWithEnvironment("staging");

// Production
initWithEnvironment("production");

// With override config
initWithEnvironment("production", {
  timeout: 10000,
});
```

## Integration with Other SDKs

All QuantaBit SDKs should read configuration from this package:

```javascript
// In auth-sdk, wallet-sdk, etc.
import {
  getConfig,
  buildApiUrl,
  getToken,
  logger,
} from "@quantabit/sdk-config";

class ApiClient {
  async request(endpoint, options = {}) {
    const config = getConfig();
    const url = buildApiUrl(endpoint);
    const token = getToken();

    logger.debug("Requesting:", url);

    const response = await fetch(url, {
      ...options,
      headers: {
        "Content-Type": "application/json",
        Authorization: token ? `Bearer ${token}` : undefined,
        ...options.headers,
      },
    });

    return response.json();
  }
}
```

## License

MIT © QuantaBit Team



---

## 🌐 Brand & Links
- Official Mainnet: [QuantaBit Chain](https://qbitchain.io/)
- Developer Platform: [Developer Platform](https://developer.quantabit.io/)
- Open Platform: [Open Platform](https://open.quantabit.io/)
- Payment Platform: [Pay Platform](https://pay.qbitwallet.io/)
- Feedback: [Feedback](https://xwin.live/qbit)
