@zkclaw/sdk 2.0.0 → 2.0.3

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