@misofm/partyos 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/queries.ts CHANGED
@@ -2,11 +2,23 @@
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
4
  // Typed reads: fetch an on-chain object (or dynamic field) via the Core API, BCS-parse
5
- // it through the generated struct, and map to the public camelCase types.
5
+ // it through the generated struct, and map to the public camelCase types. Every read
6
+ // requires the `SuiClient` service (see `@misofm/effect`) instead of taking a client
7
+ // parameter; not-found and type-mismatch paths are typed failures, not thrown errors.
6
8
 
7
- import type { ClientWithCoreApi } from "@mysten/sui/client";
9
+ import { Effect, Option, Stream } from "effect";
8
10
  import { deriveDynamicFieldID, deriveObjectID, normalizeStructTag } from "@mysten/sui/utils";
9
11
  import { bcs } from "@mysten/sui/bcs";
12
+ import {
13
+ assertObjectType,
14
+ decodeBcs,
15
+ getObjectContent,
16
+ getObjectsContent,
17
+ getOptionalObjectContent,
18
+ listDynamicFields,
19
+ type SuiClient,
20
+ } from "@misofm/effect";
21
+ import type { BcsDecodeError, ObjectNotFoundError, ObjectTypeMismatchError, SuiRpcError } from "@misofm/effect";
10
22
  import {
11
23
  MembershipKey as MembershipKeyBcs,
12
24
  Party as PartyBcs,
@@ -14,87 +26,63 @@ import {
14
26
  PendingMembershipKey as PendingMembershipKeyBcs,
15
27
  } from "./contracts/partyos/party.ts";
16
28
  import { keyBytes, mapParty } from "./internal.ts";
17
- import type { Party } from "./types.ts";
18
-
19
- /** True for the Core API's "object does not exist" error (a missing dynamic field). */
20
- export function isNotFound(e: unknown): boolean {
21
- const msg = e instanceof Error ? e.message : String(e);
22
- return /not\s*found|does not exist|no object/i.test(msg);
23
- }
24
-
25
- /**
26
- * Reads an object's BCS content, or null when it does not exist. A missing
27
- * object (e.g. an unset dynamic field) surfaces as a thrown "not found" from the
28
- * Core API, not an empty result, so optional reads can treat it as absence.
29
- */
30
- export async function getObjectContent(client: ClientWithCoreApi, objectId: string): Promise<Uint8Array | null> {
31
- try {
32
- const { object } = await client.core.getObject({ objectId, include: { content: true } });
33
- return object?.content ?? null;
34
- } catch (e) {
35
- if (isNotFound(e)) return null;
36
- throw e;
37
- }
38
- }
29
+ import { Party } from "./types.ts";
39
30
 
40
31
  /** The `Party` struct tag of one partyos deployment. */
41
32
  export function partyType(partyPackageId: string): string {
42
33
  return normalizeStructTag(`${partyPackageId}::party::Party`);
43
34
  }
44
35
 
45
- // A Party from another partyos package (a previous generation) parses
46
- // identically but no deployed package accepts it, so the object's type is
47
- // checked against the deployment before its content is trusted.
48
- function assertPartyType(objectId: string, type: string | undefined, partyPackageId: string): void {
49
- const expected = partyType(partyPackageId);
50
- if (type === undefined || normalizeStructTag(type) !== expected) {
51
- throw new Error(
52
- `Object ${objectId} is ${type ?? "of unknown type"}, not a ${expected}` +
53
- (type?.endsWith("::party::Party") ? " (a Party from a different partyos deployment)" : ""),
54
- );
55
- }
36
+ /** Decodes one object's BCS content into a `Party`, mapping the generated parse output first. */
37
+ function decodeParty(objectId: string, content: Uint8Array, expectedType: string) {
38
+ return decodeBcs(
39
+ { parse: (bytes) => mapParty(objectId, PartyBcs.parse(bytes)) },
40
+ Party,
41
+ content,
42
+ { type: expectedType, objectId },
43
+ );
56
44
  }
57
45
 
58
46
  /** Fetches and parses a shared `Party` object of this deployment's partyos package. */
59
- export async function getPartyById(
60
- client: ClientWithCoreApi,
47
+ export const getPartyById = Effect.fn("getPartyById")(function* (
61
48
  partyId: string,
62
49
  partyPackageId: string,
63
- ): Promise<Party> {
64
- let object;
65
- try {
66
- ({ object } = await client.core.getObject({ objectId: partyId, include: { content: true } }));
67
- } catch (e) {
68
- if (isNotFound(e)) throw new Error(`Party not found: ${partyId}`);
69
- throw e;
70
- }
71
- if (!object?.content) throw new Error(`Party not found: ${partyId}`);
72
- assertPartyType(partyId, object.type, partyPackageId);
73
- return mapParty(partyId, PartyBcs.parse(object.content));
74
- }
50
+ ): Effect.fn.Return<
51
+ Party,
52
+ ObjectNotFoundError | ObjectTypeMismatchError | BcsDecodeError | SuiRpcError,
53
+ SuiClient
54
+ > {
55
+ const expected = partyType(partyPackageId);
56
+ const object = yield* getObjectContent(partyId);
57
+ // A Party from another partyos package (a previous generation) parses
58
+ // identically but no deployed package accepts it, so the object's type is
59
+ // checked against the deployment before its content is trusted.
60
+ yield* assertObjectType(partyId, normalizeStructTag(object.type), expected);
61
+ return yield* decodeParty(partyId, object.content, expected);
62
+ });
75
63
 
76
64
  /**
77
65
  * Fetches and parses multiple shared `Party` objects in one Core request.
78
66
  * Missing objects are skipped; an object of another type is an error.
79
67
  */
80
- export async function getPartiesByIds(
81
- client: ClientWithCoreApi,
68
+ export const getPartiesByIds = Effect.fn("getPartiesByIds")(function* (
82
69
  partyIds: readonly string[],
83
70
  partyPackageId: string,
84
- ): Promise<Partial<Record<string, Party>>> {
71
+ ): Effect.fn.Return<
72
+ Partial<Record<string, Party>>,
73
+ ObjectTypeMismatchError | BcsDecodeError | SuiRpcError,
74
+ SuiClient
75
+ > {
85
76
  if (partyIds.length === 0) return {};
86
- const { objects } = await client.core.getObjects({
87
- objectIds: [...new Set(partyIds)],
88
- include: { content: true },
89
- });
77
+ const expected = partyType(partyPackageId);
78
+ const contentById = yield* getObjectsContent([...new Set(partyIds)]);
90
79
  const parties: Partial<Record<string, Party>> = {};
91
- for (const obj of objects) {
92
- if (obj instanceof Error) continue;
93
- assertPartyType(obj.objectId, obj.type, partyPackageId);
94
- parties[obj.objectId] = mapParty(obj.objectId, PartyBcs.parse(obj.content));
80
+ for (const [objectId, { content, type }] of contentById) {
81
+ yield* assertObjectType(objectId, normalizeStructTag(type), expected);
82
+ parties[objectId] = yield* decodeParty(objectId, content, expected);
95
83
  }
96
84
  return parties;
97
- }
85
+ });
98
86
 
99
87
  /** Derives a party's `PartyAdminCap` id (it is a `derived_object` off the party UID). */
100
88
  export function derivePartyAdminCapId(partyId: string, partyPackageId: string): string {
@@ -108,38 +96,33 @@ export function derivePartyAdminCapId(partyId: string, partyPackageId: string):
108
96
  // === Group membership reads ===
109
97
 
110
98
  /** Collects the ids stored in every dynamic-field key of `parentId` whose type ends with `keySuffix`. */
111
- async function collectKeyIds(
112
- client: ClientWithCoreApi,
99
+ function collectKeyIds(
113
100
  parentId: string,
114
101
  keySuffix: string,
115
102
  codec: { parse(bytes: Uint8Array): readonly unknown[] },
116
- ): Promise<string[]> {
117
- const ids: string[] = [];
118
- let cursor: string | null | undefined;
119
- do {
120
- const page = await client.core.listDynamicFields({ parentId, cursor: cursor ?? undefined });
121
- for (const f of page.dynamicFields) {
122
- if (typeof f.name?.type === "string" && f.name.type.endsWith(keySuffix) && f.name.bcs != null) {
123
- const [id] = codec.parse(keyBytes(f.name.bcs));
124
- ids.push(String(id));
125
- }
126
- }
127
- cursor = page.hasNextPage ? page.cursor : null;
128
- } while (cursor);
129
- return ids;
103
+ ): Effect.Effect<string[], SuiRpcError, SuiClient> {
104
+ return listDynamicFields(parentId).pipe(
105
+ Stream.filter((f) => typeof f.name?.type === "string" && f.name.type.endsWith(keySuffix) && f.name.bcs != null),
106
+ Stream.map((f) => {
107
+ const [id] = codec.parse(keyBytes(f.name!.bcs));
108
+ return String(id);
109
+ }),
110
+ Stream.runCollect,
111
+ Effect.map((chunk) => Array.from(chunk)),
112
+ );
130
113
  }
131
114
 
132
115
  /**
133
116
  * The group ids a party currently belongs to, read from its `MembershipKey`
134
117
  * dynamic fields (the member-side record). No indexer required.
135
118
  */
136
- export async function getMemberships(client: ClientWithCoreApi, partyId: string): Promise<string[]> {
137
- return collectKeyIds(client, partyId, "::party::MembershipKey", MembershipKeyBcs);
119
+ export function getMemberships(partyId: string): Effect.Effect<string[], SuiRpcError, SuiClient> {
120
+ return collectKeyIds(partyId, "::party::MembershipKey", MembershipKeyBcs);
138
121
  }
139
122
 
140
123
  /** The member ids invited to a group but not yet accepted (its `PendingInviteKey` fields). */
141
- export async function getPendingInvites(client: ClientWithCoreApi, groupId: string): Promise<string[]> {
142
- return collectKeyIds(client, groupId, "::party::PendingInviteKey", PendingInviteKeyBcs);
124
+ export function getPendingInvites(groupId: string): Effect.Effect<string[], SuiRpcError, SuiClient> {
125
+ return collectKeyIds(groupId, "::party::PendingInviteKey", PendingInviteKeyBcs);
143
126
  }
144
127
 
145
128
  /**
@@ -147,21 +130,21 @@ export async function getPendingInvites(client: ClientWithCoreApi, groupId: stri
147
130
  * This reads the member-side `PendingMembershipKey` inbox index, so it only
148
131
  * enumerates the target party's dynamic fields.
149
132
  */
150
- export async function getPendingMemberships(client: ClientWithCoreApi, partyId: string): Promise<string[]> {
151
- return collectKeyIds(client, partyId, "::party::PendingMembershipKey", PendingMembershipKeyBcs);
133
+ export function getPendingMemberships(partyId: string): Effect.Effect<string[], SuiRpcError, SuiClient> {
134
+ return collectKeyIds(partyId, "::party::PendingMembershipKey", PendingMembershipKeyBcs);
152
135
  }
153
136
 
154
137
  /** Whether `memberId` currently holds a membership record for `groupId`. */
155
- export async function isMember(
156
- client: ClientWithCoreApi,
138
+ export const isMember = Effect.fn("isMember")(function* (
157
139
  memberId: string,
158
140
  groupId: string,
159
141
  partyPackageId: string,
160
- ): Promise<boolean> {
142
+ ): Effect.fn.Return<boolean, SuiRpcError, SuiClient> {
161
143
  const fieldId = deriveDynamicFieldID(
162
144
  memberId,
163
145
  `${partyPackageId}::party::MembershipKey`,
164
146
  MembershipKeyBcs.serialize([groupId]).toBytes(),
165
147
  );
166
- return (await getObjectContent(client, fieldId)) !== null;
167
- }
148
+ const content = yield* getOptionalObjectContent(fieldId);
149
+ return Option.isSome(content);
150
+ });
package/src/types.ts CHANGED
@@ -1,18 +1,21 @@
1
1
  // Copyright (c) Miso Labs, Inc.
2
2
  // SPDX-License-Identifier: Apache-2.0
3
3
 
4
- // Public, camelCase result types. The mappers in ./internal.ts turn the generated
5
- // (snake_case, Move-shaped) parse output into these.
4
+ // Public, camelCase result types. The mapper in ./internal.ts turns the generated
5
+ // (snake_case, Move-shaped) parse output into the plain shape `Party` decodes from.
6
6
 
7
- export type PartyKind = "individual" | "group";
7
+ import { Schema } from "effect";
8
8
 
9
- export interface Party {
10
- id: string;
11
- kind: PartyKind;
9
+ export const PartyKind = Schema.Literals(["individual", "group"]);
10
+ export type PartyKind = typeof PartyKind.Type;
11
+
12
+ export class Party extends Schema.Class<Party>("@misofm/partyos/Party")({
13
+ id: Schema.String,
14
+ kind: PartyKind,
12
15
  /** Human-readable name (not verified). */
13
- name: string;
16
+ name: Schema.String,
14
17
  /** Member party ids — present only when `kind === "group"`. */
15
- members?: string[];
18
+ members: Schema.optional(Schema.Array(Schema.String)),
16
19
  /** Unix ms when the party was created. */
17
- createdAtMs: number;
18
- }
20
+ createdAtMs: Schema.Number,
21
+ }) {}