generated from scio-labs/inkathon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp-context.tsx
295 lines (266 loc) · 8.61 KB
/
app-context.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
'use client'
import { createContext, useEffect, useState } from 'react'
import { ContractIds } from '@/deployments/deployments'
import { useAccurast } from '@/deployments/use-accurast'
import {
contractQuery,
decodeOutput,
useInkathon,
useRegisteredContract,
} from '@scio-labs/use-inkathon'
import toast from 'react-hot-toast'
import { MessageProps } from '@/components/web3/message'
import { contractTxWithToast } from '@/utils/contract-tx-with-toast'
type AppContextProps = {
isChatroomActive: boolean
getMessages: (chatroomId: string) => Promise<void>
sendMessage: (newMessage: string) => Promise<void>
createChatroom: () => Promise<void>
deleteChatroom: () => Promise<void>
inviteFriends: (participants: string[]) => Promise<void>
joinChatroom: (chatroomId: string) => Promise<void>
refreshMessages: () => Promise<void>
viaAccurast: () => Promise<void>
messages: MessageProps[]
chatroomId: string | undefined
isAppLoading: boolean
isChatroomLoading: boolean
isMessagesLoading: boolean
}
const defaultData: AppContextProps = {
isChatroomActive: false,
getMessages: async (chatroomId: string) => {},
sendMessage: async (newMessage: string) => {},
createChatroom: async () => {},
deleteChatroom: async () => {},
inviteFriends: async (participants: string[]) => {},
joinChatroom: async (chatroomId: string) => {},
refreshMessages: async () => {},
viaAccurast: async () => {},
messages: [],
chatroomId: undefined,
isAppLoading: true,
isChatroomLoading: true,
isMessagesLoading: true,
}
export const AppContext = createContext(defaultData)
export function AppProvider({ children }: { children: React.ReactNode }) {
// app state
const [isChatroomActive, setIsChatroomActive] = useState(false)
const [chatroomId, setChatroomId] = useState<string>()
const [messages, setMessages] = useState<MessageProps[]>([])
// loading state
const [isAppLoading, setIsAppLoading] = useState(true)
const [isChatroomLoading, setIsChatroomLoading] = useState(true)
const [isMessagesLoading, setIsMessagesLoading] = useState(true)
// web3 state
const { api, activeAccount, activeSigner } = useInkathon()
const { contract } = useRegisteredContract(ContractIds.Chatroom)
const { id, send } = useAccurast()
// set app as loaded
useEffect(() => {
async function loadApp() {
if (activeAccount && contract && activeSigner && api) {
// check if the active account has an active chatroom, load it
const room = await queryChatroom(activeAccount.address)
// check if room object is not empty
if (!(Object.keys(room).length === 0 && room.constructor === Object)) {
setIsChatroomActive(true)
setChatroomId(activeAccount.address)
await getMessages(activeAccount.address)
} else {
// you haven't created a chatroom, so join one if you've been invited
setIsChatroomActive(false)
}
setIsAppLoading(false)
setIsChatroomLoading(false)
setIsMessagesLoading(false)
}
}
loadApp()
}, [activeAccount, contract, activeSigner, api])
// functions
// query chatroom
async function queryChatroom(_chatroomId: string): Promise<any> {
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again… chatroom')
return
}
try {
const result = await contractQuery(api, activeAccount.address, contract, 'getChatroom', {}, [
_chatroomId,
])
const { output, isError, decodedOutput } = decodeOutput(result, contract, 'getChatroom')
if (isError) throw new Error(decodedOutput)
if (!(Object.keys(output).length === 0 && output.constructor === Object)) {
// TODO change contract to output None and check for null here
return output
}
} catch (e) {
console.error(e)
toast.error('Error while loading chatroom. Try again…')
}
return {}
}
// Fetch messages
const getMessages = async (_chatroomId: string) => {
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again… mesasges')
return
}
setIsMessagesLoading(true)
try {
const result = await contractQuery(api, activeAccount.address, contract, 'getMessages', {}, [
_chatroomId,
])
const { output, isError, decodedOutput } = decodeOutput(result, contract, 'getMessages')
if (isError) throw new Error(decodedOutput)
setMessages(output)
} catch (e) {
console.error(e)
toast.error('Error while loading chatroom. Try again…')
setIsMessagesLoading(false)
} finally {
setIsMessagesLoading(false)
}
}
async function refreshMessages() {
// await getMessages(chatroomId)
}
// send a message
async function sendMessage(newMessage: string) {
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again…')
return
}
try {
await contractTxWithToast(api, activeAccount.address, contract, 'sendMessage', {}, [
chatroomId,
newMessage,
])
await getMessages(chatroomId!)
} catch (e) {
console.error(e)
} finally {
// refresh messages
}
}
async function createChatroom() {
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again…')
return
}
try {
await contractTxWithToast(api, activeAccount.address, contract, 'createChatroom', {}, [])
//set chatroomid to the caller of the create function
setChatroomId(activeAccount.address)
//fetch messages
await getMessages(activeAccount.address)
//set active chat to true
setIsChatroomActive(true)
} catch (e) {
console.error(e)
}
}
async function deleteChatroom() {
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again…')
return
}
// TODO include check that caller must be owner
try {
await contractTxWithToast(api, activeAccount.address, contract, 'deleteChatroom', {}, [
chatroomId,
])
} catch (e) {
console.error(e)
}
}
async function inviteFriends(participants: string[]) {
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again…')
return
}
try {
await contractTxWithToast(api, activeAccount.address, contract, 'invite', {}, [
chatroomId,
participants[0],
])
} catch (e) {
console.error(e)
}
}
// join chatroom
async function joinChatroom(joinChatroomId: string) {
setIsChatroomLoading(true)
setIsMessagesLoading(true)
if (!activeAccount || !contract || !activeSigner || !api) {
toast.error('Wallet not connected. Try again…')
return
}
//check if you've been invited to the chatroom
try {
const result = await contractQuery(
api,
activeAccount.address,
contract,
'isAParticipant',
{},
[joinChatroomId, activeAccount.address],
)
const { output, isError, decodedOutput } = decodeOutput(result, contract, 'isAParticipant')
if (isError) {
toast.error('Something went wrong')
throw new Error(decodedOutput)
}
if (!output) {
toast.error("You haven't been invited to this chatroom")
setIsChatroomLoading(false)
setIsMessagesLoading(false)
return
}
} catch (e) {
console.error(e)
toast.error("Error we couldn't verify your invitation. Try again…")
}
const room = await queryChatroom(joinChatroomId)
// check if room object is not empty
if (!(Object.keys(room).length === 0 && room.constructor === Object)) {
setIsChatroomActive(true)
setChatroomId(joinChatroomId)
setMessages(room.messages)
} else {
// you haven't created a chatroom, so join one if you've been invited
setIsChatroomActive(false)
}
setIsChatroomLoading(false)
setIsMessagesLoading(false)
}
// accurast
async function viaAccurast() {
// TODO additional testing & implementation
const res = await send(activeAccount?.address, '')
}
return (
<AppContext.Provider
value={{
isAppLoading,
isChatroomActive,
isChatroomLoading,
isMessagesLoading,
getMessages,
refreshMessages,
createChatroom,
deleteChatroom,
inviteFriends,
joinChatroom,
sendMessage,
viaAccurast,
messages,
chatroomId,
}}
>
{children}
</AppContext.Provider>
)
}