import type { LocalAccount } from 'viem/accounts' import type * as App from '../../../App.js' import * as Scope from '../../../Scope.js' import type * as Auth from '../../../internal/Auth.js' import type * as Db from '../../../db/Db.js' import * as Viem from '../../../internal/Viem.js' import * as Billing from '../../management/Billing.js' import type * as Mpp from '../Mpp.js' /** Resolves the chain declared by a Tempo charge challenge. */ export function chainId(input: Mpp.RelayInput): number | undefined { const request = input.challenge.request const details = record(request['methodDetails']) return number(details?.['chainId']) ?? number(request['chainId']) } /** Whether a Tempo charge credential requests platform fee sponsorship. */ export function requiresFeePayer(input: Mpp.RelayInput) { const request = input.challenge.request return record(request['methodDetails'])?.['feePayer'] === true && request['feePayer'] !== false } /** Refuses a sponsored transaction that the current fee market cannot admit. */ export function assertFeeMarketAdmission(options: assertFeeMarketAdmission.Options) { if (options.maxFeePerGas < options.baseFeePerGas) throw new PolicyDeniedError('Transaction max fee per gas is below the current base fee.') } export declare namespace assertFeeMarketAdmission { /** Current fee-market and transaction fee bounds. */ type Options = { /** Latest block base fee. */ baseFeePerGas: bigint /** Signed transaction fee cap. */ maxFeePerGas: bigint } } /** Refuses unsupported chains, unauthorized Zones, and sandbox access to mainnet. */ export function assertChainAccess(options: assertChainAccess.Options) { const { chainId, principal, supportedChainIds, zones } = options if (!supportedChainIds.has(chainId)) throw new UnsupportedChainError(chainId) const zone = zones.get(chainId) if (zone) { const scopes = principal?.type === 'api_key' ? principal.apiKey.scopes : undefined if ( !scopes?.includes(Scope.wildcard) && !scopes?.includes(`zone:${chainId}:read`) && !scopes?.includes(`zone:${chainId}:write`) ) throw new PolicyDeniedError( `Chain id ${chainId} is a zone. Use an API key granting \`zone:${chainId}:read\` or \`zone:${chainId}:write\`.`, ) } if ( principal?.type === 'api_key' && principal.environment === 'sandbox' && Viem.isMainnet(zone?.sourceId ?? chainId) ) throw new PolicyDeniedError('Sandbox API keys only support testnet. Use a testnet challenge.') } export declare namespace assertChainAccess { /** Chain-selection inputs. */ type Options = { /** Resolved credential chain. */ chainId: number /** Authenticated request principal. */ principal?: Auth.Principal | undefined /** Chains served by this API deployment. */ supportedChainIds: ReadonlySet /** Configured Zones and their parent chains. */ zones: App.Environment['Variables']['zones'] } } /** Authorizes managed fee sponsorship for one broadcast request. */ export async function authorizeFeePayer( options: authorizeFeePayer.Options, ): Promise { const { chainId, db, feePayer, input, principal, zones } = options if (!feePayer || !requiresFeePayer(input)) return feePayer if (principal?.type !== 'api_key') throw new PolicyDeniedError('Fee sponsorship requires an API key.') if (!Viem.isMainnet(zones.get(chainId)?.sourceId ?? chainId)) return feePayer if (principal.environment !== 'production') throw new PolicyDeniedError('Mainnet fee sponsorship requires a production API key.') const status = await Billing.status(db, principal.orgId) if (status !== 'active') throw new PolicyDeniedError( status === 'past_due' ? 'Billing is past due.' : 'Active billing is required for mainnet fee sponsorship.', ) return feePayer } export declare namespace authorizeFeePayer { /** Dependencies used to authorize managed fee sponsorship. */ type Options = { /** Credential chain. */ chainId: number /** Primary database for authoritative billing enforcement. */ db: Db.Db /** Managed fee-payer account, when configured. */ feePayer?: LocalAccount | undefined /** MPP credential being broadcast. */ input: Mpp.RelayInput /** Authenticated request principal. */ principal?: Auth.Principal | undefined /** Configured Zones and their parent chains. */ zones: App.Environment['Variables']['zones'] } } function record(value: unknown): Record | undefined { return value && typeof value === 'object' && !Array.isArray(value) ? (value as Record) : undefined } function number(value: unknown): number | undefined { return typeof value === 'number' && Number.isSafeInteger(value) ? value : undefined } /** Raised when an MPP credential selects a chain this deployment does not serve. */ export class UnsupportedChainError extends Error { override name = 'Mpp.Policy.UnsupportedChainError' constructor(chainId: number) { super(`Unsupported chain id ${chainId}.`) } } /** Raised when an MPP credential violates chain access or sponsorship policy. */ export class PolicyDeniedError extends Error { override name = 'Mpp.Policy.PolicyDeniedError' }