@tangle-network/tcloud 0.1.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.
@@ -0,0 +1,573 @@
1
+ // src/shielded.ts
2
+ import { privateKeyToAccount } from "viem/accounts";
3
+ import { keccak256, encodeAbiParameters, parseAbiParameters, concat, toBytes } from "viem";
4
+
5
+ // src/client.ts
6
+ var DEFAULT_BASE_URL = "https://api.tangleai.cloud/v1";
7
+ async function proxiedFetch(privacy, url, init, streaming) {
8
+ if (!privacy || privacy.mode === "direct") {
9
+ return fetch(url, init);
10
+ }
11
+ if (privacy.mode === "relayer") {
12
+ if (!privacy.relayerUrl) {
13
+ throw new Error('relayerUrl is required when privacy mode is "relayer"');
14
+ }
15
+ const proxyPath = streaming ? "/relay/proxy-stream" : "/relay/proxy";
16
+ const hdrs = {};
17
+ if (init.headers) {
18
+ const entries = init.headers instanceof Headers ? Array.from(init.headers.entries()) : Object.entries(init.headers);
19
+ for (const [k, v] of entries) hdrs[k] = v;
20
+ }
21
+ return fetch(`${privacy.relayerUrl}${proxyPath}`, {
22
+ method: "POST",
23
+ headers: { "Content-Type": "application/json" },
24
+ body: JSON.stringify({
25
+ target: url,
26
+ body: typeof init.body === "string" ? JSON.parse(init.body) : init.body,
27
+ headers: hdrs
28
+ })
29
+ });
30
+ }
31
+ if (privacy.mode === "socks5") {
32
+ if (!privacy.socksProxy) {
33
+ throw new Error('socksProxy is required when privacy mode is "socks5"');
34
+ }
35
+ const { SocksProxyAgent } = await import("socks-proxy-agent");
36
+ const agent = new SocksProxyAgent(privacy.socksProxy);
37
+ return fetch(url, {
38
+ ...init,
39
+ // @ts-expect-error agent is supported by Node's undici but not in the standard RequestInit type
40
+ agent
41
+ });
42
+ }
43
+ return fetch(url, init);
44
+ }
45
+ var TCloudClient = class {
46
+ baseURL;
47
+ apiKey;
48
+ model;
49
+ headers;
50
+ spendAuthFn;
51
+ privacy;
52
+ limits;
53
+ _totalSpent = 0;
54
+ _requestCount = 0;
55
+ constructor(config = {}) {
56
+ this.baseURL = (config.baseURL || DEFAULT_BASE_URL).replace(/\/$/, "");
57
+ this.apiKey = config.apiKey || process.env.TCLOUD_API_KEY || process.env.OPENAI_API_KEY;
58
+ this.model = config.model || "gpt-4o-mini";
59
+ this.privacy = config.privacy;
60
+ this.limits = config.limits;
61
+ this.headers = {
62
+ "Content-Type": "application/json",
63
+ "X-Tangle-Client": "tcloud-sdk/0.1.0"
64
+ };
65
+ if (this.apiKey) {
66
+ this.headers["Authorization"] = `Bearer ${this.apiKey}`;
67
+ }
68
+ if (config.routing?.prefer) {
69
+ this.headers["X-Tangle-Operator"] = config.routing.prefer;
70
+ }
71
+ if (config.routing?.region) {
72
+ this.headers["X-Tangle-Region"] = config.routing.region;
73
+ }
74
+ }
75
+ /** Set the SpendAuth signer for private mode */
76
+ setSpendAuthSigner(fn) {
77
+ this.spendAuthFn = fn;
78
+ }
79
+ /** Current metering stats */
80
+ get usage() {
81
+ return {
82
+ totalSpent: this._totalSpent,
83
+ requestCount: this._requestCount,
84
+ limits: this.limits ? { ...this.limits } : void 0
85
+ };
86
+ }
87
+ /** Check spending limits before a request. Throws TCloudError if blocked. */
88
+ checkLimits() {
89
+ if (!this.limits) return;
90
+ if (this.limits.maxRequests && this._requestCount >= this.limits.maxRequests) {
91
+ this.limits.onLimitReached?.({ type: "requests", current: this._requestCount, limit: this.limits.maxRequests });
92
+ throw new TCloudError(429, `Request limit reached (${this._requestCount}/${this.limits.maxRequests})`);
93
+ }
94
+ if (this.limits.maxTotalSpend && this._totalSpent >= this.limits.maxTotalSpend) {
95
+ this.limits.onLimitReached?.({ type: "total", current: this._totalSpent, limit: this.limits.maxTotalSpend });
96
+ throw new TCloudError(429, `Spending limit reached ($${this._totalSpent.toFixed(6)}/$${this.limits.maxTotalSpend})`);
97
+ }
98
+ if (this.limits.maxRequests && this.limits.onLimitWarning) {
99
+ const pct = this._requestCount / this.limits.maxRequests;
100
+ if (pct >= 0.8) this.limits.onLimitWarning({ type: "requests", current: this._requestCount, limit: this.limits.maxRequests });
101
+ }
102
+ if (this.limits.maxTotalSpend && this.limits.onLimitWarning) {
103
+ const pct = this._totalSpent / this.limits.maxTotalSpend;
104
+ if (pct >= 0.8) this.limits.onLimitWarning({ type: "total", current: this._totalSpent, limit: this.limits.maxTotalSpend });
105
+ }
106
+ }
107
+ /** Track cost after a response */
108
+ trackCost(completion) {
109
+ this._requestCount++;
110
+ if (completion.usage) {
111
+ const tokens = completion.usage.total_tokens || 0;
112
+ const estimatedCost = tokens * 1e-6;
113
+ this._totalSpent += estimatedCost;
114
+ if (this.limits?.maxCostPerRequest && estimatedCost > this.limits.maxCostPerRequest) {
115
+ this.limits.onLimitReached?.({ type: "cost", current: estimatedCost, limit: this.limits.maxCostPerRequest });
116
+ }
117
+ }
118
+ }
119
+ /** Chat completion (non-streaming) */
120
+ async chat(options) {
121
+ this.checkLimits();
122
+ const headers = { ...this.headers };
123
+ if (this.spendAuthFn) {
124
+ const auth = await this.spendAuthFn();
125
+ headers["X-Payment-Signature"] = JSON.stringify(auth);
126
+ delete headers["Authorization"];
127
+ }
128
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/chat/completions`, {
129
+ method: "POST",
130
+ headers,
131
+ body: JSON.stringify({
132
+ model: options.model || this.model,
133
+ messages: options.messages,
134
+ temperature: options.temperature,
135
+ max_tokens: options.maxTokens,
136
+ stream: false,
137
+ stop: options.stop,
138
+ top_p: options.topP,
139
+ frequency_penalty: options.frequencyPenalty,
140
+ presence_penalty: options.presencePenalty,
141
+ response_format: options.responseFormat,
142
+ tools: options.tools
143
+ })
144
+ }, false);
145
+ if (!res.ok) {
146
+ const err = await res.json().catch(() => ({ error: res.statusText }));
147
+ throw new TCloudError(res.status, err.error?.message || err.error || err.message || res.statusText);
148
+ }
149
+ const completion = await res.json();
150
+ this.trackCost(completion);
151
+ return completion;
152
+ }
153
+ /** Chat completion (streaming) — returns an async iterator of chunks */
154
+ async *chatStream(options) {
155
+ this.checkLimits();
156
+ const headers = { ...this.headers };
157
+ if (this.spendAuthFn) {
158
+ const auth = await this.spendAuthFn();
159
+ headers["X-Payment-Signature"] = JSON.stringify(auth);
160
+ delete headers["Authorization"];
161
+ }
162
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/chat/completions`, {
163
+ method: "POST",
164
+ headers,
165
+ body: JSON.stringify({
166
+ model: options.model || this.model,
167
+ messages: options.messages,
168
+ temperature: options.temperature,
169
+ max_tokens: options.maxTokens,
170
+ stream: true,
171
+ stop: options.stop,
172
+ top_p: options.topP
173
+ })
174
+ }, true);
175
+ if (!res.ok) {
176
+ const err = await res.json().catch(() => ({ error: res.statusText }));
177
+ throw new TCloudError(res.status, err.error || err.message || res.statusText);
178
+ }
179
+ const reader = res.body.getReader();
180
+ const decoder = new TextDecoder();
181
+ let buf = "";
182
+ while (true) {
183
+ const { done, value } = await reader.read();
184
+ if (done) break;
185
+ buf += decoder.decode(value, { stream: true });
186
+ const lines = buf.split("\n");
187
+ buf = lines.pop() || "";
188
+ for (const line of lines) {
189
+ if (!line.startsWith("data: ")) continue;
190
+ const data = line.slice(6).trim();
191
+ if (data === "[DONE]") {
192
+ this._requestCount++;
193
+ return;
194
+ }
195
+ try {
196
+ yield JSON.parse(data);
197
+ } catch {
198
+ }
199
+ }
200
+ }
201
+ }
202
+ /** Convenience: send a single message and get the text response */
203
+ async ask(message, modelOrOptions) {
204
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
205
+ const completion = await this.chat({
206
+ messages: [{ role: "user", content: message }],
207
+ ...options
208
+ });
209
+ return completion.choices[0]?.message?.content || "";
210
+ }
211
+ /** Convenience: send a single message and get the full completion (with usage) */
212
+ async askFull(message, modelOrOptions) {
213
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
214
+ return this.chat({
215
+ messages: [{ role: "user", content: message }],
216
+ ...options
217
+ });
218
+ }
219
+ /** Convenience: stream a single message and yield text chunks */
220
+ async *askStream(message, modelOrOptions) {
221
+ const options = typeof modelOrOptions === "string" ? { model: modelOrOptions } : modelOrOptions;
222
+ for await (const chunk of this.chatStream({
223
+ messages: [{ role: "user", content: message }],
224
+ ...options
225
+ })) {
226
+ const content = chunk.choices[0]?.delta?.content;
227
+ if (content) yield content;
228
+ }
229
+ }
230
+ /** List available models */
231
+ async models() {
232
+ const res = await proxiedFetch(this.privacy, `${this.baseURL}/models`, { headers: this.headers }, false);
233
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch models");
234
+ const data = await res.json();
235
+ return data.data || [];
236
+ }
237
+ /** List active operators */
238
+ async operators() {
239
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
240
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/operators`, { headers: this.headers }, false);
241
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch operators");
242
+ return res.json();
243
+ }
244
+ /** Get credit balance */
245
+ async credits() {
246
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
247
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/billing`, { headers: this.headers }, false);
248
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch credits");
249
+ return res.json();
250
+ }
251
+ /** Add credits */
252
+ async addCredits(amount) {
253
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
254
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/billing`, {
255
+ method: "POST",
256
+ headers: this.headers,
257
+ body: JSON.stringify({ amount })
258
+ }, false);
259
+ if (!res.ok) throw new TCloudError(res.status, "Failed to add credits");
260
+ return res.json();
261
+ }
262
+ /** Create a new API key */
263
+ async createKey(name) {
264
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
265
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys`, {
266
+ method: "POST",
267
+ headers: this.headers,
268
+ body: JSON.stringify({ name })
269
+ }, false);
270
+ if (!res.ok) throw new TCloudError(res.status, "Failed to create API key");
271
+ return res.json();
272
+ }
273
+ /** List API keys */
274
+ async keys() {
275
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
276
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys`, { headers: this.headers }, false);
277
+ if (!res.ok) throw new TCloudError(res.status, "Failed to fetch keys");
278
+ return res.json();
279
+ }
280
+ /** Revoke an API key */
281
+ async revokeKey(id) {
282
+ const apiRoot = this.baseURL.replace(/\/v1$/, "");
283
+ const res = await proxiedFetch(this.privacy, `${apiRoot}/api/keys/${id}`, {
284
+ method: "DELETE",
285
+ headers: this.headers
286
+ }, false);
287
+ if (!res.ok) throw new TCloudError(res.status, "Failed to revoke key");
288
+ }
289
+ /** Search models by name, provider, or capability */
290
+ async searchModels(query) {
291
+ const all = await this.models();
292
+ const q = query.toLowerCase();
293
+ return all.filter(
294
+ (m) => m.id.toLowerCase().includes(q) || m.name.toLowerCase().includes(q) || m._provider && m._provider.toLowerCase().includes(q)
295
+ );
296
+ }
297
+ /** Estimate cost for a request (without sending it) */
298
+ async estimateCost(options) {
299
+ const models = await this.models();
300
+ const model = models.find((m) => m.id === (options.model || this.model));
301
+ if (!model) return { inputCost: 0, outputCost: 0, total: 0 };
302
+ const inputCost = options.inputTokens * parseFloat(model.pricing.prompt);
303
+ const outputCost = options.outputTokens * parseFloat(model.pricing.completion);
304
+ return { inputCost, outputCost, total: inputCost + outputCost };
305
+ }
306
+ };
307
+ var TCloudError = class extends Error {
308
+ constructor(status, message) {
309
+ super(message);
310
+ this.status = status;
311
+ this.name = "TCloudError";
312
+ }
313
+ };
314
+
315
+ // src/shielded.ts
316
+ var SPEND_TYPEHASH = keccak256(
317
+ toBytes(
318
+ "SpendAuthorization(bytes32 commitment,uint64 serviceId,uint8 jobIndex,uint256 amount,address operator,uint256 nonce,uint64 expiry)"
319
+ )
320
+ );
321
+ var DEFAULT_DOMAIN = {
322
+ name: "ShieldedCredits",
323
+ version: "1"
324
+ };
325
+ function generateWallet() {
326
+ const privateKeyBytes = crypto.getRandomValues(new Uint8Array(32));
327
+ const privateKey = "0x" + Array.from(privateKeyBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
328
+ const saltBytes = crypto.getRandomValues(new Uint8Array(32));
329
+ const salt = "0x" + Array.from(saltBytes).map((b) => b.toString(16).padStart(2, "0")).join("");
330
+ const account = privateKeyToAccount(privateKey);
331
+ const commitment = keccak256(
332
+ encodeAbiParameters(
333
+ parseAbiParameters("address, bytes32"),
334
+ [account.address, salt]
335
+ )
336
+ );
337
+ return { privateKey, address: account.address, commitment, salt };
338
+ }
339
+ async function signSpendAuth(wallet, params) {
340
+ const account = privateKeyToAccount(wallet.privateKey);
341
+ const domainSeparator = keccak256(
342
+ encodeAbiParameters(
343
+ parseAbiParameters("bytes32, bytes32, bytes32, uint256, address"),
344
+ [
345
+ keccak256(toBytes("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)")),
346
+ keccak256(toBytes(DEFAULT_DOMAIN.name)),
347
+ keccak256(toBytes(DEFAULT_DOMAIN.version)),
348
+ BigInt(params.chainId),
349
+ params.creditsAddress
350
+ ]
351
+ )
352
+ );
353
+ const structHash = keccak256(
354
+ encodeAbiParameters(
355
+ parseAbiParameters("bytes32, bytes32, uint64, uint8, uint256, address, uint256, uint64"),
356
+ [
357
+ SPEND_TYPEHASH,
358
+ wallet.commitment,
359
+ params.serviceId,
360
+ params.jobIndex,
361
+ params.amount,
362
+ params.operator,
363
+ params.nonce,
364
+ params.expiry
365
+ ]
366
+ )
367
+ );
368
+ const digest = keccak256(
369
+ concat([toBytes("0x1901"), toBytes(domainSeparator), toBytes(structHash)])
370
+ );
371
+ const signature = await account.sign({ hash: digest });
372
+ return {
373
+ commitment: wallet.commitment,
374
+ serviceId: params.serviceId.toString(),
375
+ jobIndex: params.jobIndex,
376
+ amount: params.amount.toString(),
377
+ operator: params.operator,
378
+ nonce: params.nonce.toString(),
379
+ expiry: params.expiry.toString(),
380
+ signature
381
+ };
382
+ }
383
+ function estimateCost(inputTokens, maxOutputTokens, inputPricePerM = 0.15, outputPricePerM = 0.6) {
384
+ const cost = inputTokens / 1e6 * inputPricePerM + maxOutputTokens / 1e6 * outputPricePerM;
385
+ return BigInt(Math.ceil(cost * 1e6));
386
+ }
387
+ function createShieldedClient(config = {}) {
388
+ const wallet = config.wallet || generateWallet();
389
+ const chainId = config.chainId || 3799;
390
+ const creditsAddress = config.creditsAddress || "0x0000000000000000000000000000000000000000";
391
+ const operatorAddress = config.operatorAddress || "0x0000000000000000000000000000000000000000";
392
+ const serviceId = config.serviceId || 1n;
393
+ let nonce = 0n;
394
+ const client = new TCloudClient({
395
+ ...config,
396
+ apiKey: void 0
397
+ // no API key in private mode
398
+ });
399
+ client.setSpendAuthSigner(async () => {
400
+ const currentNonce = nonce++;
401
+ const amount = estimateCost(500, 4096);
402
+ const buffered = amount + amount / 5n;
403
+ return signSpendAuth(wallet, {
404
+ serviceId,
405
+ jobIndex: 0,
406
+ amount: buffered,
407
+ operator: operatorAddress,
408
+ nonce: currentNonce,
409
+ expiry: BigInt(Math.floor(Date.now() / 1e3) + 300),
410
+ chainId,
411
+ creditsAddress
412
+ });
413
+ });
414
+ const monitor = { lastBalance: 0n, timer: null, replenishing: false };
415
+ if (config.autoReplenish) {
416
+ const ar = config.autoReplenish;
417
+ const intervalMs = ar.checkIntervalMs ?? 3e4;
418
+ const check = async () => {
419
+ try {
420
+ const balance = await fetchBalance(wallet.commitment, creditsAddress, chainId);
421
+ monitor.lastBalance = balance;
422
+ if (balance < ar.minBalance && !monitor.replenishing) {
423
+ monitor.replenishing = true;
424
+ try {
425
+ if (ar.fundingSource === "relayer") {
426
+ await replenishViaRelayer(ar.relayerUrl, wallet.commitment, wallet.privateKey);
427
+ } else {
428
+ await replenishDirect(
429
+ ar.fundingWalletKey,
430
+ ar.tokenAddress,
431
+ ar.replenishAmount,
432
+ wallet.commitment,
433
+ wallet.address,
434
+ creditsAddress,
435
+ chainId
436
+ );
437
+ }
438
+ monitor.lastBalance = await fetchBalance(wallet.commitment, creditsAddress, chainId);
439
+ console.log(`[tcloud/shielded] replenished. balance=${monitor.lastBalance}`);
440
+ } finally {
441
+ monitor.replenishing = false;
442
+ }
443
+ }
444
+ } catch (err) {
445
+ console.error("[tcloud/shielded] auto-replenish error:", err instanceof Error ? err.message : String(err));
446
+ }
447
+ };
448
+ void check();
449
+ monitor.timer = setInterval(() => void check(), intervalMs);
450
+ }
451
+ function stopAutoReplenish() {
452
+ if (monitor.timer) {
453
+ clearInterval(monitor.timer);
454
+ monitor.timer = null;
455
+ }
456
+ }
457
+ return Object.assign(client, { wallet, stopAutoReplenish });
458
+ }
459
+ var GET_ACCOUNT_ABI = [{
460
+ type: "function",
461
+ name: "getAccount",
462
+ inputs: [{ name: "commitment", type: "bytes32" }],
463
+ outputs: [{
464
+ name: "",
465
+ type: "tuple",
466
+ components: [
467
+ { name: "spendingKey", type: "address" },
468
+ { name: "token", type: "address" },
469
+ { name: "balance", type: "uint256" },
470
+ { name: "totalFunded", type: "uint256" },
471
+ { name: "totalSpent", type: "uint256" },
472
+ { name: "nonce", type: "uint256" }
473
+ ]
474
+ }],
475
+ stateMutability: "view"
476
+ }];
477
+ var FUND_CREDITS_ABI = [{
478
+ type: "function",
479
+ name: "fundCredits",
480
+ inputs: [
481
+ { name: "token", type: "address" },
482
+ { name: "amount", type: "uint256" },
483
+ { name: "commitment", type: "bytes32" },
484
+ { name: "spendingKey", type: "address" }
485
+ ],
486
+ outputs: [],
487
+ stateMutability: "nonpayable"
488
+ }];
489
+ var ERC20_APPROVE_ABI = [{
490
+ type: "function",
491
+ name: "approve",
492
+ inputs: [
493
+ { name: "spender", type: "address" },
494
+ { name: "amount", type: "uint256" }
495
+ ],
496
+ outputs: [{ name: "", type: "bool" }],
497
+ stateMutability: "nonpayable"
498
+ }];
499
+ function makeChain(chainId, rpcUrl) {
500
+ return {
501
+ id: chainId,
502
+ name: `chain-${chainId}`,
503
+ nativeCurrency: { name: "Ether", symbol: "ETH", decimals: 18 },
504
+ rpcUrls: { default: { http: [rpcUrl] } }
505
+ };
506
+ }
507
+ function getRpcUrl(chainId) {
508
+ if (chainId === 3799) return "https://testnet-rpc.tangle.tools";
509
+ if (chainId === 5845) return "https://rpc.tangle.tools";
510
+ return "http://localhost:8545";
511
+ }
512
+ async function fetchBalance(commitment, creditsAddress, chainId) {
513
+ const { createPublicClient, http } = await import("viem");
514
+ const rpcUrl = getRpcUrl(chainId);
515
+ const client = createPublicClient({ chain: makeChain(chainId, rpcUrl), transport: http(rpcUrl) });
516
+ const result = await client.readContract({
517
+ address: creditsAddress,
518
+ abi: GET_ACCOUNT_ABI,
519
+ functionName: "getAccount",
520
+ args: [commitment]
521
+ });
522
+ return result.balance;
523
+ }
524
+ async function replenishViaRelayer(relayerUrl, commitment, spendingKey) {
525
+ const res = await fetch(`${relayerUrl.replace(/\/$/, "")}/relay/fund-credits`, {
526
+ method: "POST",
527
+ headers: { "Content-Type": "application/json" },
528
+ body: JSON.stringify({
529
+ anchorProof: { proof: "0x", auxPublicInputs: "0x", externalData: "0x", publicInputs: "0x", encryptions: "0x" },
530
+ commitment,
531
+ spendingKey
532
+ })
533
+ });
534
+ if (!res.ok) {
535
+ const body = await res.text();
536
+ throw new Error(`relayer fund-credits failed (${res.status}): ${body}`);
537
+ }
538
+ }
539
+ async function replenishDirect(fundingKey, tokenAddress, amount, commitment, spendingKeyAddress, creditsAddress, chainId) {
540
+ const { createPublicClient, createWalletClient, http } = await import("viem");
541
+ const { privateKeyToAccount: toAccount } = await import("viem/accounts");
542
+ const rpcUrl = getRpcUrl(chainId);
543
+ const chain = makeChain(chainId, rpcUrl);
544
+ const account = toAccount(fundingKey);
545
+ const pub = createPublicClient({ chain, transport: http(rpcUrl) });
546
+ const wal = createWalletClient({ account, chain, transport: http(rpcUrl) });
547
+ const approveHash = await wal.writeContract({
548
+ address: tokenAddress,
549
+ abi: ERC20_APPROVE_ABI,
550
+ functionName: "approve",
551
+ args: [creditsAddress, amount]
552
+ });
553
+ await pub.waitForTransactionReceipt({ hash: approveHash });
554
+ const fundHash = await wal.writeContract({
555
+ address: creditsAddress,
556
+ abi: FUND_CREDITS_ABI,
557
+ functionName: "fundCredits",
558
+ args: [tokenAddress, amount, commitment, spendingKeyAddress]
559
+ });
560
+ const receipt = await pub.waitForTransactionReceipt({ hash: fundHash });
561
+ if (receipt.status !== "success") {
562
+ throw new Error(`fundCredits reverted (tx: ${fundHash})`);
563
+ }
564
+ }
565
+
566
+ export {
567
+ TCloudClient,
568
+ TCloudError,
569
+ generateWallet,
570
+ signSpendAuth,
571
+ estimateCost,
572
+ createShieldedClient
573
+ };
@@ -0,0 +1,49 @@
1
+ import {
2
+ TCloudClient,
3
+ createShieldedClient,
4
+ generateWallet
5
+ } from "./chunk-4AOQNUQ3.js";
6
+
7
+ // src/index.ts
8
+ var TCloud = class _TCloud extends TCloudClient {
9
+ constructor(config) {
10
+ super(config);
11
+ }
12
+ /**
13
+ * Create a standard client with API key authentication.
14
+ *
15
+ * ```ts
16
+ * const client = TCloud.create({ apiKey: 'sk-tan-...' })
17
+ * ```
18
+ */
19
+ static create(config) {
20
+ return new _TCloud(config);
21
+ }
22
+ /**
23
+ * Create a shielded (private) client.
24
+ * Generates an ephemeral wallet and signs SpendAuth automatically.
25
+ * No API key needed. The operator never learns your identity.
26
+ *
27
+ * ```ts
28
+ * const client = TCloud.shielded()
29
+ * const response = await client.ask('Hello from the shadows')
30
+ * console.log(client.wallet.commitment) // anonymous credit account
31
+ * ```
32
+ */
33
+ static shielded(config) {
34
+ return createShieldedClient(config);
35
+ }
36
+ /**
37
+ * Generate a new ephemeral wallet (without creating a client).
38
+ *
39
+ * ```ts
40
+ * const wallet = TCloud.generateWallet()
41
+ * console.log(wallet.address, wallet.commitment)
42
+ * ```
43
+ */
44
+ static generateWallet = generateWallet;
45
+ };
46
+
47
+ export {
48
+ TCloud
49
+ };