-
Notifications
You must be signed in to change notification settings - Fork 11
/
ao-gather.ts
275 lines (245 loc) · 8.18 KB
/
ao-gather.ts
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
import { createDataItemSigner } from "@permaweb/aoconnect";
import type Arweave from "arweave";
import EventEmitter from "eventemitter3";
import { AoProvider } from "./ao";
import { defaultArweave } from "./arweave";
export const aoGatherProcessId = "jDS4zJhkJynXllgWFRArilTdTnmCmCTzqNqohDY8v1Q";
export type ArweaveID = string;
export type ArweavePublicKey = string;
export type ConnectionID = ArweaveID;
export type ArweaveAddress = ArweaveID;
export type ContractPosition = {
x: number;
y: number;
};
export type ContractUser = {
processId: ArweaveID; // personal process id of the user for things like notification, mail, etc.
created: number;
lastSeen: number;
name: string;
avatar: string;
status: string;
currentWorldId: string;
following: {
[address: string]: boolean;
};
// blockList: ArweaveID[]; // disallows connection to specified users and prevent them from messaging/inviting the user to lobbies.
// preferences: UserSettings;
};
export type ContractUserWritable = Omit<
ContractUser,
"processId" | "created" | "lastSeen"
>;
export type ContractWorld = {
created: number;
lastActivity: number;
name: string;
description: string;
worldSize: {
w: number;
h: number;
}
worldType: string;
worldTheme: string;
spawnPosition: ContractPosition;
playerPositions: Record<ArweaveID, ContractPosition>;
};
export type ContractWorldIndex = Array<string>;
export type ContractPost = {
created: number;
author: string;
worldId: string;
type: string;
textOrTxId: string;
};
export type ContractPostWritable = Omit<ContractPost, "created" | "author">;
export interface AoGather {
signer: unknown;
arweave: Arweave;
getUsers(): Promise<Record<ArweaveID, ContractUser>>;
getWorldIndex(): Promise<ContractWorldIndex>;
getWorlds(): Promise<Record<ArweaveID, ContractWorld>>;
getWorld(params?: { worldId: string }): Promise<ContractWorld>;
getPosts(params?: { worldId: string }): Promise<
Record<ArweaveID, ContractPost>
>; // queries contract for all connections associated with a user
register(params: ContractUserWritable): Promise<void>;
updateUser(params: Partial<ContractUserWritable>): Promise<void>;
updatePosition(params: {
worldId: string;
position: ContractPosition;
}): Promise<void>;
post(params: ContractPostWritable): Promise<void>;
follow(params: { address: string }): Promise<void>;
unfollow(params: { address: string }): Promise<void>;
}
export const gatherEventEmitter = new EventEmitter();
// Class AoGatherProvider extends from AoProvider and implements the AoGather interface
export class AoGatherProvider extends AoProvider implements AoGather {
signer: unknown;
arweave: Arweave;
updateInterval?: NodeJS.Timeout;
constructor({
arweave = defaultArweave,
processId = aoGatherProcessId,
signer = window?.arweaveWallet ?? defaultArweave,
...params
}: {
signer?: unknown;
processId?: string;
arweave?: Arweave;
scheduler?: string;
// connectConfig?: Services;
} = {}) {
super({
processId: processId,
scheduler: params.scheduler,
// connectConfig: params.connectConfig,
});
this.signer = signer;
this.arweave = arweave;
}
ensureStarted(): this {
if (!this.updateInterval) {
const heartbeat = setInterval(() => this.updateData(), 3000);
this.updateInterval = heartbeat;
}
return this;
}
/**
* @description - Starts the AoGatherProvider, sets up the heartbeat to update connection states
* @returns AoGatherProvider - the instance of the AoGatherProvider
*
*/
start(): this {
if (this.updateInterval) {
throw new Error("Already started");
}
const heartbeat = setInterval(() => this.updateData(), 3000);
this.updateInterval = heartbeat;
return this;
}
/**
* @description - Stops the AoGatherProvider, clears the heartbeat
* @returns AoGatherProvider - the instance of the AoGatherProvider
*/
stop(): this {
if (!this.updateInterval) {
throw new Error("Not started");
}
clearInterval(this.updateInterval);
this.updateInterval = undefined;
return this;
}
async updateData(): Promise<void> {
// TODO: remove?
}
async getUsers(): Promise<Record<ArweaveID, ContractUser>> {
const { Messages } = await this.ao.dryrun({
process: this.processId,
tags: [{ name: "Action", value: "GetUsers" }],
});
return JSON.parse(Messages[0].Data) as Record<ArweaveID, ContractUser>;
}
async getWorldIndex(): Promise<ContractWorldIndex> {
const { Messages } = await this.ao.dryrun({
process: this.processId,
tags: [{ name: "Action", value: "GetWorldIndex" }],
});
return JSON.parse(Messages[0].Data) as ContractWorldIndex;
}
async getWorlds(): Promise<Record<string, ContractWorld>> {
const { Messages } = await this.ao.dryrun({
process: this.processId,
tags: [{ name: "Action", value: "GetWorld" }],
});
return JSON.parse(Messages[0].Data) as Record<ArweaveID, ContractWorld>;
}
async getWorld(params: { worldId: string }): Promise<ContractWorld> {
const { Messages } = await this.ao.dryrun({
process: this.processId,
tags: [{ name: "Action", value: "GetWorld" }],
data: JSON.stringify(params),
});
return JSON.parse(Messages[0].Data) as ContractWorld;
}
async getPosts({
worldId,
}: { worldId?: string } = {}): Promise<Record<ArweaveID, ContractPost>> {
const { Messages } = await this.ao.dryrun({
process: this.processId,
tags: [{ name: "Action", value: "GetPosts" }],
});
const posts = JSON.parse(Messages[0].Data) as Record<
ArweavePublicKey,
ContractPost
>;
// return all posts if no userId or signer is provided
if (!worldId) return posts;
// return all posts for a specific user if userId is provided
return Object.fromEntries(
Object.entries(posts).filter(([_, value]) => value.worldId === worldId),
);
}
async register(userNew: ContractUserWritable): Promise<void> {
const registrationId = await this.ao.message({
process: this.processId,
data: JSON.stringify(userNew),
tags: [{ name: "Action", value: "Register" }],
signer: createDataItemSigner(this.signer),
});
console.debug(`User registered with id ${registrationId}`);
}
async updateUser(userUpdate: Partial<ContractUserWritable>): Promise<void> {
const registrationId = await this.ao.message({
process: this.processId,
data: JSON.stringify(userUpdate),
tags: [{ name: "Action", value: "UpdateUser" }],
signer: createDataItemSigner(this.signer),
});
console.debug(`User updated with id ${registrationId}`);
}
async updatePosition({
worldId,
position,
}: { worldId: string; position: ContractPosition }): Promise<void> {
const registrationId = await this.ao.message({
process: this.processId,
tags: [{ name: "Action", value: "UpdatePosition" }],
data: JSON.stringify({ worldId, position }),
signer: createDataItemSigner(this.signer),
});
console.debug(
`User position in ${worldId} to ${JSON.stringify(
position,
)} with id ${registrationId}`,
);
}
async post(post: ContractPostWritable): Promise<void> {
const registrationId = await this.ao.message({
process: this.processId,
data: JSON.stringify(post),
tags: [{ name: "Action", value: "CreatePost" }],
signer: createDataItemSigner(this.signer),
});
console.debug(`Created post with id ${registrationId}`);
}
async follow(data: { address: string }): Promise<void> {
const registrationId = await this.ao.message({
process: this.processId,
data: JSON.stringify(data),
tags: [{ name: "Action", value: "Follow" }],
signer: createDataItemSigner(this.signer),
});
console.debug(`Followed ${data.address} with id ${registrationId}`);
}
async unfollow(data: { address: string }): Promise<void> {
const registrationId = await this.ao.message({
process: this.processId,
data: JSON.stringify(data),
tags: [{ name: "Action", value: "Unfollow" }],
signer: createDataItemSigner(this.signer),
});
console.debug(`Unfollowed ${data.address} with id ${registrationId}`);
}
}