Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
-- CreateTable
CREATE TABLE "video_generation_x402" (
"videoId" TEXT NOT NULL,
"wallet" TEXT,
"userId" UUID,
"echoAppId" UUID,
"cost" DECIMAL(65,30) NOT NULL,
"createdAt" TIMESTAMPTZ(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"expiresAt" TIMESTAMPTZ(6) NOT NULL,
"isFinal" BOOLEAN NOT NULL DEFAULT false,

CONSTRAINT "video_generation_x402_pkey" PRIMARY KEY ("videoId")
);

-- AddForeignKey
ALTER TABLE "video_generation_x402" ADD CONSTRAINT "video_generation_x402_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;

-- AddForeignKey
ALTER TABLE "video_generation_x402" ADD CONSTRAINT "video_generation_x402_echoAppId_fkey" FOREIGN KEY ("echoAppId") REFERENCES "echo_apps"("id") ON DELETE CASCADE ON UPDATE CASCADE;
17 changes: 17 additions & 0 deletions packages/app/control/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ model User {
latestFreeCreditsVersion Decimal?
OutboundEmailSent OutboundEmailSent[]
creditGrantCodeUsages CreditGrantCodeUsage[]
VideoGenerationX402 VideoGenerationX402[]

@@map("users")
}
Expand Down Expand Up @@ -107,6 +108,7 @@ model EchoApp {
appSessions AppSession[]
payouts Payout[]
OutboundEmailSent OutboundEmailSent[]
VideoGenerationX402 VideoGenerationX402[]

@@map("echo_apps")
}
Expand Down Expand Up @@ -489,3 +491,18 @@ model OutboundEmailSent {
@@index([emailCampaignId])
@@map("outbound_emails_sent")
}

model VideoGenerationX402 {
videoId String @id
wallet String?
userId String? @db.Uuid
echoAppId String? @db.Uuid
cost Decimal
createdAt DateTime @default(now()) @db.Timestamptz(6)
expiresAt DateTime @db.Timestamptz(6)
isFinal Boolean @default(false)

user User? @relation(fields: [userId], references: [id], onDelete: Cascade)
echoApp EchoApp? @relation(fields: [echoAppId], references: [id], onDelete: Cascade)
@@map("video_generation_x402")
}
29 changes: 29 additions & 0 deletions packages/app/server/src/handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import {
import { Decimal } from '@prisma/client/runtime/library';
import logger from 'logger';
import { Request, Response } from 'express';
import { ProviderType } from 'providers/ProviderType';

export async function settle(
req: Request,
Expand Down Expand Up @@ -141,6 +142,19 @@ export async function handleX402Request({
provider,
isStream
);
const transaction = transactionResult.transaction;


if (provider.getType() === ProviderType.OPENAI_VIDEOS) {
await prisma.videoGenerationX402.create({
data: {
videoId: transaction.metadata.providerId,
wallet: payload.authorization.from,
cost: transaction.rawTransactionCost,
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 1),
},
});
}

modelRequestService.handleResolveResponse(
res,
Expand Down Expand Up @@ -201,10 +215,25 @@ export async function handleApiKeyRequest({
isStream
);



// There is no actual refund, this logs if we underestimate the raw cost
calculateRefundAmount(maxCost, transaction.rawTransactionCost);

modelRequestService.handleResolveResponse(res, isStream, data);

await echoControlService.createTransaction(transaction, maxCost);

if (provider.getType() === ProviderType.OPENAI_VIDEOS) {
const transactionCost = await echoControlService.computeTransactionCosts(transaction, null);
await prisma.videoGenerationX402.create({
data: {
videoId: transaction.metadata.providerId,
userId: echoControlService.getUserId()!,
echoAppId: echoControlService.getEchoAppId()!,
cost: transactionCost.totalTransactionCost,
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 1),
},
});
}
}
65 changes: 65 additions & 0 deletions packages/app/server/src/providers/OpenAIVideoProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import { Request } from 'express';
import { ProviderType } from './ProviderType';
import { EscrowRequest } from '../middleware/transaction-escrow-middleware';
import { Response } from 'express';
import { transfer } from 'transferWithAuth';
import { getVideoModelPrice } from 'services/AccountingService';
import { HttpError, UnknownModelError } from 'errors/http';
import { Decimal } from 'generated/prisma/runtime/library';
import { Transaction } from '../types';
import { prisma } from '../server';
import { EchoDbService } from '../services/DbService';
import logger from '../logger';
import { decimalToUsdcBigInt } from 'utils';

export class OpenAIVideoProvider extends BaseProvider {
static detectPassthroughProxy(
Expand Down Expand Up @@ -173,9 +175,72 @@ export class OpenAIVideoProvider extends BaseProvider {
}

const responseData = await response.json();
switch (responseData.status) {
case 'completed':
await this.handleSuccessfulVideoGeneration(responseData.id as string);
break;
case 'failed':
await this.handleFailedVideoGeneration(responseData.id as string);
break;
default:
break;
}
res.json(responseData);
}

// ====== Refund methods ======
private async handleSuccessfulVideoGeneration(
videoId: string
): Promise<void> {
await prisma.$transaction(async tx => {
const result = await tx.$queryRawUnsafe(
`SELECT * FROM "video_generation_x402" WHERE "videoId" = $1 FOR UPDATE`,
videoId
);
const video = (result as any[])[0];
if (video && !video.isFinal) {
await tx.videoGenerationX402.update({
where: {
videoId: video.videoId,
},
data: {
isFinal: true,
},
});
}
});
}

private async handleFailedVideoGeneration(videoId: string): Promise<void> {
await prisma.$transaction(async tx => {
const result = await tx.$queryRawUnsafe(
`SELECT * FROM "video_generation_x402" WHERE "videoId" = $1 FOR UPDATE`,
videoId
);
const video = (result as any[])[0];
// Exit early if video already final
if (!video || video.isFinal) {
return;
}
if (video.wallet) {
const refundAmount = decimalToUsdcBigInt(video.cost);
await transfer(video.wallet as `0x${string}`, refundAmount);
}
if (video.userId) {
// Proccess the refund to the user. There is some level of complexity here since there is a markup. Not as simple as just credit grant.
logger.info(`Refunding video generation ${video.videoId} to user ${video.userId} on app ${video.echoAppId}`);
}
await tx.videoGenerationX402.update({
where: {
videoId: video.videoId,
},
data: {
isFinal: true,
},
});
});
}

// ========== Video Download Handling ==========

private isVideoContentDownload(path: string): boolean {
Expand Down
Loading