Skip to content
Open
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
54 changes: 54 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,57 @@ This is a template project with best-practice modules:
- Winterspec for defining the API
- bun testing
- Zustand store with zod definition for database state

## Fake Payment API

This project includes a fake payment API for exercising bounty payout flows
without moving real money.

### Send a payment

```http
POST /payments/send
```

```json
{
"recipient": "maintainer@example.com",
"amount": 10,
"currency": "USD",
"owner": "tscircuit",
"repo": "fake-algora",
"repository": "tscircuit/fake-algora",
"issue_number": 1,
"bounty_id": "bounty_123",
"idempotency_key": "retry-safe-payment"
}
```

The response includes the fake `payment` and an `idempotent` boolean. Reusing
the same `idempotency_key` returns the original payment instead of creating a
duplicate.

### Read payments

```http
GET /payments/get?payment_id=0
GET /payments/list?recipient=maintainer@example.com&status=pending
GET /payments/list?owner=tscircuit&repo=fake-algora&issue_number=1
```

List filters support `recipient`, `status`, `owner`, `repo`, `repository`,
`bounty_id`, and `issue_number`.

### Update payment status

```http
POST /payments/complete
POST /payments/cancel
POST /payments/fail
```

```json
{ "payment_id": "0" }
```

Cancel and fail also accept `cancel_reason` and `failure_reason` respectively.
Binary file modified bun.lockb
Binary file not shown.
144 changes: 139 additions & 5 deletions lib/db/db-client.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,44 @@
import { createStore, type StoreApi } from "zustand/vanilla"
import { type HoistedStoreApi, hoist } from "zustand-hoist"
import { combine } from "zustand/middleware"
import { immer } from "zustand/middleware/immer"
import { hoist, type HoistedStoreApi } from "zustand-hoist"
import { type StoreApi, createStore } from "zustand/vanilla"
import {
type Payment,
type PaymentStatus,
type Thing,
databaseSchema,
} from "./schema.ts"

import { databaseSchema, type DatabaseSchema, type Thing } from "./schema.ts"
import { combine } from "zustand/middleware"
type CreatePaymentInput = Omit<
Payment,
| "payment_id"
| "status"
| "created_at"
| "updated_at"
| "completed_at"
| "canceled_at"
| "failed_at"
| "cancel_reason"
| "failure_reason"
>

type PaymentFilters = {
recipient?: string
status?: PaymentStatus
owner?: string
repo?: string
repository?: string
bounty_id?: string
issue_number?: number
}

export const createDatabase = () => {
return hoist(createStore(initializer))
}

export type DbClient = ReturnType<typeof createDatabase>

