Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use server time for sending message #678

Merged
merged 1 commit into from
Jun 15, 2024
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
25 changes: 19 additions & 6 deletions src/components/chats/ChatForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import useLoginOption from '@/hooks/useLoginOption'
import useRequestTokenAndSendMessage from '@/hooks/useRequestTokenAndSendMessage'
import { showErrorToast } from '@/hooks/useToastError'
import { useConfigContext } from '@/providers/config/ConfigProvider'
import { getPostQuery } from '@/services/api/query'
import { getPostQuery, getServerTime } from '@/services/api/query'
import { apiInstance } from '@/services/api/utils'
import { useSendOffchainMessage } from '@/services/datahub/posts/mutation'
import {
Expand Down Expand Up @@ -237,11 +237,24 @@ export default function ChatForm({
const isOffchainPosting =
env.NEXT_PUBLIC_OFFCHAIN_POSTING_HUBS.includes(hubId)
if (isOffchainPosting) {
sendOffchainMessage({
...messageParams,
uuid: crypto.randomUUID(),
timestamp: Date.now(),
})
try {
const serverTime = await getServerTime()
sendOffchainMessage({
...messageParams,
uuid: crypto.randomUUID(),
timestamp: serverTime,
})
} catch (err) {
showErrorSendingMessageToast(
err,
'Failed to get server time',
messageParams,
{
reloadUnsentMessage,
setIsDisabledInput,
}
)
}
} else if (shouldSendMessage) {
sendMessage(messageParams)
} else {
Expand Down
15 changes: 15 additions & 0 deletions src/pages/api/time.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { ApiResponse, handlerWrapper } from '@/server/common'
import { z } from 'zod'

export type ApiTimeResponse = ApiResponse<{ time: number }>

export default handlerWrapper({
inputSchema: z.any(),
dataGetter: (req) => req.query,
})<ApiTimeResponse>({
errorLabel: 'time',
allowedMethods: ['GET'],
handler: async (_, __, res) => {
res.json({ success: true, message: 'OK', time: Date.now() })
},
})
6 changes: 6 additions & 0 deletions src/services/api/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
import { Identities } from '@/pages/api/identities'
import { ApiNftParams, ApiNftResponse } from '@/pages/api/nft'
import { ApiStakedParams, ApiStakedResponse } from '@/pages/api/staked'
import { ApiTimeResponse } from '@/pages/api/time'
import { createQuery, poolQuery } from '@/subsocial-query'
import { PostData } from '@subsocial/api/types'
import { useMemo } from 'react'
Expand Down Expand Up @@ -165,3 +166,8 @@ export const getHasUserStakedQuery = createQuery({
enabled: !!data?.address,
}),
})

export async function getServerTime() {
const res = await apiInstance.get('/api/time')
return (res.data as ApiTimeResponse).time
}
2 changes: 1 addition & 1 deletion src/services/datahub/content-staking/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { getAddressLikeCountToPostQuery, getSuperLikeCountQuery } from './query'
type CreateSuperLikeArgs =
SocialCallDataArgs<'synth_active_staking_create_super_like'>
async function createSuperLike(params: DatahubParams<CreateSuperLikeArgs>) {
const input = createSocialDataEventPayload(
const input = await createSocialDataEventPayload(
socialCallName.synth_active_staking_create_super_like,
params,
params.args
Expand Down
2 changes: 1 addition & 1 deletion src/services/datahub/identity/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export async function linkIdentity(
id,
provider,
}
const input = createSocialDataEventPayload(
const input = await createSocialDataEventPayload(
socialCallName.synth_create_linked_identity,
params,
eventArgs
Expand Down
6 changes: 5 additions & 1 deletion src/services/datahub/moderation/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ async function moderationActions<T extends ModerationCallNames>(
) {
if (!data) return null

const input = createSignedSocialDataEvent(data.callName, data, data.args)
const input = await createSignedSocialDataEvent(
data.callName,
data,
data.args
)
const actionRes = await apiInstance.post<
any,
AxiosResponse<ApiDatahubModerationResponse>,
Expand Down
16 changes: 12 additions & 4 deletions src/services/datahub/posts/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ async function createPostData(
ipfsSrc: cid,
}

const input = createSignedSocialDataEvent(
const input = await createSignedSocialDataEvent(
socialCallName.create_post,
params,
eventArgs,
Expand Down Expand Up @@ -112,7 +112,7 @@ async function updatePostData(
postId,
ipfsSrc: content?.cid ?? null,
}
const input = createSignedSocialDataEvent(
const input = await createSignedSocialDataEvent(
socialCallName.update_post,
params,
eventArgs,
Expand Down Expand Up @@ -165,7 +165,11 @@ async function notifyCreatePostFailedOrRetryStatus(
}
}

const input = createSignedSocialDataEvent(event.name, params, event.args)
const input = await createSignedSocialDataEvent(
event.name,
params,
event.args
)

await apiInstance.post<any, any, ApiDatahubPostMutationBody>(
'/api/datahub/post',
Expand Down Expand Up @@ -217,7 +221,11 @@ async function notifyUpdatePostFailedOrRetryStatus(
}
}

const input = createSignedSocialDataEvent(event.name, params, event.args)
const input = await createSignedSocialDataEvent(
event.name,
params,
event.args
)

await apiInstance.post<any, any, ApiDatahubPostMutationBody>(
'/api/datahub/post',
Expand Down
2 changes: 1 addition & 1 deletion src/services/datahub/referral/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import { DatahubParams, createSocialDataEventPayload } from '../utils'
type SetReferrerIdArgs =
SocialCallDataArgs<'synth_social_profile_add_referrer_id'>
async function setReferrerId(params: DatahubParams<SetReferrerIdArgs>) {
const input = createSocialDataEventPayload(
const input = await createSocialDataEventPayload(
socialCallName.synth_social_profile_add_referrer_id,
params,
params.args
Expand Down
10 changes: 6 additions & 4 deletions src/services/datahub/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import { GraphQLClient, RequestOptions, Variables } from 'graphql-request'
import { Client, createClient } from 'graphql-ws'
import ws from 'isomorphic-ws'
import sortKeysRecursive from 'sort-keys-recursive'
import { getServerTime } from '../api/query'

dayjs.extend(utc)
dayjs.extend(isoWeek)
Expand Down Expand Up @@ -91,7 +92,7 @@ export function signDatahubPayload(
payload.sig = hexSig
}

export function createSocialDataEventPayload<
export async function createSocialDataEventPayload<
T extends keyof typeof socialCallName
>(
callName: T,
Expand All @@ -109,6 +110,7 @@ export function createSocialDataEventPayload<
content?: PostContent
) {
const owner = proxyToAddress || address
const serverTime = await getServerTime()
const payload: SocialEventDataApiInput = {
protVersion: socialEventProtVersion['0.1'],
dataType: isOffchain
Expand All @@ -118,7 +120,7 @@ export function createSocialDataEventPayload<
name: callName,
signer: owner || '',
args: JSON.stringify(eventArgs),
timestamp: timestamp || Date.now(),
timestamp: timestamp || serverTime,
uuid: uuid || crypto.randomUUID(),
proxy: proxyToAddress ? address : undefined,
},
Expand All @@ -129,15 +131,15 @@ export function createSocialDataEventPayload<
return payload
}

export function createSignedSocialDataEvent<
export async function createSignedSocialDataEvent<
T extends keyof typeof socialCallName
>(
callName: T,
params: DatahubParams<{}>,
eventArgs: SocialCallDataArgs<T>,
content?: PostContent
) {
const payload = createSocialDataEventPayload(
const payload = await createSocialDataEventPayload(
callName,
params,
eventArgs,
Expand Down
13 changes: 9 additions & 4 deletions src/services/subsocial/commentIds/mutation.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { getMaxMessageLength } from '@/constants/chat'
import useWaitHasEnergy from '@/hooks/useWaitHasEnergy'
import { useRevalidateChatPage, useSaveFile } from '@/services/api/mutation'
import { getPostQuery } from '@/services/api/query'
import { getPostQuery, getServerTime } from '@/services/api/query'
import { isPersistentId } from '@/services/datahub/posts/fetcher'
import datahubMutation from '@/services/datahub/posts/mutation'
import { isDatahubAvailable } from '@/services/datahub/utils'
Expand Down Expand Up @@ -163,7 +163,11 @@ export function useSendMessage(config?: MutationConfig<SendMessageParams>) {
}
},
onSend: allowWindowUnload,
onError: ({ data, context, address }, error, isAfterTxGenerated) => {
onError: async (
{ data, context, address },
error,
isAfterTxGenerated
) => {
allowWindowUnload()
const content = context.content
const optimisticId = content.optimisticId
Expand All @@ -182,14 +186,15 @@ export function useSendMessage(config?: MutationConfig<SendMessageParams>) {
getPostQuery.invalidate(client, data.messageIdToEdit)
}
} else {
const serverTime = await getServerTime()
if (isCreating) {
datahubMutation.notifyCreatePostFailedOrRetryStatus({
...getCurrentWallet(),
args: {
optimisticId,
reason: error,
},
timestamp: Date.now(),
timestamp: serverTime,
})
} else if (isUpdating) {
datahubMutation.notifyUpdatePostFailedOrRetryStatus({
Expand All @@ -198,7 +203,7 @@ export function useSendMessage(config?: MutationConfig<SendMessageParams>) {
postId: messageIdToEdit,
reason: error,
},
timestamp: Date.now(),
timestamp: serverTime,
})
}
}
Expand Down
9 changes: 5 additions & 4 deletions src/services/subsocial/posts/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
saveFile,
useRevalidateChatPage,
} from '@/services/api/mutation'
import { getPostQuery } from '@/services/api/query'
import { getPostQuery, getServerTime } from '@/services/api/query'
import { isPersistentId } from '@/services/datahub/posts/fetcher'
import datahubMutation from '@/services/datahub/posts/mutation'
import { isDatahubAvailable } from '@/services/datahub/utils'
Expand Down Expand Up @@ -270,14 +270,15 @@ export function useUpsertPost(
})
}
},
onError: ({ data, context }, error, isAfterTxGenerated) => {
onError: async ({ data, context }, error, isAfterTxGenerated) => {
const { action, payload } = checkAction(data)
if (!isAfterTxGenerated) return

const serverTime = await getServerTime()
if (action === 'create' && context.content.optimisticId) {
datahubMutation.notifyCreatePostFailedOrRetryStatus({
...getCurrentWallet(),
timestamp: Date.now(),
timestamp: serverTime,
args: {
optimisticId: context.content.optimisticId,
reason: error,
Expand All @@ -290,7 +291,7 @@ export function useUpsertPost(
postId: payload.postId,
reason: error,
},
timestamp: Date.now(),
timestamp: serverTime,
})
}
},
Expand Down
Loading