|
| 1 | +import { supabase } from '../config/database'; |
| 2 | +import logger from '../config/logger'; |
| 3 | +import { |
| 4 | + paymentChannelService, |
| 5 | + type PaymentChannelRecord, |
| 6 | +} from './payment-channel-service'; |
| 7 | + |
| 8 | +export type SettlementSchedule = 'monthly' | 'quarterly'; |
| 9 | + |
| 10 | +export interface ChannelPaymentLog { |
| 11 | + channelId: string; |
| 12 | + userId: string; |
| 13 | + subscriptionId: string; |
| 14 | + amount: number; |
| 15 | + sequenceNumber: number; |
| 16 | +} |
| 17 | + |
| 18 | +export interface ChannelSettlementCandidate { |
| 19 | + channelId: string; |
| 20 | + userId: string; |
| 21 | + executorBalance: number; |
| 22 | +} |
| 23 | + |
| 24 | +export class ChannelStateService { |
| 25 | + /** |
| 26 | + * Returns the newest active channel with sufficient off-chain balance. |
| 27 | + */ |
| 28 | + async findPayableChannel( |
| 29 | + userId: string, |
| 30 | + amount: number, |
| 31 | + ): Promise<PaymentChannelRecord | null> { |
| 32 | + const channels = await paymentChannelService.listChannels(userId); |
| 33 | + for (const channel of channels) { |
| 34 | + if (channel.state !== 'active') continue; |
| 35 | + const balance = |
| 36 | + channel.channelState?.userBalance ?? Number.parseFloat(channel.balance); |
| 37 | + if (balance >= amount) return channel; |
| 38 | + } |
| 39 | + return null; |
| 40 | + } |
| 41 | + |
| 42 | + /** |
| 43 | + * Applies an off-chain state update and records the payment locally (not on-chain). |
| 44 | + */ |
| 45 | + async applyRenewalPayment( |
| 46 | + channelId: string, |
| 47 | + userId: string, |
| 48 | + subscriptionId: string, |
| 49 | + amount: number, |
| 50 | + ): Promise<PaymentChannelRecord> { |
| 51 | + const updated = await paymentChannelService.applyOffChainRenewal( |
| 52 | + channelId, |
| 53 | + userId, |
| 54 | + amount, |
| 55 | + ); |
| 56 | + |
| 57 | + await this.logChannelPayment({ |
| 58 | + channelId, |
| 59 | + userId, |
| 60 | + subscriptionId, |
| 61 | + amount, |
| 62 | + sequenceNumber: updated.channelState?.sequenceNumber ?? 0, |
| 63 | + }); |
| 64 | + |
| 65 | + return updated; |
| 66 | + } |
| 67 | + |
| 68 | + async logChannelPayment(payment: ChannelPaymentLog): Promise<void> { |
| 69 | + const { error } = await supabase.from('channel_payments').insert({ |
| 70 | + channel_id: payment.channelId, |
| 71 | + user_id: payment.userId, |
| 72 | + subscription_id: payment.subscriptionId, |
| 73 | + amount: payment.amount, |
| 74 | + sequence_number: payment.sequenceNumber, |
| 75 | + created_at: new Date().toISOString(), |
| 76 | + }); |
| 77 | + |
| 78 | + if (error) { |
| 79 | + logger.warn('Failed to log channel payment', { |
| 80 | + channelId: payment.channelId, |
| 81 | + error: error.message, |
| 82 | + }); |
| 83 | + } |
| 84 | + } |
| 85 | + |
| 86 | + async getSettlementSchedule(userId: string): Promise<SettlementSchedule> { |
| 87 | + const { data } = await supabase |
| 88 | + .from('profiles') |
| 89 | + .select('channel_settlement_schedule') |
| 90 | + .eq('id', userId) |
| 91 | + .maybeSingle(); |
| 92 | + |
| 93 | + return data?.channel_settlement_schedule === 'quarterly' ? 'quarterly' : 'monthly'; |
| 94 | + } |
| 95 | + |
| 96 | + /** |
| 97 | + * Active channels whose executor-side balance should be settled on-chain. |
| 98 | + */ |
| 99 | + async getChannelsDueForSettlement(): Promise<ChannelSettlementCandidate[]> { |
| 100 | + const { data: channels, error } = await supabase |
| 101 | + .from('payment_channels') |
| 102 | + .select('id, user_id, channel_state, last_settlement_at, state') |
| 103 | + .eq('state', 'active'); |
| 104 | + |
| 105 | + if (error) throw error; |
| 106 | + |
| 107 | + const due: ChannelSettlementCandidate[] = []; |
| 108 | + const now = Date.now(); |
| 109 | + |
| 110 | + for (const row of channels ?? []) { |
| 111 | + const state = row.channel_state as { executorBalance?: number } | null; |
| 112 | + const executorBalance = state?.executorBalance ?? 0; |
| 113 | + if (executorBalance <= 0) continue; |
| 114 | + |
| 115 | + const schedule = await this.getSettlementSchedule(row.user_id as string); |
| 116 | + const intervalMs = |
| 117 | + schedule === 'quarterly' |
| 118 | + ? 90 * 24 * 60 * 60 * 1000 |
| 119 | + : 30 * 24 * 60 * 60 * 1000; |
| 120 | + |
| 121 | + const lastSettlement = row.last_settlement_at |
| 122 | + ? new Date(row.last_settlement_at as string).getTime() |
| 123 | + : 0; |
| 124 | + |
| 125 | + if (now - lastSettlement >= intervalMs) { |
| 126 | + due.push({ |
| 127 | + channelId: row.id as string, |
| 128 | + userId: row.user_id as string, |
| 129 | + executorBalance, |
| 130 | + }); |
| 131 | + } |
| 132 | + } |
| 133 | + |
| 134 | + return due; |
| 135 | + } |
| 136 | + |
| 137 | + async markChannelSettled(channelId: string, userId: string): Promise<void> { |
| 138 | + const { error } = await supabase |
| 139 | + .from('payment_channels') |
| 140 | + .update({ |
| 141 | + last_settlement_at: new Date().toISOString(), |
| 142 | + updated_at: new Date().toISOString(), |
| 143 | + }) |
| 144 | + .eq('id', channelId) |
| 145 | + .eq('user_id', userId); |
| 146 | + |
| 147 | + if (error) throw error; |
| 148 | + } |
| 149 | +} |
| 150 | + |
| 151 | +export const channelStateService = new ChannelStateService(); |
0 commit comments