@zkclaw/sdk 2.0.0 → 2.0.1

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.
@@ -0,0 +1,42 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
8
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
9
+ }) : x)(function(x) {
10
+ if (typeof require !== "undefined") return require.apply(this, arguments);
11
+ throw Error('Dynamic require of "' + x + '" is not supported');
12
+ });
13
+ var __commonJS = (cb, mod) => function __require2() {
14
+ return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
15
+ };
16
+ var __export = (target, all) => {
17
+ for (var name in all)
18
+ __defProp(target, name, { get: all[name], enumerable: true });
19
+ };
20
+ var __copyProps = (to, from, except, desc) => {
21
+ if (from && typeof from === "object" || typeof from === "function") {
22
+ for (let key of __getOwnPropNames(from))
23
+ if (!__hasOwnProp.call(to, key) && key !== except)
24
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
25
+ }
26
+ return to;
27
+ };
28
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
29
+ // If the importer is in node compatibility mode or this is not an ESM
30
+ // file that has been converted to a CommonJS file using a Babel-
31
+ // compatible transform (i.e. "__esModule" has not been set), then set
32
+ // "default" to the CommonJS "module.exports" for node compatibility.
33
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
34
+ mod
35
+ ));
36
+
37
+ export {
38
+ __require,
39
+ __commonJS,
40
+ __export,
41
+ __toESM
42
+ };
@@ -0,0 +1,350 @@
1
+ // src/client.ts
2
+ import {
3
+ createPublicClient,
4
+ http,
5
+ formatUnits,
6
+ hashMessage
7
+ } from "viem";
8
+ import { privateKeyToAccount } from "viem/accounts";
9
+ import { base } from "viem/chains";
10
+ var DEFAULT_TOKEN_ADDRESS = "0x000000000000000000000000000000000000dead";
11
+ var DEFAULT_POST_THRESHOLD = BigInt("5000") * BigInt(10 ** 18);
12
+ var DEFAULT_PROMOTE_THRESHOLD = BigInt("2000000") * BigInt(10 ** 18);
13
+ var cachedConfig = null;
14
+ var configFetchPromise = null;
15
+ var ERC20_ABI = [
16
+ {
17
+ name: "balanceOf",
18
+ type: "function",
19
+ stateMutability: "view",
20
+ inputs: [{ name: "account", type: "address" }],
21
+ outputs: [{ name: "", type: "uint256" }]
22
+ }
23
+ ];
24
+ var ZKClaw = class {
25
+ constructor(config) {
26
+ this.config = null;
27
+ if (!config.privateKey && !config.account && !config.signer) {
28
+ throw new Error(
29
+ "ZKClaw requires one of: privateKey, account, or signer"
30
+ );
31
+ }
32
+ if (config.signer) {
33
+ this.signer = config.signer;
34
+ } else if (config.account) {
35
+ const account = config.account;
36
+ this.signer = {
37
+ getAddress: () => account.address,
38
+ signMessage: async (message) => {
39
+ if ("signMessage" in account && typeof account.signMessage === "function") {
40
+ return account.signMessage({ message });
41
+ }
42
+ throw new Error("Account does not support signMessage");
43
+ }
44
+ };
45
+ } else if (config.privateKey) {
46
+ const account = privateKeyToAccount(config.privateKey);
47
+ this.signer = {
48
+ getAddress: () => account.address,
49
+ signMessage: (message) => account.signMessage({ message })
50
+ };
51
+ } else {
52
+ throw new Error("Invalid configuration");
53
+ }
54
+ this.apiUrl = config.apiUrl || "https://zkclaw.com";
55
+ const rpcUrl = config.rpcUrl || process.env.BASE_RPC_URL || "https://mainnet.base.org";
56
+ this.publicClient = createPublicClient({
57
+ chain: base,
58
+ transport: http(rpcUrl)
59
+ });
60
+ this.fetchConfig().catch(() => {
61
+ });
62
+ }
63
+ /**
64
+ * Fetch remote config from API (cached)
65
+ */
66
+ async fetchConfig() {
67
+ if (this.config) return this.config;
68
+ if (cachedConfig) {
69
+ this.config = cachedConfig;
70
+ return cachedConfig;
71
+ }
72
+ if (configFetchPromise) {
73
+ const config = await configFetchPromise;
74
+ this.config = config;
75
+ return config;
76
+ }
77
+ configFetchPromise = (async () => {
78
+ try {
79
+ const response = await fetch(`${this.apiUrl}/api/config`);
80
+ if (!response.ok) throw new Error("Failed to fetch config");
81
+ const config = await response.json();
82
+ cachedConfig = config;
83
+ this.config = config;
84
+ return config;
85
+ } catch {
86
+ const defaultConfig = {
87
+ token: {
88
+ address: DEFAULT_TOKEN_ADDRESS,
89
+ chainId: 8453,
90
+ decimals: 18,
91
+ symbol: "ZKCLAW"
92
+ },
93
+ thresholds: {
94
+ post: 5e3,
95
+ promote: 2e6
96
+ },
97
+ limits: {
98
+ maxPostLength: 320,
99
+ maxImages: { farcaster: 2, twitter: 4 }
100
+ },
101
+ links: {
102
+ buy: `https://app.uniswap.org/swap?outputCurrency=${DEFAULT_TOKEN_ADDRESS}&chain=base`,
103
+ farcaster: "https://farcaster.xyz/zkclaw",
104
+ twitter: "https://x.com/zkclawcom"
105
+ }
106
+ };
107
+ this.config = defaultConfig;
108
+ return defaultConfig;
109
+ } finally {
110
+ configFetchPromise = null;
111
+ }
112
+ })();
113
+ return configFetchPromise;
114
+ }
115
+ /**
116
+ * Get current config (fetches if not cached)
117
+ */
118
+ async getConfig() {
119
+ return this.fetchConfig();
120
+ }
121
+ /**
122
+ * Get the wallet address
123
+ */
124
+ getAddress() {
125
+ const address = this.signer.getAddress();
126
+ if (typeof address === "string") return address;
127
+ throw new Error("getAddress returned a promise, use getAddressAsync instead");
128
+ }
129
+ /**
130
+ * Get the wallet address (async version)
131
+ */
132
+ async getAddressAsync() {
133
+ return this.signer.getAddress();
134
+ }
135
+ /**
136
+ * Generate a ZK proof locally
137
+ * Proof generation happens in your Node.js environment using WASM
138
+ */
139
+ async generateProofLocally() {
140
+ const { AnonBalanceVerifier, BALANCE_THRESHOLDS } = await import("./src-RO47KUEP.js");
141
+ const address = await this.signer.getAddress();
142
+ const message = `Verify $ZKCLAW balance for anonymous posting
143
+
144
+ Timestamp: ${Date.now()}`;
145
+ const signature = await this.signer.signMessage(message);
146
+ const messageHash = hashMessage(message);
147
+ const verifier = new AnonBalanceVerifier();
148
+ const { input } = await verifier.buildInput(address, BALANCE_THRESHOLDS.POST);
149
+ const actualBalance = input.storageProof[0].value;
150
+ if (actualBalance < BALANCE_THRESHOLDS.POST) {
151
+ const config = await this.fetchConfig();
152
+ throw new Error(
153
+ `Insufficient $ZKCLAW balance. Required: ${config.thresholds.post.toLocaleString()}, got: ${Number(formatUnits(actualBalance, 18)).toLocaleString()}. Buy at: ${config.links.buy}`
154
+ );
155
+ }
156
+ const threshold = actualBalance >= BALANCE_THRESHOLDS.PROMOTE ? BALANCE_THRESHOLDS.PROMOTE : BALANCE_THRESHOLDS.POST;
157
+ const { input: finalInput } = await verifier.buildInput(address, threshold);
158
+ const proofResult = await verifier.generateProof({
159
+ ...finalInput,
160
+ signature,
161
+ messageHash
162
+ });
163
+ return {
164
+ proof: {
165
+ proof: Array.from(proofResult.proof),
166
+ publicInputs: proofResult.publicInputs
167
+ },
168
+ balance: actualBalance
169
+ };
170
+ }
171
+ /**
172
+ * Post anonymously to Farcaster (and Twitter if you have 2M+ tokens)
173
+ *
174
+ * @param text - The text content of your post (max 320 characters)
175
+ * @param options - Optional images and embeds
176
+ * @returns Post result with URLs to the published content
177
+ *
178
+ * @example
179
+ * ```typescript
180
+ * // Simple post
181
+ * await bot.post('Hello world!')
182
+ *
183
+ * // Post with image
184
+ * await bot.post('Check this out', {
185
+ * images: ['https://example.com/image.png']
186
+ * })
187
+ *
188
+ * // Post with embed
189
+ * await bot.post('Great thread', {
190
+ * embeds: ['https://farcaster.xyz/user/0x123']
191
+ * })
192
+ * ```
193
+ */
194
+ async post(text, options) {
195
+ const config = await this.fetchConfig();
196
+ if (!text || text.trim().length === 0) {
197
+ return {
198
+ success: false,
199
+ error: "Text is required"
200
+ };
201
+ }
202
+ if (text.length > config.limits.maxPostLength) {
203
+ return {
204
+ success: false,
205
+ error: `Text exceeds ${config.limits.maxPostLength} character limit (got ${text.length})`
206
+ };
207
+ }
208
+ try {
209
+ const { proof, balance } = await this.generateProofLocally();
210
+ const promoteThreshold = BigInt(config.thresholds.promote) * BigInt(10 ** config.token.decimals);
211
+ const canPromote = balance >= promoteThreshold;
212
+ const body = {
213
+ proof,
214
+ text: text.trim(),
215
+ platforms: {
216
+ farcaster: true,
217
+ twitter: canPromote
218
+ // Auto-enable Twitter if user has enough balance
219
+ }
220
+ };
221
+ if (options?.images && options.images.length > 0) {
222
+ body.images = options.images;
223
+ }
224
+ if (options?.embeds && options.embeds.length > 0) {
225
+ body.embeds = options.embeds;
226
+ }
227
+ const response = await fetch(`${this.apiUrl}/api/post`, {
228
+ method: "POST",
229
+ headers: { "Content-Type": "application/json" },
230
+ body: JSON.stringify(body)
231
+ });
232
+ if (!response.ok) {
233
+ const errorData = await response.json().catch(() => ({}));
234
+ return {
235
+ success: false,
236
+ error: errorData.error || `HTTP error: ${response.status}`
237
+ };
238
+ }
239
+ const result = await response.json();
240
+ return result;
241
+ } catch (err) {
242
+ return {
243
+ success: false,
244
+ error: err instanceof Error ? err.message : "Failed to generate proof or post"
245
+ };
246
+ }
247
+ }
248
+ /**
249
+ * Check your $ZKCLAW token balance
250
+ *
251
+ * @returns Balance information including whether you can post/promote
252
+ *
253
+ * @example
254
+ * ```typescript
255
+ * const balance = await bot.getBalance()
256
+ * console.log(balance.formatted) // "5,000"
257
+ * console.log(balance.canPost) // true
258
+ * console.log(balance.canPromote) // false
259
+ * ```
260
+ */
261
+ async getBalance() {
262
+ const config = await this.fetchConfig();
263
+ const address = await this.signer.getAddress();
264
+ const balance = await this.publicClient.readContract({
265
+ address: config.token.address,
266
+ abi: ERC20_ABI,
267
+ functionName: "balanceOf",
268
+ args: [address]
269
+ });
270
+ const balanceBigInt = balance;
271
+ const formatted = Number(formatUnits(balanceBigInt, config.token.decimals)).toLocaleString();
272
+ const postThreshold = BigInt(config.thresholds.post) * BigInt(10 ** config.token.decimals);
273
+ const promoteThreshold = BigInt(config.thresholds.promote) * BigInt(10 ** config.token.decimals);
274
+ const canPost = balanceBigInt >= postThreshold;
275
+ const canPromote = balanceBigInt >= promoteThreshold;
276
+ let tier = "none";
277
+ if (canPromote) tier = "promote";
278
+ else if (canPost) tier = "post";
279
+ return {
280
+ balance: balanceBigInt.toString(),
281
+ formatted,
282
+ canPost,
283
+ canPromote,
284
+ tier
285
+ };
286
+ }
287
+ /**
288
+ * Generate a ZK proof without posting
289
+ *
290
+ * Useful for testing or caching proofs
291
+ *
292
+ * @returns Proof data that can be reused
293
+ */
294
+ async generateProof() {
295
+ try {
296
+ const { proof, balance } = await this.generateProofLocally();
297
+ const config = await this.fetchConfig();
298
+ const promoteThreshold = BigInt(config.thresholds.promote) * BigInt(10 ** config.token.decimals);
299
+ return {
300
+ success: true,
301
+ proof,
302
+ balance: balance.toString(),
303
+ tier: balance >= promoteThreshold ? "promote" : "post"
304
+ };
305
+ } catch (err) {
306
+ return {
307
+ success: false,
308
+ error: err instanceof Error ? err.message : "Failed to generate proof"
309
+ };
310
+ }
311
+ }
312
+ /**
313
+ * Get the Uniswap link to buy $ZKCLAW tokens
314
+ */
315
+ async getBuyLink() {
316
+ const config = await this.fetchConfig();
317
+ return config.links.buy;
318
+ }
319
+ /**
320
+ * Get the Uniswap link to buy $ZKCLAW tokens (sync version with fallback)
321
+ */
322
+ getBuyLinkSync() {
323
+ const tokenAddress = this.config?.token.address || DEFAULT_TOKEN_ADDRESS;
324
+ return `https://app.uniswap.org/swap?outputCurrency=${tokenAddress}&chain=base`;
325
+ }
326
+ /**
327
+ * Get token requirements
328
+ */
329
+ async getRequirements() {
330
+ const config = await this.fetchConfig();
331
+ return {
332
+ post: `${config.thresholds.post.toLocaleString()} $ZKCLAW`,
333
+ promote: `${config.thresholds.promote.toLocaleString()} $ZKCLAW`
334
+ };
335
+ }
336
+ /**
337
+ * Get token requirements (sync version with defaults)
338
+ */
339
+ getRequirementsSync() {
340
+ const config = this.config;
341
+ return {
342
+ post: `${(config?.thresholds.post || 5e3).toLocaleString()} $ZKCLAW`,
343
+ promote: `${(config?.thresholds.promote || 2e6).toLocaleString()} $ZKCLAW`
344
+ };
345
+ }
346
+ };
347
+
348
+ export {
349
+ ZKClaw
350
+ };