@show-karma/karma-gap-sdk 0.4.15 → 0.4.16

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.
Files changed (188) hide show
  1. package/.cursorrules +43 -0
  2. package/core/abi/AirdropNFT.json +1 -1
  3. package/core/abi/Allo.json +860 -860
  4. package/core/abi/AlloRegistry.json +578 -578
  5. package/core/abi/CommunityResolverABI.json +506 -506
  6. package/core/abi/Donations.json +251 -251
  7. package/core/abi/EAS.json +1 -1
  8. package/core/abi/MultiAttester.json +746 -746
  9. package/core/abi/ProjectResolver.json +574 -574
  10. package/core/abi/SchemaRegistry.json +1 -1
  11. package/core/abi/index.ts +21 -0
  12. package/core/class/AllGapSchemas.ts +21 -0
  13. package/core/class/Attestation.ts +429 -0
  14. package/core/class/Fetcher.ts +224 -0
  15. package/core/class/GAP.ts +481 -0
  16. package/core/class/GapSchema.ts +93 -0
  17. package/core/class/Gelato/{Gelato.js → Gelato.ts} +23 -0
  18. package/core/class/GrantProgramRegistry/Allo.ts +188 -0
  19. package/core/class/GrantProgramRegistry/AlloRegistry.ts +101 -0
  20. package/core/class/GraphQL/AxiosGQL.ts +29 -0
  21. package/core/class/GraphQL/EASClient.ts +34 -0
  22. package/core/class/GraphQL/GapEasClient.ts +869 -0
  23. package/core/class/Schema.ts +659 -0
  24. package/core/class/SchemaError.ts +42 -0
  25. package/core/class/contract/GapContract.ts +457 -0
  26. package/core/class/entities/Community.ts +148 -0
  27. package/core/class/entities/ContributorProfile.ts +108 -0
  28. package/core/class/entities/Grant.ts +321 -0
  29. package/core/class/entities/GrantUpdate.ts +187 -0
  30. package/core/class/entities/MemberOf.ts +52 -0
  31. package/core/class/entities/Milestone.ts +898 -0
  32. package/core/class/entities/Project.ts +672 -0
  33. package/core/class/entities/ProjectImpact.ts +170 -0
  34. package/core/class/entities/ProjectMilestone.ts +254 -0
  35. package/core/class/entities/ProjectPointer.ts +39 -0
  36. package/core/class/entities/ProjectUpdate.ts +176 -0
  37. package/core/class/entities/Track.ts +32 -0
  38. package/core/class/karma-indexer/GapIndexerClient.ts +383 -0
  39. package/core/class/karma-indexer/api/GapIndexerApi.ts +446 -0
  40. package/core/class/karma-indexer/api/types.ts +313 -0
  41. package/core/class/remote-storage/IpfsStorage.ts +76 -0
  42. package/core/class/remote-storage/RemoteStorage.ts +65 -0
  43. package/core/class/types/allo.ts +93 -0
  44. package/core/class/types/attestations.ts +223 -0
  45. package/core/consts.ts +775 -0
  46. package/core/scripts/create-grant.ts +102 -0
  47. package/core/scripts/create-program.ts +43 -0
  48. package/core/scripts/create-schemas.ts +65 -0
  49. package/core/scripts/deploy.ts +65 -0
  50. package/core/scripts/index.ts +1 -0
  51. package/core/scripts/milestone-multi-grants.ts +125 -0
  52. package/core/shared/types.ts +13 -0
  53. package/core/types.ts +224 -0
  54. package/core/utils/gelato/send-gelato-txn.ts +114 -0
  55. package/core/utils/gelato/sponsor-handler.ts +77 -0
  56. package/core/utils/gelato/watch-gelato-txn.ts +67 -0
  57. package/core/utils/get-date.ts +3 -0
  58. package/core/utils/get-ipfs-data.ts +13 -0
  59. package/core/utils/get-web3-provider.ts +18 -0
  60. package/core/utils/gql-queries.ts +133 -0
  61. package/core/utils/map-filter.ts +21 -0
  62. package/core/utils/serialize-bigint.ts +7 -0
  63. package/core/utils/to-unix.ts +18 -0
  64. package/create-community-example.ts +119 -0
  65. package/csv-upload/README.md +74 -0
  66. package/csv-upload/config.ts +41 -0
  67. package/csv-upload/example.csv +2 -0
  68. package/csv-upload/keys.example.json +8 -0
  69. package/csv-upload/scripts/run.ts +417 -0
  70. package/csv-upload/types.ts +39 -0
  71. package/docs/.gitkeep +0 -0
  72. package/docs/images/attestation-architecture.png +0 -0
  73. package/docs/images/dfd-get-projects.png +0 -0
  74. package/gap-schema.yaml +155 -0
  75. package/milestone-workflow-example.ts +353 -0
  76. package/package.json +45 -39
  77. package/readme.md +872 -0
  78. package/schemas/.gitkeep +0 -0
  79. package/schemas/GAP-schemas-1692135812877.json +33 -0
  80. package/test-file-indexer-api.ts +25 -0
  81. package/tsconfig.json +26 -0
  82. package/core/abi/index.d.ts +0 -1114
  83. package/core/abi/index.js +0 -26
  84. package/core/class/AllGapSchemas.d.ts +0 -9
  85. package/core/class/AllGapSchemas.js +0 -19
  86. package/core/class/Attestation.d.ts +0 -173
  87. package/core/class/Attestation.js +0 -333
  88. package/core/class/Fetcher.d.ts +0 -175
  89. package/core/class/Fetcher.js +0 -13
  90. package/core/class/GAP.d.ts +0 -254
  91. package/core/class/GAP.js +0 -289
  92. package/core/class/GapSchema.d.ts +0 -34
  93. package/core/class/GapSchema.js +0 -62
  94. package/core/class/GrantProgramRegistry/Allo.d.ts +0 -17
  95. package/core/class/GrantProgramRegistry/Allo.js +0 -137
  96. package/core/class/GrantProgramRegistry/AlloRegistry.d.ts +0 -15
  97. package/core/class/GrantProgramRegistry/AlloRegistry.js +0 -70
  98. package/core/class/GraphQL/AxiosGQL.d.ts +0 -6
  99. package/core/class/GraphQL/AxiosGQL.js +0 -25
  100. package/core/class/GraphQL/EASClient.d.ts +0 -16
  101. package/core/class/GraphQL/EASClient.js +0 -26
  102. package/core/class/GraphQL/GapEasClient.d.ts +0 -71
  103. package/core/class/GraphQL/GapEasClient.js +0 -451
  104. package/core/class/GraphQL/index.js +0 -19
  105. package/core/class/Schema.d.ts +0 -233
  106. package/core/class/Schema.js +0 -488
  107. package/core/class/SchemaError.d.ts +0 -30
  108. package/core/class/SchemaError.js +0 -39
  109. package/core/class/contract/GapContract.d.ts +0 -102
  110. package/core/class/contract/GapContract.js +0 -285
  111. package/core/class/entities/Community.d.ts +0 -34
  112. package/core/class/entities/Community.js +0 -109
  113. package/core/class/entities/ContributorProfile.d.ts +0 -41
  114. package/core/class/entities/ContributorProfile.js +0 -69
  115. package/core/class/entities/Grant.d.ts +0 -54
  116. package/core/class/entities/Grant.js +0 -223
  117. package/core/class/entities/GrantUpdate.d.ts +0 -40
  118. package/core/class/entities/GrantUpdate.js +0 -114
  119. package/core/class/entities/MemberOf.d.ts +0 -11
  120. package/core/class/entities/MemberOf.js +0 -33
  121. package/core/class/entities/Milestone.d.ts +0 -168
  122. package/core/class/entities/Milestone.js +0 -657
  123. package/core/class/entities/Project.d.ts +0 -92
  124. package/core/class/entities/Project.js +0 -418
  125. package/core/class/entities/ProjectImpact.d.ts +0 -50
  126. package/core/class/entities/ProjectImpact.js +0 -112
  127. package/core/class/entities/ProjectMilestone.d.ts +0 -60
  128. package/core/class/entities/ProjectMilestone.js +0 -174
  129. package/core/class/entities/ProjectPointer.d.ts +0 -12
  130. package/core/class/entities/ProjectPointer.js +0 -22
  131. package/core/class/entities/ProjectUpdate.d.ts +0 -50
  132. package/core/class/entities/ProjectUpdate.js +0 -110
  133. package/core/class/entities/Track.d.ts +0 -16
  134. package/core/class/entities/Track.js +0 -21
  135. package/core/class/entities/index.js +0 -26
  136. package/core/class/index.js +0 -26
  137. package/core/class/karma-indexer/GapIndexerClient.d.ts +0 -66
  138. package/core/class/karma-indexer/GapIndexerClient.js +0 -207
  139. package/core/class/karma-indexer/api/GapIndexerApi.d.ts +0 -73
  140. package/core/class/karma-indexer/api/GapIndexerApi.js +0 -256
  141. package/core/class/karma-indexer/api/types.d.ts +0 -295
  142. package/core/class/karma-indexer/api/types.js +0 -2
  143. package/core/class/remote-storage/IpfsStorage.d.ts +0 -23
  144. package/core/class/remote-storage/IpfsStorage.js +0 -56
  145. package/core/class/remote-storage/RemoteStorage.d.ts +0 -41
  146. package/core/class/remote-storage/RemoteStorage.js +0 -38
  147. package/core/class/types/allo.d.ts +0 -78
  148. package/core/class/types/allo.js +0 -2
  149. package/core/class/types/attestations.d.ts +0 -168
  150. package/core/class/types/attestations.js +0 -66
  151. package/core/consts.d.ts +0 -48
  152. package/core/consts.js +0 -641
  153. package/core/index.js +0 -24
  154. package/core/shared/types.d.ts +0 -6
  155. package/core/shared/types.js +0 -2
  156. package/core/types.d.ts +0 -131
  157. package/core/types.js +0 -13
  158. package/core/utils/gelato/index.js +0 -19
  159. package/core/utils/gelato/send-gelato-txn.d.ts +0 -55
  160. package/core/utils/gelato/send-gelato-txn.js +0 -100
  161. package/core/utils/gelato/sponsor-handler.d.ts +0 -9
  162. package/core/utils/gelato/sponsor-handler.js +0 -60
  163. package/core/utils/gelato/watch-gelato-txn.d.ts +0 -7
  164. package/core/utils/gelato/watch-gelato-txn.js +0 -63
  165. package/core/utils/get-date.d.ts +0 -1
  166. package/core/utils/get-date.js +0 -7
  167. package/core/utils/get-ipfs-data.d.ts +0 -1
  168. package/core/utils/get-ipfs-data.js +0 -20
  169. package/core/utils/get-web3-provider.d.ts +0 -2
  170. package/core/utils/get-web3-provider.js +0 -18
  171. package/core/utils/gql-queries.d.ts +0 -12
  172. package/core/utils/gql-queries.js +0 -90
  173. package/core/utils/index.js +0 -23
  174. package/core/utils/map-filter.d.ts +0 -8
  175. package/core/utils/map-filter.js +0 -20
  176. package/core/utils/serialize-bigint.d.ts +0 -1
  177. package/core/utils/serialize-bigint.js +0 -8
  178. package/core/utils/to-unix.d.ts +0 -1
  179. package/core/utils/to-unix.js +0 -25
  180. package/index.js +0 -17
  181. /package/core/class/GraphQL/{index.d.ts → index.ts} +0 -0
  182. /package/core/class/entities/{index.d.ts → index.ts} +0 -0
  183. /package/core/class/{index.d.ts → index.ts} +0 -0
  184. /package/core/{index.d.ts → index.ts} +0 -0
  185. /package/core/utils/gelato/{index.d.ts → index.ts} +0 -0
  186. /package/core/utils/{index.d.ts → index.ts} +0 -0
  187. /package/{core/class/Gelato/Gelato.d.ts → csv-upload/.gitkeep} +0 -0
  188. /package/{index.d.ts → index.ts} +0 -0
