npm package: @payxor/types
Description: Shared TypeScript types for PayXor
Author: PayXor
Latest version: 0.1.2

# @payxor/types

Shared TypeScript types, interfaces, constants, and utilities for the PayXor ecosystem. This package is a dependency of `@payxor/sdk` and `@payxor/react`.

## Table of Contents

- [Installation](#installation)
- [Enums](#enums)
  - [PaymentMode](#paymentmode)
  - [QuoteStatus](#quotestatus)
  - [AnalyticsEvent](#analyticsevent)
- [Interfaces](#interfaces)
  - [Quote](#quote)
  - [QuoteRequest](#quoterequest)
  - [QuoteResponse](#quoteresponse)
  - [ProductInfo](#productinfo)
  - [ChainConfig](#chainconfig)
  - [StablecoinConfig](#stablecoinconfig)
  - [ConfirmTxRequest](#confirmtxrequest)
  - [ConfirmTxResponse](#confirmtxresponse)
- [Constants](#constants)
  - [SUPPORTED_CHAINS](#supported_chains)
  - [STABLECOINS_BY_CHAIN](#stablecoins_by_chain)
  - [MOCK_TOKENS_BY_CHAIN](#mock_tokens_by_chain)
  - [FAUCET_ADDRESSES_BY_CHAIN](#faucet_addresses_by_chain)
  - [TESTNET_CHAIN_IDS](#testnet_chain_ids)
- [Helper Functions](#helper-functions)
- [Analytics](#analytics)
- [Supported Chains Reference](#supported-chains-reference)

## Installation

```bash
pnpm add @payxor/types
```

```bash
npm install @payxor/types
```

```bash
yarn add @payxor/types
```

> **Note:** This package has no runtime dependencies.

---

## Enums

### PaymentMode

Defines the type of payment/entitlement for a product.

```typescript
import { PaymentMode } from "@payxor/types";

enum PaymentMode {
  SESSION = 0,  // Time-based access (e.g., 1-hour streaming)
  FEATURE = 1,  // Permanent unlock (e.g., premium feature)
  RECEIPT = 2,  // One-time payment proof (e.g., digital purchase)
  PASS = 3,     // Pass/membership (e.g., VIP access)
}
```

| Value | Name | Description |
|-------|------|-------------|
| `0` | `SESSION` | Time-limited access that expires after a duration |
| `1` | `FEATURE` | Permanent one-time unlock |
| `2` | `RECEIPT` | Proof of payment without on-chain entitlement |
| `3` | `PASS` | Pass-based access (membership/subscription) |

---

### QuoteStatus

Status of a payment quote.

```typescript
import { QuoteStatus } from "@payxor/types";

enum QuoteStatus {
  ISSUED = "issued",   // Quote created, awaiting payment
  USED = "used",       // Payment completed
  EXPIRED = "expired", // Quote expired before payment
}
```

---

### AnalyticsEvent

Predefined analytics event names for consistent tracking.

```typescript
import { AnalyticsEvent } from "@payxor/types";

// Authentication events
AnalyticsEvent.SIGN_UP
AnalyticsEvent.SIGN_IN
AnalyticsEvent.SIGN_OUT
AnalyticsEvent.OAUTH_SIGN_IN

// App management events
AnalyticsEvent.APP_CREATED
AnalyticsEvent.APP_VIEWED
AnalyticsEvent.APP_UPDATED

// Product events
AnalyticsEvent.PRODUCT_CREATED
AnalyticsEvent.PRODUCT_VIEWED
AnalyticsEvent.PRODUCT_UPDATED

// Payment events
AnalyticsEvent.QUOTE_REQUESTED
AnalyticsEvent.QUOTE_GENERATED
AnalyticsEvent.PAYMENT_INITIATED
AnalyticsEvent.PAYMENT_COMPLETED
AnalyticsEvent.PAYMENT_FAILED

// Navigation & UI events
AnalyticsEvent.PAGE_VIEW
AnalyticsEvent.BUTTON_CLICK
AnalyticsEvent.FORM_SUBMIT
AnalyticsEvent.LINK_CLICK
AnalyticsEvent.CONTACT_FORM_SUBMITTED
AnalyticsEvent.DOCS_VIEWED
AnalyticsEvent.DOCS_SECTION_VIEWED
```

---

## Interfaces

### Quote

The core quote structure used for EIP-712 signing and payment execution.

```typescript
interface Quote {
  appId: string;         // bytes32 hex - Application identifier
  productId: string;     // bytes32 hex - Product identifier
  mode: PaymentMode;     // Payment mode (SESSION, FEATURE, etc.)
  token: string;         // address - Payment token contract
  amount: string;        // uint256 string - Payment amount in wei
  payee: string;         // address - Recipient wallet
  entitlementId: string; // bytes32 hex - Entitlement identifier
  duration: number;      // uint64 - Session duration in seconds
  expiresAt: number;     // uint64 - Quote expiration timestamp
  quoteId: string;       // uint256 string - Unique quote ID (nonce)
  payer: string;         // address - Payer wallet
  deadline: number;      // uint64 - Payment deadline timestamp
  chainId: number;       // uint256 - Target chain ID
}
```

| Field | Type | Description |
|-------|------|-------------|
| `appId` | `string` | Application ID as bytes32 hex |
| `productId` | `string` | Product ID as bytes32 hex |
| `mode` | `PaymentMode` | Type of payment/entitlement |
| `token` | `string` | ERC20 token address for payment |
| `amount` | `string` | Payment amount in smallest unit (wei) |
| `payee` | `string` | Address receiving the payment |
| `entitlementId` | `string` | ID for the granted entitlement |
| `duration` | `number` | Session duration (seconds), 0 for non-session |
| `expiresAt` | `number` | Unix timestamp when quote expires |
| `quoteId` | `string` | Unique identifier, also serves as nonce |
| `payer` | `string` | Address making the payment |
| `deadline` | `number` | Unix timestamp deadline for payment |
| `chainId` | `number` | Target blockchain network ID |

---

### QuoteRequest

Request payload for generating a quote.

```typescript
interface QuoteRequest {
  appId: string;        // App ID (hex string)
  productId: string;    // Product ID (hex string)
  chainId: number;      // Target chain ID
  payer: string;        // Payer's wallet address
  tokenAddress?: string; // Optional: specific payment token
}
```

---

### QuoteResponse

Response from the quote generation API.

```typescript
interface QuoteResponse {
  quote: Quote;       // The generated quote
  sigBackend: string; // Backend's EIP-712 signature
}
```

---

### ProductInfo

Public product information (no quote creation).

```typescript
interface ProductInfo {
  appId: string;              // bytes32 hex
  productId: string;          // bytes32 hex
  name: string;               // Product display name
  mode: PaymentMode;          // Payment mode
  price: string;              // Price in smallest unit (wei)
  duration: number | null;    // Session duration, null for non-session
  entitlementId: string | null; // Entitlement ID, null if not set
}
```

---

### ChainConfig

Blockchain network configuration.

```typescript
interface ChainConfig {
  chainId: number;              // Network chain ID
  name: string;                 // Human-readable name
  rpcUrl?: string;              // Optional RPC endpoint
  usdcAddress: string;          // Default USDC address (deprecated)
  payxorContractAddress?: string; // PayXor contract address
}
```

> **Note:** `usdcAddress` is deprecated. Use `STABLECOINS_BY_CHAIN` for token addresses.

---

### StablecoinConfig

Stablecoin token configuration.

```typescript
interface StablecoinConfig {
  symbol: string;   // Token symbol (e.g., "USDC", "USDT", "DAI")
  name: string;     // Full token name (e.g., "USD Coin")
  address: string;  // Token contract address
  decimals: number; // Token decimals (6 for USDC/USDT, 18 for DAI)
}
```

---

### ConfirmTxRequest

Request payload for confirming a transaction.

```typescript
interface ConfirmTxRequest {
  txHash: string;  // Transaction hash
  quoteId: string; // Quote ID being confirmed
}
```

---

### ConfirmTxResponse

Response from transaction confirmation.

```typescript
interface ConfirmTxResponse {
  success: boolean; // Whether confirmation succeeded
  quoteId: string;  // Confirmed quote ID
}
```

---

## Constants

### SUPPORTED_CHAINS

Map of chain ID to chain configuration for all supported networks.

```typescript
import { SUPPORTED_CHAINS } from "@payxor/types";

const baseConfig = SUPPORTED_CHAINS[8453];
// { chainId: 8453, name: "Base", usdcAddress: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913" }
```

**Supported Mainnets:** Ethereum (1), Arbitrum (42161), Base (8453), Polygon (137), Avalanche (43114), Optimism (10), BNB Chain (56), zkSync (324)

**Supported Testnets:** Sepolia (11155111), Base Sepolia (84532), Arbitrum Sepolia (421614), Polygon Mumbai (80001), Optimism Sepolia (11155420), Avalanche Fuji (43113), BNB Testnet (97), zkSync Sepolia (300)

---

### STABLECOINS_BY_CHAIN

Map of chain ID to available stablecoins.

```typescript
import { STABLECOINS_BY_CHAIN } from "@payxor/types";

const baseStablecoins = STABLECOINS_BY_CHAIN[8453];
// [
//   { symbol: "USDC", name: "USD Coin", address: "0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913", decimals: 6 },
//   { symbol: "USDT", name: "Tether", address: "0xfde4C96c8593536E31F229EA8f37b2ADa2699f20", decimals: 6 },
//   { symbol: "DAI", name: "Dai Stablecoin", address: "0x50c5725949A6F0c72E6C4a641F24049A917E0Cb6", decimals: 18 },
// ]
```

---

### MOCK_TOKENS_BY_CHAIN

Map of chain ID to mock test tokens (testnets only).

```typescript
import { MOCK_TOKENS_BY_CHAIN } from "@payxor/types";

const sepoliaMockTokens = MOCK_TOKENS_BY_CHAIN[11155111];
// [
//   { symbol: "MockUSDC", name: "Mock USD Coin", address: "0x61C16DdA462EB7dC80084655BF083855581B7D76", decimals: 6 },
//   { symbol: "MockUSDT", name: "Mock Tether", address: "0xacc10698EafB8E63dd542aB8ad1d58a75B4e5349", decimals: 6 },
//   { symbol: "MockDAI", name: "Mock Dai Stablecoin", address: "0x6da5567587c4B17e8E8273E08176508A0123a91E", decimals: 18 },
// ]
```

---

### FAUCET_ADDRESSES_BY_CHAIN

Map of chain ID to mock token faucet contract addresses.

```typescript
import { FAUCET_ADDRESSES_BY_CHAIN } from "@payxor/types";

const sepoliaFaucet = FAUCET_ADDRESSES_BY_CHAIN[11155111];
// "0xbc513b7A213276A839Bdd07a4D82DcfaAd3a7982"
```

---

### TESTNET_CHAIN_IDS

Array of all testnet chain IDs as a const tuple.

```typescript
import { TESTNET_CHAIN_IDS } from "@payxor/types";

// [11155111, 84532, 421614, 80001, 11155420, 43113, 97, 300]
```

---

## Helper Functions

### isTestnet

Check if a chain ID is a testnet.

```typescript
import { isTestnet } from "@payxor/types";

isTestnet(11155111); // true (Sepolia)
isTestnet(8453);     // false (Base mainnet)
```

---

### getTestnetChains

Get all testnet chain configurations.

```typescript
import { getTestnetChains } from "@payxor/types";

const testnets = getTestnetChains();
// Returns array of ChainConfig for all testnets
```

---

### getMainnetChains

Get all mainnet chain configurations.

```typescript
import { getMainnetChains } from "@payxor/types";

const mainnets = getMainnetChains();
// Returns array of ChainConfig for all mainnets
```

---

### getStablecoinsForChain

Get stablecoins available for a specific chain.

```typescript
import { getStablecoinsForChain } from "@payxor/types";

const tokens = getStablecoinsForChain(8453);
// Returns StablecoinConfig[] for Base
```

---

### getMockTokensForChain

Get mock tokens available for a specific testnet.

```typescript
import { getMockTokensForChain } from "@payxor/types";

const mockTokens = getMockTokensForChain(11155111);
// Returns StablecoinConfig[] for Sepolia mock tokens
```

---

### getAllTokensForChain

Get all tokens (real + mock) for a chain.

```typescript
import { getAllTokensForChain } from "@payxor/types";

const allTokens = getAllTokensForChain(11155111);
// Returns combined real USDC + mock tokens for Sepolia
```

---

### getMockTokenAddress

Get a specific mock token address by symbol.

```typescript
import { getMockTokenAddress } from "@payxor/types";

const mockUsdcAddress = getMockTokenAddress(11155111, "MockUSDC");
// "0x61C16DdA462EB7dC80084655BF083855581B7D76"
```

---

### getFaucetAddress

Get the faucet contract address for a testnet.

```typescript
import { getFaucetAddress } from "@payxor/types";

const faucet = getFaucetAddress(11155111);
// "0xbc513b7A213276A839Bdd07a4D82DcfaAd3a7982"
```

---

## Analytics

The package includes a flexible analytics system with support for multiple providers.

### AnalyticsProvider Interface

```typescript
interface AnalyticsProvider {
  track(event: string, properties?: AnalyticsEventProperties): void;
  page(name: string, properties?: AnalyticsEventProperties): void;
  identify(userId: string, traits?: AnalyticsEventProperties): void;
}

interface AnalyticsEventProperties {
  [key: string]: string | number | boolean | null | undefined;
}
```

### Built-in Providers

#### GoogleAnalyticsProvider

```typescript
import { GoogleAnalyticsProvider } from "@payxor/types";

const ga = new GoogleAnalyticsProvider("G-XXXXXXXXXX");
ga.track("payment_completed", { amount: 100, currency: "USD" });
ga.page("Checkout");
ga.identify("user-123", { plan: "premium" });
```

#### ConsoleAnalyticsProvider

For development and debugging.

```typescript
import { ConsoleAnalyticsProvider } from "@payxor/types";

const console = new ConsoleAnalyticsProvider();
console.track("test_event"); // Logs to console
```

### AnalyticsClient

Multi-provider client for sending events to multiple analytics services.

```typescript
import { AnalyticsClient, GoogleAnalyticsProvider, ConsoleAnalyticsProvider } from "@payxor/types";

const client = new AnalyticsClient([
  new GoogleAnalyticsProvider("G-XXXXXXXXXX"),
  new ConsoleAnalyticsProvider(),
]);

client.track("payment_completed", { amount: 100 });
client.page("Dashboard");
client.identify("user-123");
```

### createAnalyticsClient

Factory function for creating an analytics client.

```typescript
import { createAnalyticsClient, AnalyticsEvent } from "@payxor/types";

// Production: Google Analytics only
const prodClient = createAnalyticsClient("G-XXXXXXXXXX");

// Development: Google Analytics + console logging
const devClient = createAnalyticsClient("G-XXXXXXXXXX", true);

// Track events using predefined event names
devClient.track(AnalyticsEvent.PAYMENT_COMPLETED, {
  amount: 100,
  token: "USDC",
  chainId: 8453,
});
```

---

## Supported Chains Reference

### Mainnets

| Chain | ID | Stablecoins |
|-------|-----|-------------|
| Ethereum | 1 | USDC, USDT, DAI, USD1 |
| Arbitrum | 42161 | USDC, USDT, DAI |
| Base | 8453 | USDC, USDT, DAI |
| Polygon | 137 | USDC, USDC.e, USDT, DAI |
| Avalanche | 43114 | USDC, USDT, DAI |
| Optimism | 10 | USDC, USDT, DAI |
| BNB Chain | 56 | USDC, USDT, DAI, USD1 |
| zkSync | 324 | USDC, USDT, DAI |

### Testnets

| Chain | ID | Real Stablecoin | Mock Tokens |
|-------|-----|-----------------|-------------|
| Ethereum Sepolia | 11155111 | USDC | MockUSDC, MockUSDT, MockDAI |
| Base Sepolia | 84532 | USDC | MockUSDC, MockUSDT, MockDAI |
| Arbitrum Sepolia | 421614 | USDC | MockUSDC, MockUSDT, MockDAI |
| Polygon Mumbai | 80001 | USDC | MockUSDC, MockUSDT, MockDAI |
| Optimism Sepolia | 11155420 | USDC | MockUSDC, MockUSDT, MockDAI |
| Avalanche Fuji | 43113 | USDC | MockUSDC, MockUSDT, MockDAI |
| BNB Testnet | 97 | USDC | MockUSDC, MockUSDT, MockDAI |
| zkSync Sepolia | 300 | USDC | MockUSDC, MockUSDT, MockDAI |

---

## Usage with Other Packages

This package is automatically included when you install `@payxor/sdk` or `@payxor/react`:

```typescript
// Types are re-exported from @payxor/sdk
import { Quote, PaymentMode, StablecoinConfig } from "@payxor/sdk";

// Or import directly
import { Quote, PaymentMode, StablecoinConfig } from "@payxor/types";
```

---

## Notes

- All `bytes32` values (appId, productId, entitlementId) are represented as hex strings with `0x` prefix.
- All `uint256` amounts are represented as strings to avoid JavaScript number precision issues.
- Token addresses are checksummed Ethereum addresses.
- Timestamps are Unix timestamps in seconds.