const initializer = combine(databaseSchema.parse({}), (set) => ({
const initializer = combine(databaseSchema.parse({}), (set, get) => ({
addThing: (thing: Omit<Thing, "thing_id">) => {
set((state) => ({
things: [
Expand All @@ -21,4 +48,111 @@ const initializer = combine(databaseSchema.parse({}), (set) => ({
idCounter: state.idCounter + 1,
}))
},
sendPayment: (input: CreatePaymentInput) => {
if (input.idempotency_key) {
const existingPayment = get().payments.find(
(item) => item.idempotency_key === input.idempotency_key,
)

if (existingPayment) return existingPayment
}

const now = new Date().toISOString()
const payment: Payment = {
...input,
payment_id: get().paymentIdCounter.toString(),
status: "pending",
created_at: now,
updated_at: now,
}

set((state) => ({
payments: [...state.payments, payment],
paymentIdCounter: state.paymentIdCounter + 1,
}))

return payment
},
listPayments: (filters: PaymentFilters = {}) => {
return get().payments.filter((payment) => {
if (filters.recipient && payment.recipient !== filters.recipient) {
return false
}
if (filters.status && payment.status !== filters.status) {
return false
}
if (filters.owner && payment.owner !== filters.owner) {
return false
}
if (filters.repo && payment.repo !== filters.repo) {
return false
}
if (filters.repository && payment.repository !== filters.repository) {
return false
}
if (filters.bounty_id && payment.bounty_id !== filters.bounty_id) {
return false
}
if (
filters.issue_number !== undefined &&
payment.issue_number !== filters.issue_number
) {
return false
}
return true
})
},
getPayment: (paymentId: string) => {
return get().payments.find((payment) => payment.payment_id === paymentId)
},
completePayment: (paymentId: string) => {
return get().updatePaymentStatus(paymentId, "completed")
},
cancelPayment: (paymentId: string, cancelReason?: string) => {
return get().updatePaymentStatus(paymentId, "canceled", {
cancel_reason: cancelReason,
})
},
failPayment: (paymentId: string, failureReason?: string) => {
return get().updatePaymentStatus(paymentId, "failed", {
failure_reason: failureReason,
})
},
updatePaymentStatus: (
paymentId: string,
status: Exclude<PaymentStatus, "pending">,
options: { cancel_reason?: string; failure_reason?: string } = {},
) => {
const existingPayment = get().payments.find(
(payment) => payment.payment_id === paymentId,
)

if (!existingPayment) return undefined

const now = new Date().toISOString()
const payment: Payment = {
...existingPayment,
status,
updated_at: now,
completed_at: status === "completed" ? now : existingPayment.completed_at,
canceled_at: status === "canceled" ? now : existingPayment.canceled_at,
failed_at: status === "failed" ? now : existingPayment.failed_at,
cancel_reason:
status === "canceled"
? options.cancel_reason
: existingPayment.cancel_reason,
failure_reason:
status === "failed"
? options.failure_reason
: existingPayment.failure_reason,
}

set((state) => ({
payments: state.payments.map((item) =>
item.payment_id === paymentId ? payment : item,
),
}))

return payment
},
}))
32 changes: 32 additions & 0 deletions lib/db/schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,40 @@ export const thingSchema = z.object({
})
export type Thing = z.infer<typeof thingSchema>

export const paymentStatusSchema = z.enum([
"pending",
"completed",
"canceled",
"failed",
])
export type PaymentStatus = z.infer<typeof paymentStatusSchema>

export const paymentSchema = z.object({
payment_id: z.string(),
recipient: z.string(),
amount: z.number(),
currency: z.string(),
status: paymentStatusSchema,
owner: z.string().optional(),
repo: z.string().optional(),
bounty_id: z.string().optional(),
issue_number: z.number().optional(),
repository: z.string().optional(),
idempotency_key: z.string().optional(),
cancel_reason: z.string().optional(),
failure_reason: z.string().optional(),
created_at: z.string(),
updated_at: z.string(),
completed_at: z.string().optional(),
canceled_at: z.string().optional(),
failed_at: z.string().optional(),
})
export type Payment = z.infer<typeof paymentSchema>

export const databaseSchema = z.object({
idCounter: z.number().default(0),
paymentIdCounter: z.number().default(0),
things: z.array(thingSchema).default([]),
payments: z.array(paymentSchema).default([]),
})
export type DatabaseSchema = z.infer<typeof databaseSchema>
23 changes: 23 additions & 0 deletions routes/payments/cancel.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

const cancelPaymentBodySchema = z.object({
payment_id: z.string().min(1),
cancel_reason: z.string().min(1).optional(),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: cancelPaymentBodySchema,
jsonResponse: z.object({
payment: paymentSchema.nullable(),
}),
})(async (req, ctx) => {
const { payment_id, cancel_reason } = cancelPaymentBodySchema.parse(
await req.json(),
)
const payment = ctx.db.cancelPayment(payment_id, cancel_reason)

return ctx.json({ payment: payment ?? null })
})
20 changes: 20 additions & 0 deletions routes/payments/complete.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

const completePaymentBodySchema = z.object({
payment_id: z.string().min(1),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: completePaymentBodySchema,
jsonResponse: z.object({
payment: paymentSchema.nullable(),
}),
})(async (req, ctx) => {
const { payment_id } = completePaymentBodySchema.parse(await req.json())
const payment = ctx.db.completePayment(payment_id)

return ctx.json({ payment: payment ?? null })
})
23 changes: 23 additions & 0 deletions routes/payments/fail.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

const failPaymentBodySchema = z.object({
payment_id: z.string().min(1),
failure_reason: z.string().min(1).optional(),
})

export default withRouteSpec({
methods: ["POST"],
jsonBody: failPaymentBodySchema,
jsonResponse: z.object({
payment: paymentSchema.nullable(),
}),
})(async (req, ctx) => {
const { payment_id, failure_reason } = failPaymentBodySchema.parse(
await req.json(),
)
const payment = ctx.db.failPayment(payment_id, failure_reason)

return ctx.json({ payment: payment ?? null })
})
16 changes: 16 additions & 0 deletions routes/payments/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { paymentSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["GET"],
jsonResponse: z.object({
payment: paymentSchema.nullable(),
}),
})((req, ctx) => {
const url = new URL(req.url)
const paymentId = url.searchParams.get("payment_id")
const payment = paymentId ? ctx.db.getPayment(paymentId) : undefined

return ctx.json({ payment: payment ?? null })
})
26 changes: 26 additions & 0 deletions routes/payments/list.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { paymentSchema, paymentStatusSchema } from "lib/db/schema"
import { withRouteSpec } from "lib/middleware/with-winter-spec"
import { z } from "zod"

export default withRouteSpec({
methods: ["GET"],
jsonResponse: z.object({
payments: z.array(paymentSchema),
}),
})((req, ctx) => {
const url = new URL(req.url)
const issueNumber = url.searchParams.get("issue_number")
const status = paymentStatusSchema.safeParse(url.searchParams.get("status"))

const payments = ctx.db.listPayments({
recipient: url.searchParams.get("recipient") ?? undefined,
status: status.success ? status.data : undefined,
owner: url.searchParams.get("owner") ?? undefined,
repo: url.searchParams.get("repo") ?? undefined,
repository: url.searchParams.get("repository") ?? undefined,
bounty_id: url.searchParams.get("bounty_id") ?? undefined,
issue_number: issueNumber ? Number(issueNumber) : undefined,
})

return ctx.json({ payments })
})
Loading