import { TypedData, Call } from 'starknet'; export { Call } from 'starknet'; /** * Core configuration and environment types */ interface ChipiSDKConfig { apiPublicKey: string; alphaUrl?: string; nodeUrl?: string; apiSecretKey?: string; } interface ChipiServerSDKConfig extends ChipiSDKConfig { apiSecretKey: string; } interface ChipiBrowserSDKConfig extends Omit { apiSecretKey?: never; } type alphaUrl = string; declare enum Chain { STARKNET = "STARKNET", BASE = "BASE", ARBITRUM = "ARBITRUM", OPTIMISM = "OPTIMISM", ROOTSTOCK = "ROOTSTOCK", SCROLL = "SCROLL", WORLDCHAIN = "WORLDCHAIN" } declare enum Currency { MXN = "MXN", USD = "USD" } declare enum ChainToken { USDC = "USDC", USDC_E = "USDC_E", USDT = "USDT", DAI = "DAI", ETH = "ETH", STRK = "STRK", SLINK = "SLINK", ALF = "ALF", BROTHER = "BROTHER", ARB = "ARB", DOC = "DOC", MXNB = "MXNB", WLD = "WLD", WBTC = "WBTC", OTHER = "OTHER" } interface PaginationQuery { page?: number; limit?: number; offset?: number; } interface PaginatedResponse { data: T[]; total: number; page: number; limit: number; totalPages: number; } declare const STARKNET_CONTRACTS: Record; /** * Wallet-related types */ /** * Supported wallet types * - CHIPI: OpenZeppelin account with SNIP-9 session keys support (legacy v29) * - READY: Argent X Account v0.4.0 * - SHHH (default post-P2.2): V8.4 ShhhAccount — pluggable-signer Starknet * account dispatching to one of 10 verifier classes (STARK, ED25519, * SECP256K1, EIP191/EIP712, P256, WEBAUTHN_P256, JWT_ES256, * JWT_ES256_APPLE_SUB, BLS12_381). Requires CHIPI_SHHH_ENABLED on the * backend. * - Custom string values accepted for extensibility (e.g., community account implementations) */ type WalletType = "CHIPI" | "READY" | "SHHH" | (string & {}); /** * SHHH signer kinds (V8.4 ShhhAccount). The `kind_tag` value the account uses * to dispatch `verify` to the matching verifier class via library_call_syscall. * See SHHH_VERIFIER_CLASS_HASHES and SHHH_KIND_GAS_OVERHEAD in @chipi-stack/shared. */ type ShhhSignerKind = "STARK" | "ED25519" | "SECP256K1" | "EIP191_SECP256K1" | "EIP712_SECP256K1" | "P256" | "WEBAUTHN_P256" | "JWT_ES256" | "JWT_ES256_APPLE_SUB" | "BLS12_381"; /** * Authentication method used for wallet encryption. * - "passkey": passkey only (no PIN backup — legacy, not recommended) * - "pin": PIN only (current default) * - "passkey+pin": passkey primary + PIN backup (recommended default) */ type AuthMethod = "passkey" | "pin" | "passkey+pin"; interface WalletData { publicKey: string; encryptedPrivateKey: string; walletType?: WalletType; normalizedPublicKey?: string; /** * SHHH V8.4 primary signer kind. Optional; the OE submission path * uses it to pick the right envelope builder (STARK / ED25519 / * etc.). Accepts `null` so callers can spread a * `GetWalletResponse` (which surfaces `null` for non-SHHH rows) * straight into `WalletData` without coercion. Treated as "default * to STARK" by every downstream consumer. */ signerKind?: ShhhSignerKind | null; } interface DeploymentData { class_hash: string; salt: string; unique: string; calldata: string[]; } interface CreateWalletParams { encryptKey?: string; externalUserId: string; userId?: string; chain: Chain; /** * The type of wallet to create. * - "CHIPI" (legacy v29): OpenZeppelin account with SNIP-9 session keys support * - "READY": Argent X Account v0.4.0 * - "SHHH" (default post-P2.2): V8.4 ShhhAccount, pluggable-signer. * `signerKind` defaults to `"STARK"` when omitted; explicit non-STARK * kinds throw a deferred-feature error until follow-up PRs add * external-rooted (MetaMask, Phantom, passkey, Apple) deploy paths. * Omitting `walletType` entirely produces an SHHH V8.4 wallet with * `signerKind: "STARK"` — the same kind every live mainnet smoke * since 2026-05-26 has been signing under. */ walletType?: WalletType; /** * Optional custom class hash for wallet deployment. * When provided, overrides the default class hash for the wallet type. * Use this for custom account implementations (e.g., community-submitted accounts). */ classHash?: string; /** * SHHH V8.4 primary signer kind. Optional in P0.3: defaults to * `"STARK"` when `walletType="SHHH"` and the caller omits it. * Ignored for non-SHHH wallet types. Explicit non-STARK kinds * (ED25519, EIP191_SECP256K1, WEBAUTHN_P256, JWT_ES256_APPLE_SUB) * throw a deferred-feature error in P0.3; they will be enabled by * a follow-up PR that adds the external-rooted wallet adapter * pubkey flow (Chipi does not hold the signing key for those). */ signerKind?: ShhhSignerKind; /** * Owner pubkey felts for SHHH wallets rooted in a NON-Chipi-held key * (MetaMask, Phantom, Apple). Pass the per-kind felt array from the * matching `*PubkeyFelts` helper in `@chipi-stack/backend`. Ignored * for `signerKind="STARK"` because Chipi generates the STARK key * itself. */ ownerPubkeyFelts?: string[]; usePasskey?: boolean; /** PIN for backup encryption (dual-key wrapping). Required when usePasskey: true. */ encryptKeyBackup?: string; /** Auth method: "passkey+pin" for dual-key, "pin" for PIN-only */ authMethod?: AuthMethod; /** WebAuthn credential ID stored in backend for recovery */ credentialId?: string; /** Whether browser supports PRF extension */ prfSupported?: boolean; /** Device type for telemetry */ deviceType?: "web" | "ios" | "android"; } /** * Create-wallet API returns the wallet object at the top level (no nested `wallet`). * Same shape as GetWalletResponse for consistency. */ type CreateWalletResponse = GetWalletResponse; interface GetWalletParams { externalUserId: string; } interface GetTokenBalanceParams { externalUserId?: string; walletPublicKey?: string; chainToken: ChainToken; chain: Chain; } interface GetTokenBalanceResponse { chain: Chain; chainToken: ChainToken; chainTokenAddress: string; decimals: number; balance: string; } interface GetWalletResponse { id: string; externalUserId: string; organizationId: string | null; apiPublicKey: string; publicKey: string; normalizedPublicKey: string; encryptedPrivateKey: string; isDeployed: boolean; createdAt: string; updatedAt: string; walletType: WalletType; chain: Chain; /** PIN-encrypted backup (null for legacy PIN-only wallets) */ encryptedPrivateKeyBackup?: string | null; /** Auth method used for this wallet (null = legacy PIN) */ authMethod?: string | null; /** WebAuthn credential ID for passkey recovery */ credentialId?: string | null; /** Whether PRF extension was used during passkey creation */ prfSupported?: boolean | null; /** Device type that created this wallet */ deviceType?: string | null; /** * Deploy transaction hash. Surfaced from chipi-back's createWallet * response so callers can walk `starknet_traceTransaction` and detect * silent inner-OE reverts at the wallet contract level (B9 smoke * pattern, hardening recommended by the Shhh team 2026-05-25). * Only present on createWallet responses; null/undefined on plain * getWallet reads where the deploy tx has been GCed from chipi-back. */ transactionHash?: string | null; /** * SHHH V8.4 primary signer kind. Populated for SHHH wallets so the * SDK can auto-route OE submissions to the right envelope builder * (STARK uses `buildStarkEnvelope`, ED25519 uses `buildEd25519Envelope`, * etc.). Null on CHIPI / READY rows by construction. */ signerKind?: ShhhSignerKind | null; } interface PrepareWalletCreationParams { encryptKey: string; apiPublicKey: string; } interface PrepareWalletCreationResponse { typedData: TypedData; accountClassHash: string; } interface CreateCustodialWalletParams { chain: Chain; orgId: string; } interface GetMerchantWalletParams { apiKeyId: string; chain: Chain; orgId: string; } interface UpdateWalletEncryptionParams { externalUserId: string; newEncryptedPrivateKey: string; /** Optional; disambiguates when multiple wallets exist for the same user */ publicKey?: string; } interface UpdateWalletEncryptionResponse { success?: boolean; } interface MigrateWalletToPasskeyParams { wallet: WalletData; oldEncryptKey: string; externalUserId: string; } interface PasskeyMetadata { credentialId: string; createdAt: string; userId: string; prfSupported: boolean; } /** * Parameters for preparing a wallet upgrade (e.g., READY → CHIPI or CHIPI v29 → v33). * Server-only: requires API secret key. */ interface PrepareWalletUpgradeParams { /** Wallet address to upgrade */ walletAddress: string; /** Target class hash to upgrade to (defaults to latest CHIPI if omitted) */ targetClassHash?: string; } /** * Response from prepare-upgrade containing typed data for signing. */ interface PrepareWalletUpgradeResponse { /** SNIP-12 typed data to sign for the upgrade */ typedData: TypedData; /** Current class hash of the wallet */ currentClassHash: string; /** Target class hash for upgrade */ targetClassHash: string; /** Current wallet type */ currentWalletType: WalletType; /** Target wallet type after upgrade */ targetWalletType: WalletType; } /** * Parameters for executing a wallet upgrade after signing. * Server-only: requires API secret key. */ interface ExecuteWalletUpgradeParams { /** Wallet address being upgraded */ walletAddress: string; /** SNIP-12 typed data (from prepare step) */ typedData: TypedData; /** User signature over the typed data */ signature: string[]; } /** * Response from wallet upgrade execution. */ interface ExecuteWalletUpgradeResponse { /** Transaction hash for the upgrade */ transactionHash: string; /** New class hash after upgrade */ newClassHash: string; /** New wallet type after upgrade */ newWalletType: WalletType; } /** * Transaction-related types */ type PasskeyEnabledParams = { usePasskey: true; externalUserId: string; }; type PasskeyDisabledParams = { usePasskey?: false; externalUserId?: string; }; type PasskeyParams = PasskeyEnabledParams | PasskeyDisabledParams; type ExecuteTransactionParams = PasskeyParams & { encryptKey?: string; wallet: WalletData; calls: Call[]; }; type TxType = string; type TxStatus = "PENDING" | "PROCESSING" | "SUCCESS" | "FAILED" | "CANCELLED"; interface Transaction { id: string; type: TxType; subType?: string; chain: Chain; transactionHash: string; senderAddress: string; destinationAddress: string; contractAddress?: string; contractName?: string; functionName?: string; functionSelector?: string; callData?: unknown; token?: ChainToken; tokenAddress?: string; amount?: string; nftTokenId?: string; nftContract?: string; nftMetadata?: Record; skuId?: string; skuReference?: string; skuPurchaseAmount?: number; skuPurchaseCurrency?: Currency; skuFileNumber?: string; status: TxStatus; createdAt: Date; confirmedAt?: Date; updatedAt: Date; apiPublicKey: string; chipiWalletId?: string; destinationChipiWalletId?: string; } interface PrepareTypedDataParams { calls: Call[]; walletAddress: string; } interface PrepareTypedDataResponse { typedData: TypedData; walletType: WalletType; } interface ExecuteSponsoredTransactionParams { calls: Call[]; walletAddress: string; signature: string[]; apiPublicKey: string; } interface ExecuteSponsoredTransactionResponse { transactionHash: string; } interface RecordSendTransactionParams { transactionHash: string; expectedSender: string; expectedRecipient: string; expectedToken: ChainToken; expectedAmount: string; chain: Chain; } type TransferParams = PasskeyParams & { encryptKey?: string; wallet: WalletData; token: ChainToken; otherToken?: { contractAddress: string; decimals: number; }; recipient: string; amount: string; }; type TransferHookInput = PasskeyParams & { encryptKey?: string; wallet: WalletData; token: ChainToken; otherToken?: { contractAddress: string; decimals: number; }; recipient: string; amount: number; }; type ApproveParams = PasskeyParams & { encryptKey?: string; wallet: WalletData; contractAddress: string; spender: string; amount: string; decimals?: number; }; type ApproveHookInput = PasskeyParams & { encryptKey?: string; wallet: WalletData; contractAddress: string; spender: string; decimals?: number; amount: number; }; type CallAnyContractParams = PasskeyParams & { encryptKey?: string; wallet: WalletData; contractAddress: string; calls: Call[]; }; interface GetTransactionsParams { page?: number; limit?: number; orgId: string; } interface GetTransactionListQuery { page?: number; limit?: number; calledFunction?: string; walletAddress: string; day?: number; month?: number; year?: number; } /** * Parameters for fetching a single transaction by hash or internal ID. */ interface GetTransactionParams { /** Transaction hash (0x...) or internal database ID */ hashOrId: string; } /** * Parameters for fetching on-chain transaction status. */ interface GetTransactionStatusParams { /** Transaction hash (0x...) */ hash: string; } /** * On-chain transaction status from StarkNet sequencer. */ declare enum OnChainTxStatus { RECEIVED = "RECEIVED", PENDING = "PENDING", ACCEPTED_ON_L2 = "ACCEPTED_ON_L2", ACCEPTED_ON_L1 = "ACCEPTED_ON_L1", REJECTED = "REJECTED", REVERTED = "REVERTED", NOT_RECEIVED = "NOT_RECEIVED" } /** * Response from the transaction status endpoint. */ interface TransactionStatusResponse { /** Transaction hash */ transactionHash: string; /** Current on-chain status */ status: OnChainTxStatus; /** Block number (if included in a block) */ blockNumber?: number; /** Revert reason (if status is REVERTED) */ revertReason?: string; } /** * Minimal account interface for PaymasterAdapter. * Compatible with starknet.js Account, external wallet objects, and Cartridge Controller. */ interface PaymasterAccount { address: string; signMessage(typedData: TypedData): Promise; getClassHashAt(contractAddress: string): Promise; } /** * Adapter for executing gasless (paymaster-sponsored) transactions. * * Handles the full flow: prepare typed data -> sign -> submit to paymaster. * For external wallets (Argent X, Braavos), `account.signMessage()` triggers the wallet popup. * For DirectSigner, signing happens programmatically. */ interface PaymasterAdapter { execute(params: { account: PaymasterAccount; calls: Call[]; }): Promise; } /** * Parameters for signing SNIP-12 typed data without executing a transaction. * Useful for x402 payment signatures and other off-chain signing flows. */ interface SignTypedDataParams { /** Encryption key (PIN) to decrypt the private key */ encryptKey: string; /** Wallet data containing encrypted private key */ wallet: WalletData; /** SNIP-12 typed data to sign */ typedData: TypedData; } /** * Result of signing SNIP-12 typed data. */ interface SignTypedDataResult { /** Signature r component */ r: string; /** Signature s component */ s: string; } /** * Parameters for syncing on-chain transactions from Voyager. */ interface SyncOnChainTransfersParams { /** Wallet address to sync transfers for */ walletAddress: string; } /** * Response from sync-on-chain endpoint. */ interface SyncOnChainTransfersResponse { /** Number of new transactions synced to DB */ synced: number; /** Total transfers found on-chain */ total: number; } /** * SKU Purchase types */ interface CreateSkuPurchaseBody { transactionHash: string; walletAddress: string; skuId: string; skuReference: string; currencyAmount: number; chain: Chain; token: ChainToken; } interface CreateSkuPurchaseParams { skuId: string; skuReference: string; currencyAmount: number; currency: Currency; chain: Chain; token: ChainToken; encryptKey: string; wallet: WalletData; } interface StakeVesuUsdcHookInputParams { encryptKey?: string; wallet: WalletData; amount: number; receiverWallet: string; usePasskey?: boolean; } interface StakeVesuUsdcParams { encryptKey?: string; wallet: WalletData; amount: string; receiverWallet: string; usePasskey?: boolean; } interface WithdrawVesuUsdcParams { encryptKey?: string; wallet: WalletData; amount: string; recipient: string; usePasskey?: boolean; } interface WithdrawVesuUsdcHookInputParams { encryptKey?: string; wallet: WalletData; amount: number; recipient: string; usePasskey?: boolean; } type SkuCategory = "TELEPEAJE" | "TELEFONIA" | "GENERAL" | "TESORERIA" | "LUZ" | "INTERNET" | "TV" | "MOVILIDAD" | "RECARGAS" | "GIFT_CARDS" | "GAMING" | "VENTAS_CATALOGO" | "DEPORTES" | "STREAMING"; interface Sku { id: string; providerId: string; name: string; description?: string; category: SkuCategory; referenceRegexValidation: string; referenceLabel: string; amountRegexValidation: string; amountLabel: string; fixedAmount?: number; currency: Currency; canCheckSkuReference: boolean; logoUrl?: string; createdAt: Date; updatedAt: Date; } type SkuProvider = "TET" | "CHIPI"; interface GetSkuListQuery extends PaginationQuery { /** Filter by upstream provider (TET = bill-payment aggregator, CHIPI = native). */ provider?: SkuProvider; /** * Filter by SkuCategory enum (e.g. RECARGAS, GIFT_CARDS, TELEFONIA, GENERAL). * Matches against `Sku.category` (the upstream classification). */ category?: SkuCategory; /** * Filter by the curated chipi-side category code. * Matches against `Sku.chipiCategory` — the admin-curated taxonomy * referenced from `SkuCategoryMapping.code`. Use this when you want to * follow what the dashboard categorizes the SKU as, even if it differs * from the upstream `category`. */ chipiCategory?: string; /** * Case-insensitive substring filter on `Sku.carrierName` * (e.g. "Telcel", "Amazon Gift Card"). */ carrierName?: string; /** * Locale for descriptions and category display names. * @default "en" */ locale?: "en" | "es"; } /** * API-related types and interfaces */ interface ApiKey { id: string; publicKey: string; secretKey: string; environment: "development" | "production"; isActive: boolean; orgId: string; createdAt: Date; updatedAt: Date; } interface ApiResponse { data?: T; error?: string; message?: string; } interface ApiError { code: string; message: string; details?: any; } interface AuthContext { apiKey: ApiKey; orgId: string; userId?: string; } interface JwtPayload { sub: string; iss: string; aud: string; exp: number; iat: number; [key: string]: any; } /** * Utility types and helper interfaces */ type Prettify = { [K in keyof T]: T[K]; } & {}; type Optional = Omit & Partial>; type RequireAtLeastOne = Pick> & { [K in Keys]-?: Required> & Partial>>; }[Keys]; type DeepPartial = { [P in keyof T]?: T[P] extends object ? DeepPartial : T[P]; }; type NonEmptyArray = [T, ...T[]]; interface ErrorWithCode extends Error { code?: string; status?: number; } type AsyncReturnType Promise> = T extends (...args: any) => Promise ? R : any; type ValueOrFunction = T | (() => T); type MaybePromise = T | Promise; interface User { id: string; username: string; externalId: string; orgId: string; apiKeyId: string; name: string; lastName: string; email: string; phoneCountryCode: number; phoneNumber: number; profession?: string; taxId?: string; createdAt: Date; updatedAt: Date; } type Country = "MX" | "US" | "OTHER"; interface CreateUserParams { externalId: string; username?: string; name?: string; lastName?: string; country?: Country; phoneCountryCode?: number; phoneNumber?: number; email?: string; profession?: string; taxId?: string; } interface GetUserParams { id?: string; externalId?: string; username?: string; phone?: { phoneCountryCode: number; phoneNumber: number; }; taxId?: string; includeStarknetWallet?: boolean; } /** * Session key types for CHIPI wallets (SNIP-9 compatible) * * Session keys enable temporary, delegated access to execute transactions * without requiring the owner's private key for each operation. * * @see https://github.com/chipi-pay/sessions-smart-contract */ /** * Session key data returned to developer for self-custodial storage. * The SDK generates this data but does NOT store it - developers must * persist it externally (e.g., in Clerk metadata, database, etc.) */ interface SessionKeyData { /** Stark public key (hex format, e.g., "0x...") */ publicKey: string; /** AES encrypted private key - encrypt with user's encryptKey */ encryptedPrivateKey: string; /** Unix timestamp (seconds) when this session expires */ validUntil: number; } /** * Full session configuration for on-chain registration. * Used when calling add_or_update_session_key on the contract. */ interface SessionConfig { /** Stark public key of the session (hex format) */ sessionPublicKey: string; /** Unix timestamp (seconds) - u64 on-chain */ validUntil: number; /** Maximum number of transactions allowed - u32 on-chain */ maxCalls: number; /** * Whitelisted function selectors (hex format). * Empty array = all entrypoints allowed. * Non-empty = only these selectors can be called with this session. */ allowedEntrypoints: string[]; } /** * Parameters for creating a session keypair locally. * This only generates keys - does NOT register on-chain. */ interface CreateSessionKeyParams { /** Encryption key to encrypt the session private key */ encryptKey: string; /** * Session duration in seconds. * @default 21600 (6 hours) */ durationSeconds?: number; } /** * Parameters for registering a session key on the smart contract. * Requires owner signature (uses owner's encrypted private key). * * NOTE: walletType is intentionally optional for backward compatibility. * Legacy wallets from getWallet() may not have walletType set (defaults to ARGENT). * Runtime validation in ChipiSessions ensures only CHIPI wallets are used. * Making walletType required here would be a breaking change for existing users. * @see ChipiSessions.validateChipiWallet() for runtime validation. */ interface AddSessionKeyParams { /** Encryption key to decrypt the owner's private key for signing */ encryptKey: string; /** Wallet data including encrypted owner private key */ wallet: WalletData & { walletType?: WalletType; }; /** Session configuration to register on-chain */ sessionConfig: SessionConfig; } /** * Parameters for executing a transaction using a session key. * Uses session signature (4-element format) instead of owner signature. * * NOTE: walletType is intentionally optional for backward compatibility. * @see AddSessionKeyParams for detailed reasoning. */ interface ExecuteWithSessionParams { /** Encryption key to decrypt the session private key */ encryptKey: string; /** Wallet data (session executes on behalf of this wallet) */ wallet: WalletData & { walletType?: WalletType; }; /** Session key data (must be registered on-chain first) */ session: SessionKeyData; /** Calls to execute */ calls: Call[]; } /** * Parameters for revoking a session key from the smart contract. * Requires owner signature. * * NOTE: walletType is intentionally optional for backward compatibility. * @see AddSessionKeyParams for detailed reasoning. */ interface RevokeSessionKeyParams { /** Encryption key to decrypt the owner's private key for signing */ encryptKey: string; /** Wallet data including encrypted owner private key */ wallet: WalletData & { walletType?: WalletType; }; /** Public key of the session to revoke */ sessionPublicKey: string; } /** * Parameters for querying session data from the contract. */ interface GetSessionDataParams { /** Wallet address to query */ walletAddress: string; /** Session public key to query */ sessionPublicKey: string; } /** * Response from get_session_data contract call. * Represents the on-chain state of a session key. */ interface SessionDataResponse { /** Whether the session is currently active (not revoked, not expired) */ isActive: boolean; /** Unix timestamp when the session expires */ validUntil: number; /** Number of calls remaining (decrements with each use) */ remainingCalls: number; /** Whitelisted selectors (empty = all allowed) */ allowedEntrypoints: string[]; } /** * Extended wallet data with required walletType for session operations. * Session keys only work with CHIPI wallets. */ interface SessionWalletData extends WalletData { walletType: WalletType; } /** * Configuration for setting a spending policy on a session key. * Spending policies enforce per-token limits on ERC-20 operations * (transfer, approve, increase_allowance) executed by session keys. */ interface SpendingPolicyConfig { /** Session public key to apply the policy to */ sessionPublicKey: string; /** ERC-20 token contract address (hex format) */ token: string; /** Maximum amount per single call — u256 on-chain */ maxPerCall: bigint; /** Maximum cumulative amount within the rolling window — u256 on-chain */ maxPerWindow: bigint; /** Rolling window duration in seconds — u64 on-chain */ windowSeconds: number; } /** * On-chain spending policy state returned by get_spending_policy. * Includes both configured limits and current window tracking. */ interface SpendingPolicyData { /** Maximum amount per single call */ maxPerCall: bigint; /** Maximum cumulative amount within the rolling window */ maxPerWindow: bigint; /** Rolling window duration in seconds */ windowSeconds: number; /** Amount spent in the current active window */ spentInWindow: bigint; /** Unix timestamp when the current window started */ windowStart: number; } /** * Parameters for setting a spending policy on a session key. * Requires owner signature (the wallet owner sets limits on the session). * * NOTE: walletType is intentionally optional for backward compatibility. * @see AddSessionKeyParams for detailed reasoning. */ interface SetSpendingPolicyParams { /** Encryption key to decrypt the owner's private key for signing */ encryptKey: string; /** Wallet data including encrypted owner private key */ wallet: WalletData & { walletType?: WalletType; }; /** Spending policy configuration */ spendingPolicyConfig: SpendingPolicyConfig; } /** * Parameters for querying a spending policy from the contract. * Read-only — no signature or gas required. */ interface GetSpendingPolicyParams { /** Wallet address to query */ walletAddress: string; /** Session public key */ sessionPublicKey: string; /** ERC-20 token contract address */ token: string; } /** * Parameters for removing a spending policy from a session key. * Requires owner signature. * * NOTE: walletType is intentionally optional for backward compatibility. * @see AddSessionKeyParams for detailed reasoning. */ interface RemoveSpendingPolicyParams { /** Encryption key to decrypt the owner's private key for signing */ encryptKey: string; /** Wallet data including encrypted owner private key */ wallet: WalletData & { walletType?: WalletType; }; /** Session public key to remove policy from */ sessionPublicKey: string; /** ERC-20 token contract address */ token: string; } /** * x402 Payment Protocol types for HTTP 402 pay-per-request APIs. * * Implements the x402 open payment protocol (https://www.x402.org/) for Starknet, * using SNIP-12 typed data signing and paymaster-sponsored USDC transfers. */ /** Payment requirement returned in 402 response PAYMENT-REQUIRED header */ interface PaymentRequirement { /** Payment scheme — x402-starknet uses "exact" */ scheme: "exact"; /** Network identifier */ network: "starknet-mainnet"; /** Amount in token base units (e.g. "10000" = 0.01 USDC) */ maxAmountRequired: string; /** URL of the resource being paid for */ resource: string; /** Human-readable description of the payment */ description?: string; /** MIME type of the resource */ mimeType?: string; /** Recipient address (merchant) */ payTo: string; /** Max seconds before payment expires */ maxTimeoutSeconds: number; /** Token contract address (USDC) */ asset: string; /** Additional protocol-specific data */ extra?: Record; } /** * SHHH V8.4 extension on the x402 payment payload. Present when the * buyer's wallet is a SHHH ShhhAccount — V8.4 cannot validate a raw * `{r, s}` signature (its `execute_from_outside_v2` requires either a * 5-felt V2_SNIP12 envelope or a 4-felt session sig at * `account.cairo:389`). For SHHH buyers, the client pre-builds the * full execute_from_outside_v2 calldata + signs the V8.4 SNIP-12 * hash locally; the facilitator forwards verbatim through * `/transactions/execute-sponsored-raw` instead of calling the * CHIPI v29 prepare-typed-data + execute-sponsored-transaction * pair. * * Absent for CHIPI v29 / READY buyers — those keep the existing * `signature: {r, s}` field, and the facilitator builds the on-chain * tx itself. */ interface ShhhPaymentExtension { /** Discriminator. Forces the facilitator into the V8.4 raw path. */ walletType: "SHHH"; /** Primary signer kind. Drives the paymaster's per-kind gas overhead. */ signerKind: "STARK" | "ED25519"; /** * Pre-serialized `execute_from_outside_v2` calldata, ready for the * paymaster JSON-RPC. The facilitator forwards this verbatim — the * V8.4 envelope signature lives inside this span. */ oeCalldata: string[]; } /** Signed payment payload sent in X-PAYMENT header */ interface PaymentPayload { x402Version: 1; scheme: "exact"; network: "starknet-mainnet"; payload: { signature: { r: string; s: string; }; fromAddress: string; toAddress: string; amount: string; asset: string; validUntil: number; nonce: string; /** * SHHH V8.4 extension. Present when fromAddress is a SHHH wallet. * The facilitator detects this field and routes the settle through * `/transactions/execute-sponsored-raw` instead of CHIPI v29's * prepare-typed-data + execute-sponsored-transaction. Backward- * compatible: a CHIPI v29 buyer (or any older client) omits this * field and the existing flow runs. */ shhh?: ShhhPaymentExtension; }; } /** Facilitator verify response */ interface VerifyResponse { isValid: boolean; invalidReason?: string; } /** Facilitator settle response */ interface SettleResponse { success: boolean; transactionHash?: string; errorReason?: string; networkId?: string; } /** * Pluggable nonce store for facilitator replay protection. * Default: in-memory Set (resets on restart). * For production: plug in Redis, PostgreSQL, DynamoDB, etc. */ interface NonceStore { /** Check if nonce has been used (non-consuming read). */ has(nonce: string): Promise | boolean; /** * Atomically consume a nonce. Returns true if successfully consumed (was new). * Returns false if nonce was already used. * Must be atomic to prevent concurrent replay attacks. * Maps to Redis SETNX, PostgreSQL INSERT ON CONFLICT DO NOTHING, etc. */ consume(nonce: string): Promise | boolean; } /** x402 client configuration */ interface X402ClientConfig { /** Max amount willing to pay per request (in human-readable units, e.g. "1.00" = 1 USDC) */ maxPaymentAmount?: string; /** Allowed recipient addresses (whitelist). Empty = allow all. */ allowedRecipients?: string[]; /** Custom header name (default: "X-PAYMENT") */ headerName?: string; } /** x402 facilitator configuration */ interface X402FacilitatorConfig { /** Custom nonce store for persistent replay protection. Defaults to in-memory. */ nonceStore?: NonceStore; /** * RPC provider for on-chain SNIP-12 signature verification. * When provided, the facilitator calls `is_valid_signature()` on the sender's * account contract to cryptographically verify the payment signature. * When omitted, falls back to presence-only signature check (backwards compatible). * * Accepts any object with a `callContract` method (e.g. starknet.js RpcProvider). */ provider?: { callContract(call: { contractAddress: string; entrypoint: string; calldata?: string[]; }): Promise; }; } /** x402 middleware payment config for a protected endpoint */ interface X402PaymentConfig { /** Amount in human-readable units (e.g. "0.01" for 0.01 USDC) */ amount: string; /** Merchant receiving address */ payTo: string; /** Human-readable description */ description?: string; } /** * Plus epic — shared subscription state types. * * Single source of truth for the org's plan tier. Mirrored by the * `Plan` enum in chipi-back's Prisma schema and the dashboard's zod * `PlanEnum`. Backend webhooks (Stripe) and the monthly USDC debit * cron flip `Organization.plan` between these values. * * Wave 1 ships the type only — gating logic lands in Waves 3, 6, 7. */ /** The org's subscription tier. `STARTER` and `GROWTH` are legacy enum * values preserved for one release; no production rows exist. * Treat as `FREE` for any gating logic. */ type Plan = "FREE" | "PLUS" | "ENTERPRISE"; /** Settlement provider for the Plus subscription. Persisted on * `Organization.planPaymentProvider`. `null` means the org has no * active subscription (FREE or ENTERPRISE-without-self-serve). */ type PlanPaymentProvider = "STRIPE" | "USDC_PAYMASTER"; /** Plus subscription state snapshot returned by chipi-back's * `GET /organizations/:id/plan` endpoint. Consumed by the dashboard's * `useOrgPlan()` hook (Wave 1) and the SDK's pre-flight tier checks * (Wave 6). */ interface PlanSnapshot { plan: Plan; /** Most recent transition timestamp (any direction). */ planUpdatedAt: string | null; /** First-ever activation of PLUS for this org (preserved across * cancel → resubscribe cycles). `null` for orgs that have never * upgraded. */ planActivatedAt: string | null; /** End of current billing cycle. `null` for FREE / ENTERPRISE. */ planExpiresAt: string | null; /** `null` for FREE / ENTERPRISE. */ planPaymentProvider: PlanPaymentProvider | null; } export { type AddSessionKeyParams, type ApiError, type ApiKey, type ApiResponse, type ApproveHookInput, type ApproveParams, type AsyncReturnType, type AuthContext, type AuthMethod, type CallAnyContractParams, Chain, ChainToken, type ChipiBrowserSDKConfig, type ChipiSDKConfig, type ChipiServerSDKConfig, type Country, type CreateCustodialWalletParams, type CreateSessionKeyParams, type CreateSkuPurchaseBody, type CreateSkuPurchaseParams, type CreateUserParams, type CreateWalletParams, type CreateWalletResponse, Currency, type DeepPartial, type DeploymentData, type ErrorWithCode, type ExecuteSponsoredTransactionParams, type ExecuteSponsoredTransactionResponse, type ExecuteTransactionParams, type ExecuteWalletUpgradeParams, type ExecuteWalletUpgradeResponse, type ExecuteWithSessionParams, type GetMerchantWalletParams, type GetSessionDataParams, type GetSkuListQuery, type GetSpendingPolicyParams, type GetTokenBalanceParams, type GetTokenBalanceResponse, type GetTransactionListQuery, type GetTransactionParams, type GetTransactionStatusParams, type GetTransactionsParams, type GetUserParams, type GetWalletParams, type GetWalletResponse, type JwtPayload, type MaybePromise, type MigrateWalletToPasskeyParams, type NonEmptyArray, type NonceStore, OnChainTxStatus, type Optional, type PaginatedResponse, type PaginationQuery, type PasskeyMetadata, type PaymasterAccount, type PaymasterAdapter, type PaymentPayload, type PaymentRequirement, type Plan, type PlanPaymentProvider, type PlanSnapshot, type PrepareTypedDataParams, type PrepareTypedDataResponse, type PrepareWalletCreationParams, type PrepareWalletCreationResponse, type PrepareWalletUpgradeParams, type PrepareWalletUpgradeResponse, type Prettify, type RecordSendTransactionParams, type RemoveSpendingPolicyParams, type RequireAtLeastOne, type RevokeSessionKeyParams, STARKNET_CONTRACTS, type SessionConfig, type SessionDataResponse, type SessionKeyData, type SessionWalletData, type SetSpendingPolicyParams, type SettleResponse, type ShhhPaymentExtension, type ShhhSignerKind, type SignTypedDataParams, type SignTypedDataResult, type Sku, type SkuCategory, type SkuProvider, type SpendingPolicyConfig, type SpendingPolicyData, type StakeVesuUsdcHookInputParams, type StakeVesuUsdcParams, type SyncOnChainTransfersParams, type SyncOnChainTransfersResponse, type Transaction, type TransactionStatusResponse, type TransferHookInput, type TransferParams, type TxStatus, type TxType, type UpdateWalletEncryptionParams, type UpdateWalletEncryptionResponse, type User, type ValueOrFunction, type VerifyResponse, type WalletData, type WalletType, type WithdrawVesuUsdcHookInputParams, type WithdrawVesuUsdcParams, type X402ClientConfig, type X402FacilitatorConfig, type X402PaymentConfig, type alphaUrl };