@@ -0,0 +1,659 @@
1
+ import {
2
+ AttestationRequestData,
3
+ getUIDsFromAttestReceipt,
4
+ OffchainAttestationParams,
5
+ SchemaEncoder,
6
+ SchemaItem,
7
+ SchemaValue,
8
+ } from "@ethereum-attestation-service/eas-sdk";
9
+ import {
10
+ AttestArgs,
11
+ Hex,
12
+ MultiRevokeArgs,
13
+ SchemaInterface,
14
+ TSchemaName,
15
+ SignerOrProvider,
16
+ RawMultiAttestPayload,
17
+ RawAttestationPayload,
18
+ TNetwork,
19
+ } from "../types";
20
+ import { AttestationError, SchemaError } from "./SchemaError";
21
+ import { ethers, Transaction } from "ethers";
22
+ import { useDefaultAttestation, zeroAddress } from "../consts";
23
+ import { GAP } from "./GAP";
24
+ import { Attestation } from "./Attestation";
25
+ import { GapContract } from "./contract/GapContract";
26
+ import { isAddress } from "ethers";
27
+ import { IpfsStorage } from "./remote-storage/IpfsStorage";
28
+ import { AttestationWithTx } from "./types/attestations";
29
+ /**
30
+ * Represents the EAS Schema and provides methods to encode and decode the schema,
31
+ * and validate the schema references.
32
+ *
33
+ * Also provides a set of static methods to manage the schema list.
34
+ *
35
+ * @example
36
+ * ```
37
+ * // You may or not attribute a schema to a variable.
38
+ * new Schema({
39
+ * name: "Grantee",
40
+ * schema: [{ type: "bool", name: "grantee", value: true }],
41
+ * uid: "0x000000000
42
+ * });
43
+ *
44
+ * const granteeDetails = new Schema({
45
+ * name: "GranteeDetails",
46
+ * schema: [
47
+ * { type: "bool", name: "name", value: null }
48
+ * { type: "bool", name: "description", value: null }
49
+ * { type: "bool", name: "imageURL", value: null }
50
+ * ],
51
+ * uid: "0x000000000,
52
+ * references: "Grantee"
53
+ * });
54
+ *
55
+ * // Validate if references are correct and all of them exist.
56
+ * Schema.validate();
57
+ *
58
+ * // Gets the schema by name.
59
+ * const grantee = Schema.get("Grantee");
60
+ *
61
+ * // Sets a single schema value.
62
+ * grantee.setValue("grantee", true);
63
+ *
64
+ * // Sets multiple schema values.
65
+ * granteeDetails.setValues({ name: "John Doe", description: "A description", imageURL: "https://example.com/image.png" });
66
+ *
67
+ * // Gets the schema encoded data, used to create an attestation.
68
+ * const encodedGrantee = grantee.encode();
69
+ *
70
+ * // Verify if schema exists
71
+ * Schema.exists("Grantee"); // true
72
+ * Schema.exists("GranteeDetails"); // true
73
+ * Schema.exists("GranteeDetails2"); // false
74
+ *
75
+ * // Get all schemas.
76
+ * Schema.getAll(); // [grantee, granteeDetails]
77
+ *
78
+ * // Get all schema names.
79
+ * Schema.getNames(); // ["Grantee", "GranteeDetails"]
80
+ *
81
+ * // Get many schemas by name. Throws an error if schema does not exist.
82
+ * Schema.getMany(["Grantee", "GranteeDetails"]); // [grantee, granteeDetails]
83
+ *
84
+ * // Replace all schemas. Throws an error if schema does not exist.
85
+ * Schema.replaceAll([grantee, granteeDetails]);
86
+ *
87
+ * // Replace one schema. This will replace a schema using the inbound schema name.. Throws an error if schema does not exist.
88
+ * Schema.replaceOne(grantee);
89
+ *
90
+ * // Converts a raw schema string (e.g. "uint256 id, string name") to a SchemaItem[].
91
+ * const schema = Schema.rawToObject("uint256 id, string name");
92
+ * ```
93
+ */
94
+ export abstract class Schema<T extends string = string>
95
+ implements SchemaInterface<T>
96
+ {
97
+ protected static schemas: Record<TNetwork, Schema[]> = {
98
+ "optimism-sepolia": [],
99
+ // "optimism-goerli": [],
100
+ optimism: [],
101
+ sepolia: [],
102
+ arbitrum: [],
103
+ celo: [],
104
+ sei: [],
105
+ "sei-testnet": [],
106
+ "base-sepolia": [],
107
+ lisk: [],
108
+ scroll: [],
109
+ };
110
+
111
+ protected encoder: SchemaEncoder;
112
+ private _schema: SchemaItem[] = [];
113
+
114
+ readonly uid: Hex;
115
+ readonly name: string;
116
+
117
+ readonly revocable?: boolean;
118
+ readonly references?: T;
119
+
120
+ readonly gap: GAP;
121
+
122
+ readonly oldSchemas?: {uid: string; raw: SchemaItem[]}[];
123
+ /**
124
+ * Creates a new schema instance
125
+ * @param args
126
+ * @param strict If true, will throw an error if schema reference is not valid. With this option, user should add schemas
127
+ * in a strict order.
128
+ */
129
+ constructor(
130
+ args: SchemaInterface<T>,
131
+ gap?: GAP,
132
+ strict = false,
133
+ ignoreSchema = false
134
+ ) {
135
+ this.assert(args, strict);
136
+ this.gap = gap;
137
+ this._schema = args.schema;
138
+ this.uid = args.uid;
139
+ this.name = args.name;
140
+ this.references = args.references;
141
+ this.revocable = args.revocable || true;
142
+ this.oldSchemas = args.oldSchemas || null;
143
+ this.encoder = new SchemaEncoder(this.raw);
144
+ }
145
+
146
+ /**
147
+ * Encode the schema to be used as payload in the attestation
148
+ * @returns
149
+ */
150
+ encode(schema?: SchemaItem[]) {
151
+ return this.encoder.encodeData(schema || this.schema);
152
+ }
153
+
154
+ /**
155
+ * Set a schema field value.
156
+ * @param key
157
+ * @param value
158
+ */
159
+ setValue(key: string, value: SchemaValue) {
160
+ const idx = this._schema.findIndex((item) => item.name === key);
161
+ if (!~idx)
162
+ throw new SchemaError(
163
+ "INVALID_SCHEMA_FIELD",
164
+ `Field ${key} not found in schema ${this.name}`
165
+ );
166
+
167
+ this.assertField(this._schema[idx], value);
168
+ this._schema[idx].value = value;
169
+ }
170
+
171
+ /**
172
+ * Tests if the current schema is a JSON Schema.
173
+ *
174
+ * @returns boolean
175
+ */
176
+ isJsonSchema() {
177
+ return !!this.schema.find((s) => s.name === "json" && s.type === "string");
178
+ }
179
+
180
+ private assertField(item: SchemaItem, value: any) {
181
+ const { type, name } = item;
182
+
183
+ if (type.includes("uint") && /\D/.test(value)) {
184
+ throw new SchemaError(
185
+ "INVALID_SCHEMA_FIELD",
186
+ `Field ${name} is of type ${type} but value is not a number.`
187
+ );
188
+ }
189
+
190
+ if (
191
+ type.includes("address") &&
192
+ !isAddress(value) &&
193
+ value !== zeroAddress
194
+ ) {
195
+ throw new SchemaError(
196
+ "INVALID_SCHEMA_FIELD",
197
+ `Field ${name} is of type ${type} but value is not a valid address.`
198
+ );
199
+ }
200
+
201
+ if (type.includes("bytes") && !value.startsWith("0x")) {
202
+ throw new SchemaError(
203
+ "INVALID_SCHEMA_FIELD",
204
+ `Field ${name} is of type ${type} but value is not a valid hex string.`
205
+ );
206
+ }
207
+
208
+ if (
209
+ type.includes("bool") &&
210
+ (!["true", "false", true, false].includes(value) ||
211
+ typeof value !== "boolean")
212
+ ) {
213
+ throw new SchemaError(
214
+ "INVALID_SCHEMA_FIELD",
215
+ `Field ${name} is of type ${type} but value is not a valid boolean.`
216
+ );
217
+ }
218
+
219
+ if (type.includes("tuple") && !Array.isArray(value)) {
220
+ throw new SchemaError(
221
+ "INVALID_SCHEMA_FIELD",
222
+ `Field ${name} is of type ${type} but value is not a valid array.`
223
+ );
224
+ }
225
+
226
+ if (type === "string" && name === "json") {
227
+ try {
228
+ JSON.parse(value);
229
+ } catch (error) {
230
+ throw new SchemaError(
231
+ "INVALID_SCHEMA_FIELD",
232
+ `Field ${name} is of type ${type} but value is not a valid JSON string.`,
233
+ error
234
+ );
235
+ }
236
+ }
237
+ }
238
+
239
+ /**
240
+ * Asserts if schema is valid.
241
+ * > Does not check references if `strict = false`. To check references use `Schema.validate()`
242
+ * @param args
243
+ */
244
+ protected assert(args: SchemaInterface, strict = false) {
245
+ const { name, schema, uid, references } = args;
246
+
247
+ if (!name) {
248
+ throw new SchemaError("MISSING_FIELD", "Schema name is required");
249
+ }
250
+
251
+ if (!schema && !Array.isArray(schema)) {
252
+ throw new SchemaError("MISSING_FIELD", "Schema must be an array.");
253
+ }
254
+
255
+ // if (!uid) {
256
+ // throw new SchemaError("MISSING_FIELD", "Schema uid is required");
257
+ // }
258
+
259
+ if (strict && references && !Schema.exists(references, this.gap.network)) {
260
+ throw new SchemaError(
261
+ "INVALID_REFERENCE",
262
+ `Schema ${name} references ${references} but it does not exist.`
263
+ );
264
+ }
265
+ }
266
+
267
+ /**
268
+ * Attest off chain data
269
+ * @returns
270
+ */
271
+ async attestOffchain({ data, signer, to, refUID }: AttestArgs) {
272
+ const eas = await this.gap.eas.getOffchain();
273
+ const payload = <OffchainAttestationParams>{
274
+ data,
275
+ version: eas.version,
276
+ revocable: this.revocable,
277
+ expirationTime: 0n,
278
+ recipient: to,
279
+ refUID,
280
+ schema: this.raw,
281
+ time: BigInt((Date.now() / 1000).toFixed(0)),
282
+ };
283
+ return eas.signOffchainAttestation(payload, signer as any);
284
+ }
285
+
286
+ /**
287
+ * Revokes one off chain attestation by its UID.
288
+ * @param uid
289
+ * @param signer
290
+ * @returns
291
+ */
292
+ async revokeOffchain(uid: Hex, signer: SignerOrProvider) {
293
+ const eas = this.gap.eas.connect(signer);
294
+ return eas.revokeOffchain(uid);
295
+ }
296
+
297
+ /**
298
+ * Revokes multiple off chain attestations by their UIDs.
299
+ * @param uids
300
+ * @param signer
301
+ * @returns
302
+ */
303
+ async multiRevokeOffchain(uids: Hex[], signer: SignerOrProvider) {
304
+ const eas = this.gap.eas.connect(signer);
305
+ return eas.multiRevokeOffchain(uids);
306
+ }
307
+
308
+ /**
309
+ * Validates and attests a given schema.
310
+ *
311
+ * This function checks a schema against predefined standards or rules. If the 'ipfsKey' parameter is enabled,
312
+ * it uploads the data to the IPFS (InterPlanetary File System). Upon successful upload, the function
313
+ * returns the CID (Content Identifier) within the Attestation Body, providing a reference to the data on IPFS.
314
+ *
315
+ * Usage:
316
+ * - Ensure that the schema to be attested conforms to the required format.
317
+ * - Enable 'ipfsKey' if you wish to store the data on IPFS and retrieve its CID.
318
+ *
319
+ * @param {Object} param0 - An object containing the schema and other optional settings.
320
+ * @returns {Object} An object containing the attestation results, including the CID if 'ipfsKey' is enabled.
321
+ */
322
+ async attest<T>({
323
+ data,
324
+ to,
325
+ signer,
326
+ refUID,
327
+ callback,
328
+ }: AttestArgs<T>): Promise<AttestationWithTx> {
329
+ const eas = this.gap.eas.connect(signer);
330
+
331
+ if (this.references && !refUID)
332
+ throw new AttestationError(
333
+ "INVALID_REFERENCE",
334
+ "Attestation schema references another schema but no reference UID was provided."
335
+ );
336
+
337
+ if (this.isJsonSchema()) {
338
+ this.setValue("json", JSON.stringify(data));
339
+ } else {
340
+ Object.entries(data).forEach(([key, value]) => {
341
+ this.setValue(key, value);
342
+ });
343
+ }
344
+
345
+ const payload: RawAttestationPayload = {
346
+ schema: this.uid,
347
+ data: {
348
+ raw: {
349
+ recipient: to,
350
+ expirationTime: 0n,
351
+ revocable: true,
352
+ data: this.schema as any,
353
+ refUID,
354
+ value: 0n,
355
+ },
356
+ payload: {
357
+ recipient: to,
358
+ expirationTime: 0n,
359
+ revocable: true,
360
+ data: this.encode(this.schema),
361
+ refUID,
362
+ value: 0n,
363
+ },
364
+ },
365
+ };
366
+
367
+ callback?.("preparing");
368
+ if (useDefaultAttestation.includes(this.name as TSchemaName)) {
369
+ const uid = await eas.attest({
370
+ schema: this.uid,
371
+ data: payload.data.payload,
372
+ });
373
+
374
+ callback?.("pending");
375
+
376
+ const uidResult = await uid.wait();
377
+
378
+ callback?.("confirmed");
379
+
380
+ return {
381
+ tx: [
382
+ {
383
+ hash: uidResult as Hex,
384
+ } as Transaction,
385
+ ],
386
+ uids: [uidResult as Hex],
387
+ };
388
+ }
389
+
390
+ const { tx, uids } = await GapContract.attest(signer, payload, callback);
391
+ return {
392
+ tx,
393
+ uids,
394
+ };
395
+ }
396
+
397
+ /**
398
+ * Bulk attest a set of attestations.
399
+ * @param signer
400
+ * @param entities
401
+ * @returns
402
+ */
403
+ async multiAttest(
404
+ signer: SignerOrProvider,
405
+ entities: Attestation[] = [],
406
+ callback?: Function
407
+ ): Promise<AttestationWithTx> {
408
+ entities.forEach((entity) => {
409
+ if (this.references && !entity.refUID)
410
+ throw new SchemaError(
411
+ "INVALID_REF_UID",
412
+ `Entity ${entity.schema.name} references another schema but no reference UID was provided.`
413
+ );
414
+ });
415
+
416
+ const eas = this.gap.eas.connect(signer);
417
+
418
+ const entityBySchema = entities.reduce(
419
+ (acc, entity) => {
420
+ const schema = entity.schema.uid;
421
+ if (!acc[schema]) acc[schema] = [];
422
+ acc[schema].push(entity);
423
+ return acc;
424
+ },
425
+ {} as Record<string, Attestation[]>
426
+ );
427
+ const payload = Object.entries(entityBySchema).map(([schema, ents]) => ({
428
+ schema,
429
+ data: ents.map((e) => ({
430
+ data: e.schema.encode(),
431
+ refUID: e.refUID,
432
+ recipient: e.recipient,
433
+ expirationTime: 0n,
434
+ })),
435
+ }));
436
+
437
+ if (callback) callback("preparing");
438
+ const attestation = await eas.multiAttest(payload, {
439
+ gasLimit: 5000000n,
440
+ });
441
+ if (callback) callback("pending");
442
+ const txResult = await attestation.wait().then((res) => {
443
+ if (callback) callback("confirmed");
444
+ return res;
445
+ });
446
+
447
+ const tx = txResult.map((item) => ({ hash: item }) as Transaction);
448
+
449
+ return {
450
+ tx,
451
+ uids: txResult as Hex[],
452
+ };
453
+ }
454
+
455
+ /**
456
+ * Revokes a set of attestations by their UIDs.
457
+ * @param signer
458
+ * @param uids
459
+ * @returns
460
+ */
461
+ async multiRevoke(
462
+ signer: SignerOrProvider,
463
+ toRevoke: MultiRevokeArgs[],
464
+ callback?: Function
465
+ ) {
466
+ callback?.("preparing");
467
+ const groupBySchema = toRevoke.reduce(
468
+ (acc, { uid, schemaId }) => {
469
+ if (!acc[schemaId]) acc[schemaId] = [];
470
+ acc[schemaId].push(uid);
471
+ return acc;
472
+ },
473
+ {} as Record<string, Hex[]>
474
+ );
475
+
476
+ const eas = this.gap.eas.connect(signer);
477
+ const payload = Object.entries(groupBySchema).map(([schema, uids]) => ({
478
+ schema,
479
+ data: uids.map((uid) => ({ uid })),
480
+ }));
481
+
482
+ const tx = await eas.multiRevoke(payload, {
483
+ gasLimit: 5000000n,
484
+ });
485
+ callback?.("pending");
486
+ await tx.wait();
487
+ callback?.("confirmed");
488
+
489
+ return {
490
+ tx: [{ hash: tx.tx.hash } as Transaction],
491
+ uids: payload.map((p) => p.data.map((d) => d.uid)).flat(),
492
+ };
493
+ }
494
+
495
+ static exists(name: string, network: TNetwork) {
496
+ return this.schemas[network].find((schema) => schema.name === name);
497
+ }
498
+
499
+ /**
500
+ * Adds the schema signature to a shares list. Use Schema.get("SchemaName") to get the schema.
501
+ *
502
+ * __Note that this will make the schema available to all instances
503
+ * of the class AND its data can be overriden by any changes.__
504
+ * @param schemas
505
+ */
506
+ static add<T extends Schema>(network: TNetwork, ...schemas: T[]) {
507
+ schemas.forEach((schema) => {
508
+ if (!this.exists(schema.name, network))
509
+ this.schemas[network].push(schema);
510
+ });
511
+ }
512
+
513
+ static getAll<T extends Schema>(network: TNetwork): T[] {
514
+ return this.schemas[network] as T[];
515
+ }
516
+
517
+ static get<N extends string, T extends Schema>(
518
+ name: N,
519
+ network: TNetwork
520
+ ): T {
521
+ const schema = this.schemas[network].find(
522
+ (schema) => schema.name === name || schema.uid === name
523
+ );
524
+
525
+ if (!schema)
526
+ throw new SchemaError(
527
+ "SCHEMA_NOT_FOUND",
528
+ `Schema ${name} not found. Available schemas: ${Schema.getNames(
529
+ network
530
+ )}`
531
+ );
532
+
533
+ return schema as T;
534
+ }
535
+
536
+ /**
537
+ * Find many schemas by name and return them as an array in the same order.
538
+ * @param names
539
+ * @returns
540
+ */
541
+ static getMany<N extends string, T extends Schema>(
542
+ names: N[],
543
+ network: TNetwork
544
+ ) {
545
+ return names.map((name) => <T>this.get(name, network));
546
+ }
547
+
548
+ static getNames(network: TNetwork): string[] {
549
+ return Schema.schemas[network].map((schema) => schema.name);
550
+ }
551
+
552
+ /**
553
+ * Validade references
554
+ * @throws {SchemaError} if any reference is not valid
555
+ * @returns {true} if references are valid
556
+ */
557
+ static validate(network: TNetwork): true {
558
+ const errors: SchemaError[] = [];
559
+
560
+ this.schemas[network].forEach((schema) => {
561
+ if (!schema.references || Schema.exists(schema.references, network))
562
+ return;
563
+ else
564
+ errors.push(
565
+ new SchemaError(
566
+ "INVALID_REFERENCE",
567
+ `Schema ${schema.name} references ${schema.references} but it does not exist.`
568
+ )
569
+ );
570
+ });
571
+
572
+ if (errors.length) throw errors;
573
+ return true;
574
+ }
575
+
576
+ /**
577
+ * Replaces the schema list with a new list.
578
+ * @param schemas
579
+ */
580
+ static replaceAll(schemas: Schema[], network: TNetwork) {
581
+ this.schemas[network] = schemas;
582
+ }
583
+
584
+ /**
585
+ * Replaces a schema from the schema list.
586
+ * @throws {SchemaError} if desired schema name does not exist.
587
+ */
588
+ static replaceOne(schema: Schema, network: TNetwork) {
589
+ const idx = this.schemas[network].findIndex(
590
+ (item) => schema.name === item.name
591
+ );
592
+ if (!~idx)
593
+ throw new SchemaError(
594
+ "SCHEMA_NOT_FOUND",
595
+ `Schema ${schema.name} not found.`
596
+ );
597
+
598
+ this.schemas[idx] = schema;
599
+ }
600
+
601
+ /**
602
+ * Transforms the given raw schema to SchemaItem[]
603
+ *
604
+ * @example
605
+ * ```
606
+ * const schema = Schema.rawToObject("uint256 id, string name");
607
+ * // schema = [{ type: "uint256", name: "id", value: null }, { type: "string", name: "name", value: null }]
608
+ * ```
609
+ * @param abi
610
+ * @returns
611
+ */
612
+ static rawToObject(abi: string) {
613
+ const items = abi.trim().replace(/,\s+/gim, ",").split(",");
614
+ const schema: SchemaItem[] = items.map((item) => {
615
+ const [type, name] = item.split(" ");
616
+ return { type, name, value: null };
617
+ });
618
+
619
+ return schema;
620
+ }
621
+
622
+ /**
623
+ * Returns the raw schema string.
624
+ * @example
625
+ * ```ts
626
+ * const schema = new Schema({ name: "Grantee", schema: [{ type: "bool", name: "grantee", value: true }], uid: "0x000000000" });
627
+ * schema.raw; // "bool grantee"
628
+ * ```
629
+ */
630
+ get raw() {
631
+ return this.schema.map((item) => `${item.type} ${item.name}`).join(",");
632
+ }
633
+
634
+ get schema() {
635
+ return this._schema;
636
+ }
637
+
638
+ /**
639
+ * Get all schemas that references this schema. Note that this
640
+ * will return a reference to the original schema and all
641
+ * the changes made to it will reflect the original instance.
642
+ */
643
+ get children() {
644
+ return Schema.schemas[this.gap.network].filter(
645
+ (schema) =>
646
+ schema.references === this.name || schema.references === this.uid
647
+ );
648
+ }
649
+
650
+ /**
651
+ * Asserts and sets the schema value.
652
+ */
653
+ set schema(schema: SchemaItem[]) {
654
+ schema.forEach((item) => {
655
+ this.setValue(item.name, item.value);
656
+ });
657
+ }
658
+
659
+ }
@@ -0,0 +1,42 @@
1
+ const SchemaErrorCodes = {
2
+ INVALID_SCHEMA: 50001,
3
+ INVALID_SCHEMA_NAME: 50002,
4
+ INVALID_SCHEMA_TYPE: 50003,
5
+ SCHEMA_ALREADY_EXISTS: 50004,
6
+ SCHEMA_NOT_FOUND: 50005,
7
+ SCHEMA_NOT_CREATED: 50006,
8
+ MISSING_FIELD: 50007,
9
+ INVALID_REFERENCE: 50008,
10
+ INVALID_SCHEMA_FIELD: 50009,
11
+ INVALID_DATA: 50010,
12
+ REVOKE_ERROR: 50011,
13
+ ATTEST_ERROR: 50012,
14
+ INVALID_REF_UID: 50013,
15
+ REVOKATION_ERROR: 50014,
16
+ NOT_REVOCABLE: 50015,
17
+ REMOTE_STORAGE_UPLOAD: 50016,
18
+ };
19
+
20
+ export class SchemaError extends Error {
21
+ readonly code: number;
22
+ private readonly _message: string;
23
+ readonly originalError: any;
24
+
25
+ constructor(
26
+ code: keyof typeof SchemaErrorCodes,
27
+ append?: string,
28
+ originalError?: any
29
+ ) {
30
+ super(`${code}${append ? `: ${append}` : ""}`);
31
+ this._message = append || code.replace(/_/g, " ");
32
+ this.code = SchemaErrorCodes[code];
33
+ this.originalError = originalError;
34
+ }
35
+
36
+ get message(): string {
37
+ return this._message;
38
+ }
39
+ }
40
+
41
+ export class AttestationError extends SchemaError {}
42
+ export class RemoteStorageError extends SchemaError {}