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