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