2022-09-23 14:02:40 +00:00
|
|
|
import * as admin from 'firebase-admin'
|
|
|
|
import { z } from 'zod'
|
|
|
|
|
|
|
|
import { Contract } from '../../common/contract'
|
|
|
|
import { getUser } from './utils'
|
|
|
|
|
|
|
|
import { isAdmin, isManifoldId } from '../../common/envs/constants'
|
|
|
|
import { APIError, newEndpoint, validate } from './api'
|
|
|
|
|
|
|
|
const bodySchema = z.object({
|
|
|
|
contractId: z.string(),
|
2022-09-23 14:14:41 +00:00
|
|
|
closeTime: z.number().int().nonnegative().optional(),
|
2022-09-23 14:02:40 +00:00
|
|
|
})
|
|
|
|
|
|
|
|
export const closemarket = newEndpoint({}, async (req, auth) => {
|
2022-09-23 14:14:41 +00:00
|
|
|
const { contractId, closeTime } = validate(bodySchema, req.body)
|
2022-09-23 14:02:40 +00:00
|
|
|
const contractDoc = firestore.doc(`contracts/${contractId}`)
|
|
|
|
const contractSnap = await contractDoc.get()
|
|
|
|
if (!contractSnap.exists)
|
|
|
|
throw new APIError(404, 'No contract exists with the provided ID')
|
|
|
|
const contract = contractSnap.data() as Contract
|
2022-09-23 14:14:41 +00:00
|
|
|
const { creatorId } = contract
|
2022-09-23 14:02:40 +00:00
|
|
|
const firebaseUser = await admin.auth().getUser(auth.uid)
|
|
|
|
|
|
|
|
if (
|
|
|
|
creatorId !== auth.uid &&
|
|
|
|
!isManifoldId(auth.uid) &&
|
|
|
|
!isAdmin(firebaseUser.email)
|
|
|
|
)
|
|
|
|
throw new APIError(403, 'User is not creator of contract')
|
|
|
|
|
|
|
|
const now = Date.now()
|
2022-09-23 14:14:41 +00:00
|
|
|
if (!closeTime && contract.closeTime && contract.closeTime < now)
|
2022-09-23 14:02:40 +00:00
|
|
|
throw new APIError(400, 'Contract already closed')
|
|
|
|
|
2022-09-23 14:14:41 +00:00
|
|
|
if (closeTime && closeTime < now)
|
|
|
|
throw new APIError(
|
|
|
|
400,
|
|
|
|
'Close time must be in the future. ' +
|
|
|
|
'Alternatively, do not provide a close time to close immediately.'
|
|
|
|
)
|
|
|
|
|
2022-09-23 14:02:40 +00:00
|
|
|
const creator = await getUser(creatorId)
|
|
|
|
if (!creator) throw new APIError(500, 'Creator not found')
|
|
|
|
|
|
|
|
const updatedContract = {
|
|
|
|
...contract,
|
2022-09-23 14:14:41 +00:00
|
|
|
closeTime: closeTime ? closeTime : now,
|
2022-09-23 14:02:40 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
await contractDoc.update(updatedContract)
|
|
|
|
|
|
|
|
console.log('contract ', contractId, 'closed')
|
|
|
|
|
|
|
|
return updatedContract
|
|
|
|
})
|
|
|
|
|
|
|
|
const firestore = admin.firestore()
|