@0xgasless/agentos 0.0.0-stage → 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.
Files changed (36) hide show
  1. package/README.md +32 -2
  2. package/dist/config/env.d.ts +12 -0
  3. package/dist/config/env.js +63 -0
  4. package/dist/core/AgentOSClient.d.ts +48 -0
  5. package/dist/core/AgentOSClient.js +115 -0
  6. package/dist/core/IntentBuilder.d.ts +76 -0
  7. package/dist/core/IntentBuilder.js +47 -0
  8. package/dist/cre/CREWorkflowClient.d.ts +22 -0
  9. package/dist/cre/CREWorkflowClient.js +148 -0
  10. package/dist/cre/creTypes.d.ts +58 -0
  11. package/dist/cre/creTypes.js +1 -0
  12. package/dist/http/fetchWithRetry.d.ts +12 -0
  13. package/dist/http/fetchWithRetry.js +49 -0
  14. package/dist/index.d.ts +16 -0
  15. package/dist/index.js +16 -0
  16. package/dist/protocols/erc8004/IdentityManager.d.ts +52 -0
  17. package/dist/protocols/erc8004/IdentityManager.js +120 -0
  18. package/dist/protocols/erc8004/erc8004Types.d.ts +15 -0
  19. package/dist/protocols/erc8004/erc8004Types.js +1 -0
  20. package/dist/protocols/x402/FacilitatorClient.d.ts +9 -0
  21. package/dist/protocols/x402/FacilitatorClient.js +106 -0
  22. package/dist/protocols/x402/X402PaymentHandler.d.ts +25 -0
  23. package/dist/protocols/x402/X402PaymentHandler.js +139 -0
  24. package/dist/protocols/x402/x402Types.d.ts +52 -0
  25. package/dist/protocols/x402/x402Types.js +1 -0
  26. package/dist/security/ValidationGate.d.ts +12 -0
  27. package/dist/security/ValidationGate.js +14 -0
  28. package/dist/sxt/SXTQueryProvider.d.ts +30 -0
  29. package/dist/sxt/SXTQueryProvider.js +220 -0
  30. package/dist/sxt/sxtTypes.d.ts +48 -0
  31. package/dist/sxt/sxtTypes.js +1 -0
  32. package/dist/telemetry/DashboardLogger.d.ts +35 -0
  33. package/dist/telemetry/DashboardLogger.js +66 -0
  34. package/dist/wallet/GaslessWalletProvider.d.ts +55 -0
  35. package/dist/wallet/GaslessWalletProvider.js +99 -0
  36. package/package.json +47 -4
@@ -0,0 +1,49 @@
1
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
2
+ function isAbortError(e) {
3
+ return e instanceof Error && e.name === "AbortError";
4
+ }
5
+ function shouldRetry(status, opts) {
6
+ if (status === 429)
7
+ return opts.retryOnRateLimit;
8
+ return status >= 500 && status <= 599;
9
+ }
10
+ /**
11
+ * Bounded retries with exponential backoff and jitter for oracle / indexer drift.
12
+ */
13
+ export async function fetchWithRetry(input, init, opts) {
14
+ let attempt = 0;
15
+ let lastError;
16
+ while (attempt <= opts.maxRetries) {
17
+ try {
18
+ const res = await fetch(input, { ...init, signal: opts.signal });
19
+ if (!shouldRetry(res.status, opts) || attempt === opts.maxRetries) {
20
+ return res;
21
+ }
22
+ const backoff = opts.baseDelayMs * 2 ** attempt + Math.floor(Math.random() * 120);
23
+ await sleep(backoff);
24
+ attempt += 1;
25
+ }
26
+ catch (e) {
27
+ lastError = e;
28
+ if (isAbortError(e))
29
+ throw e;
30
+ if (attempt === opts.maxRetries)
31
+ throw e;
32
+ const backoff = opts.baseDelayMs * 2 ** attempt + Math.floor(Math.random() * 120);
33
+ await sleep(backoff);
34
+ attempt += 1;
35
+ }
36
+ }
37
+ throw lastError instanceof Error ? lastError : new Error(String(lastError));
38
+ }
39
+ export function mergeSignals(a, b) {
40
+ if (a.aborted)
41
+ return a;
42
+ if (b.aborted)
43
+ return b;
44
+ const c = new AbortController();
45
+ const onAbort = () => c.abort();
46
+ a.addEventListener("abort", onAbort);
47
+ b.addEventListener("abort", onAbort);
48
+ return c.signal;
49
+ }
@@ -0,0 +1,16 @@
1
+ export * from "./core/AgentOSClient.js";
2
+ export * from "./core/IntentBuilder.js";
3
+ export * from "./security/ValidationGate.js";
4
+ export * from "./wallet/GaslessWalletProvider.js";
5
+ export * from "./cre/CREWorkflowClient.js";
6
+ export * from "./cre/creTypes.js";
7
+ export * from "./sxt/SXTQueryProvider.js";
8
+ export * from "./sxt/sxtTypes.js";
9
+ export * from "./config/env.js";
10
+ export * from "./http/fetchWithRetry.js";
11
+ export * from "./protocols/x402/X402PaymentHandler.js";
12
+ export * from "./protocols/x402/FacilitatorClient.js";
13
+ export * from "./protocols/x402/x402Types.js";
14
+ export * from "./protocols/erc8004/IdentityManager.js";
15
+ export * from "./protocols/erc8004/erc8004Types.js";
16
+ export * from "./telemetry/DashboardLogger.js";
package/dist/index.js ADDED
@@ -0,0 +1,16 @@
1
+ export * from "./core/AgentOSClient.js";
2
+ export * from "./core/IntentBuilder.js";
3
+ export * from "./security/ValidationGate.js";
4
+ export * from "./wallet/GaslessWalletProvider.js";
5
+ export * from "./cre/CREWorkflowClient.js";
6
+ export * from "./cre/creTypes.js";
7
+ export * from "./sxt/SXTQueryProvider.js";
8
+ export * from "./sxt/sxtTypes.js";
9
+ export * from "./config/env.js";
10
+ export * from "./http/fetchWithRetry.js";
11
+ export * from "./protocols/x402/X402PaymentHandler.js";
12
+ export * from "./protocols/x402/FacilitatorClient.js";
13
+ export * from "./protocols/x402/x402Types.js";
14
+ export * from "./protocols/erc8004/IdentityManager.js";
15
+ export * from "./protocols/erc8004/erc8004Types.js";
16
+ export * from "./telemetry/DashboardLogger.js";
@@ -0,0 +1,52 @@
1
+ import { GaslessWalletProvider } from "../../wallet/GaslessWalletProvider.js";
2
+ import { SXTQueryProvider } from "../../sxt/SXTQueryProvider.js";
3
+ import type { ERC8004FeedbackInput, ERC8004RegistryConfig } from "./erc8004Types.js";
4
+ /**
5
+ * Hooks for ERC-8004 Identity, Reputation, and Validation registries.
6
+ */
7
+ export declare class IdentityManager {
8
+ private readonly wallet;
9
+ private readonly sxt;
10
+ private registries;
11
+ constructor(wallet: GaslessWalletProvider, sxt: SXTQueryProvider, registries: ERC8004RegistryConfig);
12
+ setRegistries(registries: ERC8004RegistryConfig): void;
13
+ /**
14
+ * Registers a new Agent Identity on the ERC-8004 Identity Registry.
15
+ */
16
+ register(agentURI: string, donSignature: string): Promise<{
17
+ success: boolean;
18
+ txHash?: string;
19
+ error?: string;
20
+ }>;
21
+ /**
22
+ * Fetches the agent's core metadata URI from the Identity Registry.
23
+ */
24
+ getIdentity(agentId: bigint): Promise<{
25
+ metadataUri: string;
26
+ verifiedWallet?: `0x${string}`;
27
+ }>;
28
+ /**
29
+ * Fetches the agent's verified, ZK-proven reputation score from SXT and the Reputation Registry.
30
+ */
31
+ getReputation(agentId: string): Promise<{
32
+ score: number;
33
+ count: number;
34
+ proof: string;
35
+ }>;
36
+ /**
37
+ * Commits an on-chain trust feedback score for another agent on the Reputation Registry.
38
+ */
39
+ giveFeedback(input: ERC8004FeedbackInput, donSignature: string): Promise<{
40
+ success: boolean;
41
+ txHash?: string;
42
+ error?: string;
43
+ }>;
44
+ /**
45
+ * Pre-authorizes a task consumer to leave feedback.
46
+ */
47
+ authorizeFeedback(consumerAddress: string, expiration: number): Promise<{
48
+ success: boolean;
49
+ signature?: string;
50
+ error?: string;
51
+ }>;
52
+ }
@@ -0,0 +1,120 @@
1
+ import { encodeFunctionData } from "viem";
2
+ const IDENTITY_ABI = [
3
+ { type: "function", name: "register", stateMutability: "nonpayable", inputs: [{ name: "agentURI", type: "string" }], outputs: [{ name: "agentId", type: "uint256" }] },
4
+ { type: "function", name: "tokenURI", stateMutability: "view", inputs: [{ name: "tokenId", type: "uint256" }], outputs: [{ name: "", type: "string" }] },
5
+ { type: "function", name: "getAgentWallet", stateMutability: "view", inputs: [{ name: "agentId", type: "uint256" }], outputs: [{ name: "", type: "address" }] },
6
+ ];
7
+ const REPUTATION_ABI = [
8
+ {
9
+ type: "function",
10
+ name: "giveFeedback",
11
+ stateMutability: "nonpayable",
12
+ inputs: [
13
+ { name: "agentId", type: "uint256" },
14
+ { name: "value", type: "int128" },
15
+ { name: "valueDecimals", type: "uint8" },
16
+ { name: "tag1", type: "string" },
17
+ { name: "tag2", type: "string" },
18
+ { name: "endpoint", type: "string" },
19
+ { name: "feedbackURI", type: "string" },
20
+ { name: "feedbackHash", type: "bytes32" },
21
+ ],
22
+ outputs: [],
23
+ },
24
+ ];
25
+ /**
26
+ * Hooks for ERC-8004 Identity, Reputation, and Validation registries.
27
+ */
28
+ export class IdentityManager {
29
+ wallet;
30
+ sxt;
31
+ registries;
32
+ constructor(wallet, sxt, registries) {
33
+ this.wallet = wallet;
34
+ this.sxt = sxt;
35
+ this.registries = registries;
36
+ }
37
+ setRegistries(registries) {
38
+ this.registries = registries;
39
+ }
40
+ /**
41
+ * Registers a new Agent Identity on the ERC-8004 Identity Registry.
42
+ */
43
+ async register(agentURI, donSignature) {
44
+ try {
45
+ const data = encodeFunctionData({
46
+ abi: IDENTITY_ABI,
47
+ functionName: "register",
48
+ args: [agentURI],
49
+ });
50
+ return await this.wallet.sendContractCallAuthorized({ to: this.registries.identityRegistry, data }, donSignature);
51
+ }
52
+ catch (e) {
53
+ return { success: false, error: e.message };
54
+ }
55
+ }
56
+ /**
57
+ * Fetches the agent's core metadata URI from the Identity Registry.
58
+ */
59
+ async getIdentity(agentId) {
60
+ const client = this.wallet.getPublicClient();
61
+ const metadataUri = await client.readContract({
62
+ address: this.registries.identityRegistry,
63
+ abi: IDENTITY_ABI,
64
+ functionName: "tokenURI",
65
+ args: [agentId],
66
+ });
67
+ const verifiedWallet = await client.readContract({
68
+ address: this.registries.identityRegistry,
69
+ abi: IDENTITY_ABI,
70
+ functionName: "getAgentWallet",
71
+ args: [agentId],
72
+ });
73
+ return { metadataUri, verifiedWallet };
74
+ }
75
+ /**
76
+ * Fetches the agent's verified, ZK-proven reputation score from SXT and the Reputation Registry.
77
+ */
78
+ async getReputation(agentId) {
79
+ return this.sxt.getAgentReputation(agentId);
80
+ }
81
+ /**
82
+ * Commits an on-chain trust feedback score for another agent on the Reputation Registry.
83
+ */
84
+ async giveFeedback(input, donSignature) {
85
+ try {
86
+ const data = encodeFunctionData({
87
+ abi: REPUTATION_ABI,
88
+ functionName: "giveFeedback",
89
+ args: [
90
+ input.agentId,
91
+ input.value,
92
+ input.valueDecimals,
93
+ input.tag1 ?? "",
94
+ input.tag2 ?? "",
95
+ input.endpoint ?? "",
96
+ input.feedbackURI ?? "",
97
+ input.feedbackHash ??
98
+ "0x0000000000000000000000000000000000000000000000000000000000000000",
99
+ ],
100
+ });
101
+ return await this.wallet.sendContractCallAuthorized({ to: this.registries.reputationRegistry, data }, donSignature);
102
+ }
103
+ catch (e) {
104
+ return { success: false, error: e.message };
105
+ }
106
+ }
107
+ /**
108
+ * Pre-authorizes a task consumer to leave feedback.
109
+ */
110
+ async authorizeFeedback(consumerAddress, expiration) {
111
+ try {
112
+ console.log(`[ERC-8004] Generating off-chain feedbackAuth signature for consumer: ${consumerAddress} (Expires: ${expiration})`);
113
+ const mockSignature = "0xerc8004_auth_sig_" + Date.now().toString(16);
114
+ return { success: true, signature: mockSignature };
115
+ }
116
+ catch (e) {
117
+ return { success: false, error: e.message };
118
+ }
119
+ }
120
+ }
@@ -0,0 +1,15 @@
1
+ export interface ERC8004RegistryConfig {
2
+ identityRegistry: `0x${string}`;
3
+ reputationRegistry: `0x${string}`;
4
+ validationRegistry?: `0x${string}`;
5
+ }
6
+ export interface ERC8004FeedbackInput {
7
+ agentId: bigint;
8
+ value: bigint;
9
+ valueDecimals: number;
10
+ tag1?: string;
11
+ tag2?: string;
12
+ endpoint?: string;
13
+ feedbackURI?: string;
14
+ feedbackHash?: `0x${string}`;
15
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,9 @@
1
+ import type { FacilitatorConfig, PaymentPayload, PaymentRequirements, SettleResponse, VerifyResponse } from "./x402Types.js";
2
+ export declare class FacilitatorClient {
3
+ private readonly cfg;
4
+ private readonly baseUrl;
5
+ constructor(cfg: FacilitatorConfig);
6
+ private postJson;
7
+ verify(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<VerifyResponse>;
8
+ settle(paymentPayload: PaymentPayload, requirements: PaymentRequirements): Promise<SettleResponse>;
9
+ }
@@ -0,0 +1,106 @@
1
+ import { fetchWithRetry } from "../../http/fetchWithRetry.js";
2
+ const DEFAULT_TIMEOUT_MS = 45_000;
3
+ const DEFAULT_RETRIES = 3;
4
+ const DEFAULT_RETRY_DELAY_MS = 400;
5
+ function normalizeBaseUrl(baseUrl) {
6
+ if (!baseUrl.startsWith("http://") && !baseUrl.startsWith("https://")) {
7
+ throw new Error(`x402 Facilitator: invalid baseUrl (must include protocol): ${baseUrl}`);
8
+ }
9
+ return baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
10
+ }
11
+ function toWirePaymentPayload(payload) {
12
+ return {
13
+ token: payload.token,
14
+ payload: {
15
+ authorization: {
16
+ ...payload.payload.authorization,
17
+ value: payload.payload.authorization.value.toString(),
18
+ validAfter: String(payload.payload.authorization.validAfter),
19
+ validBefore: String(payload.payload.authorization.validBefore),
20
+ },
21
+ signature: payload.payload.signature,
22
+ },
23
+ };
24
+ }
25
+ export class FacilitatorClient {
26
+ cfg;
27
+ baseUrl;
28
+ constructor(cfg) {
29
+ this.cfg = cfg;
30
+ this.baseUrl = normalizeBaseUrl(cfg.baseUrl);
31
+ }
32
+ async postJson(path, body) {
33
+ const controller = new AbortController();
34
+ const timeoutMs = this.cfg.requestTimeoutMs ?? DEFAULT_TIMEOUT_MS;
35
+ const t = setTimeout(() => controller.abort(), timeoutMs);
36
+ try {
37
+ const res = await fetchWithRetry(`${this.baseUrl}${path}`, {
38
+ method: "POST",
39
+ signal: controller.signal,
40
+ headers: {
41
+ "content-type": "application/json",
42
+ ...(this.cfg.apiKey ? { Authorization: `Bearer ${this.cfg.apiKey}` } : {}),
43
+ },
44
+ body: JSON.stringify(body),
45
+ }, {
46
+ maxRetries: this.cfg.maxRetries ?? DEFAULT_RETRIES,
47
+ baseDelayMs: this.cfg.retryBaseDelayMs ?? DEFAULT_RETRY_DELAY_MS,
48
+ signal: controller.signal,
49
+ retryOnRateLimit: true,
50
+ });
51
+ const txt = await res.text();
52
+ let json = {};
53
+ try {
54
+ json = txt ? JSON.parse(txt) : {};
55
+ }
56
+ catch {
57
+ throw new Error(`x402 Facilitator: non-JSON response (${res.status})`);
58
+ }
59
+ if (!res.ok) {
60
+ throw new Error(`x402 Facilitator: HTTP ${res.status}`);
61
+ }
62
+ return json;
63
+ }
64
+ finally {
65
+ clearTimeout(t);
66
+ }
67
+ }
68
+ async verify(paymentPayload, requirements) {
69
+ const body = {
70
+ paymentPayload: toWirePaymentPayload(paymentPayload),
71
+ paymentRequirements: {
72
+ scheme: requirements.scheme,
73
+ network: requirements.network,
74
+ asset: requirements.asset,
75
+ payTo: requirements.payTo,
76
+ maxAmountRequired: requirements.maxAmountRequired,
77
+ },
78
+ };
79
+ const raw = await this.postJson("/verify", body);
80
+ return {
81
+ success: !!raw.success,
82
+ verified: raw.verified ?? raw.isValid ?? raw.is_valid,
83
+ recoveredAddress: raw.recoveredAddress ?? raw.payer,
84
+ error: raw.error,
85
+ };
86
+ }
87
+ async settle(paymentPayload, requirements) {
88
+ const body = {
89
+ paymentPayload: toWirePaymentPayload(paymentPayload),
90
+ paymentRequirements: {
91
+ scheme: requirements.scheme,
92
+ network: requirements.network,
93
+ asset: requirements.asset,
94
+ payTo: requirements.payTo,
95
+ maxAmountRequired: requirements.maxAmountRequired,
96
+ },
97
+ };
98
+ const raw = await this.postJson("/settle", body);
99
+ return {
100
+ success: !!raw.success,
101
+ txHash: raw.txHash ?? raw.transactionHash ?? raw.transaction,
102
+ status: raw.status,
103
+ error: raw.error,
104
+ };
105
+ }
106
+ }
@@ -0,0 +1,25 @@
1
+ import { GaslessWalletProvider } from "../../wallet/GaslessWalletProvider.js";
2
+ import type { FacilitatorConfig } from "./x402Types.js";
3
+ /**
4
+ * Handles agent-to-agent HTTP-native micro-payments via the x402 standard.
5
+ */
6
+ export declare class X402PaymentHandler {
7
+ private readonly wallet;
8
+ private readonly facilitator;
9
+ constructor(wallet: GaslessWalletProvider, cfg?: FacilitatorConfig);
10
+ /**
11
+ * Executes an x402 payment flow against `x402.0xgasless.com` facilitator:
12
+ * - request target
13
+ * - if 402, read `paymentRequirements` JSON from response
14
+ * - sign EIP-712 TransferWithAuthorization
15
+ * - verify + settle via facilitator
16
+ * - retry request with `x402-payment: <txHash>`
17
+ */
18
+ performPayment(targetApiUrl: string, amount: string): Promise<{
19
+ success: boolean;
20
+ error?: string;
21
+ token?: string;
22
+ }>;
23
+ private createPaymentPayload;
24
+ private randomBytes32Hex;
25
+ }
@@ -0,0 +1,139 @@
1
+ import { FacilitatorClient } from "./FacilitatorClient.js";
2
+ // EIP-712 domains of the EIP-3009 tokens the 0xGasless facilitator settles.
3
+ // Verified against each token's DOMAIN_SEPARATOR (XSGD exposes none: its
4
+ // domain comes from the token source). Key: `${chainId}:${lowercase address}`.
5
+ const KNOWN_EIP3009_DOMAINS = {
6
+ "43114:0xb97ef9ef8734c71904d8002f8b6bc66dd9c48a6e": { name: "USD Coin", version: "2" }, // USDC Avalanche
7
+ "43113:0x5425890298aed601595a70ab815c96711a31bc65": { name: "USD Coin", version: "2" }, // USDC Fuji
8
+ "43114:0xb2f85b7ab3c2b6f62df06de6ae7d09c010a5096e": { name: "XSGD", version: "2" }, // XSGD Avalanche
9
+ "43113:0xd769410dc8772695a7f55a304d2125320a65c2a5": { name: "XSGD", version: "2" }, // XSGD Fuji
10
+ };
11
+ /**
12
+ * Handles agent-to-agent HTTP-native micro-payments via the x402 standard.
13
+ */
14
+ export class X402PaymentHandler {
15
+ wallet;
16
+ facilitator;
17
+ constructor(wallet, cfg = { baseUrl: "https://x402.0xgasless.com" }) {
18
+ this.wallet = wallet;
19
+ this.facilitator = new FacilitatorClient(cfg);
20
+ }
21
+ /**
22
+ * Executes an x402 payment flow against `x402.0xgasless.com` facilitator:
23
+ * - request target
24
+ * - if 402, read `paymentRequirements` JSON from response
25
+ * - sign EIP-712 TransferWithAuthorization
26
+ * - verify + settle via facilitator
27
+ * - retry request with `x402-payment: <txHash>`
28
+ */
29
+ async performPayment(targetApiUrl, amount) {
30
+ try {
31
+ const first = await fetch(targetApiUrl, { method: "GET" });
32
+ if (first.status !== 402) {
33
+ // If endpoint didn’t require payment, treat as success and return empty token.
34
+ return { success: true, token: "" };
35
+ }
36
+ let requirements;
37
+ try {
38
+ const body = (await first.json());
39
+ requirements = body?.paymentRequirements || body?.requirements;
40
+ }
41
+ catch { }
42
+ if (!requirements) {
43
+ return { success: false, error: "x402: 402 received but no paymentRequirements provided by server" };
44
+ }
45
+ // Enforce caller-provided amount doesn’t exceed requirement (best-effort).
46
+ if (amount && /^\d+$/.test(amount) && /^\d+$/.test(String(requirements.maxAmountRequired))) {
47
+ if (BigInt(amount) > BigInt(requirements.maxAmountRequired)) {
48
+ return { success: false, error: "x402: requested amount exceeds server maxAmountRequired" };
49
+ }
50
+ }
51
+ const paymentPayload = await this.createPaymentPayload(requirements);
52
+ const verify = await this.facilitator.verify(paymentPayload, requirements);
53
+ if (!verify.success || verify.verified === false) {
54
+ return { success: false, error: `x402 verify failed: ${verify.error || "invalid"}` };
55
+ }
56
+ const settle = await this.facilitator.settle(paymentPayload, requirements);
57
+ if (!settle.success || !settle.txHash) {
58
+ return { success: false, error: `x402 settle failed: ${settle.error || "unknown"}` };
59
+ }
60
+ const headers = new Headers();
61
+ headers.set("x402-payment", settle.txHash);
62
+ // Retry original request with proof of payment header.
63
+ await fetch(targetApiUrl, { method: "GET", headers });
64
+ return { success: true, token: settle.txHash };
65
+ }
66
+ catch (e) {
67
+ return { success: false, error: e.message };
68
+ }
69
+ }
70
+ async createPaymentPayload(requirements) {
71
+ const now = Math.floor(Date.now() / 1000);
72
+ const validBefore = now + Number(requirements.maxTimeoutSeconds || 3600);
73
+ const nonce = this.randomBytes32Hex();
74
+ const from = (await this.wallet.getAddress());
75
+ const authorization = {
76
+ from,
77
+ to: requirements.payTo,
78
+ value: String(requirements.maxAmountRequired),
79
+ validAfter: 0,
80
+ validBefore,
81
+ nonce,
82
+ };
83
+ // Sign under the TOKEN's own EIP-3009 domain (USDC/XSGD settle on the
84
+ // token itself). The old "A402" relayer domain is retired: its signed
85
+ // message did not include the token, so it could be settled against a
86
+ // different token.
87
+ const chainId = await this.wallet.getChainId();
88
+ const tokenDomain = requirements.extra?.name && requirements.extra?.version
89
+ ? { name: requirements.extra.name, version: requirements.extra.version }
90
+ : KNOWN_EIP3009_DOMAINS[`${chainId}:${requirements.asset.toLowerCase()}`];
91
+ if (!tokenDomain) {
92
+ throw new Error(`x402: unknown EIP-712 domain for token ${requirements.asset} on chain ${chainId}. ` +
93
+ 'Pass requirements.extra = { name, version } (the seller\'s 402 response includes it).');
94
+ }
95
+ const domain = {
96
+ name: tokenDomain.name,
97
+ version: tokenDomain.version,
98
+ chainId,
99
+ verifyingContract: requirements.asset,
100
+ };
101
+ const types = {
102
+ TransferWithAuthorization: [
103
+ { name: "from", type: "address" },
104
+ { name: "to", type: "address" },
105
+ { name: "value", type: "uint256" },
106
+ { name: "validAfter", type: "uint256" },
107
+ { name: "validBefore", type: "uint256" },
108
+ { name: "nonce", type: "bytes32" },
109
+ ],
110
+ };
111
+ const signature = (await this.wallet.signTypedData({
112
+ account: from,
113
+ domain: domain,
114
+ types: types,
115
+ primaryType: "TransferWithAuthorization",
116
+ message: {
117
+ from: authorization.from,
118
+ to: authorization.to,
119
+ value: BigInt(authorization.value),
120
+ validAfter: BigInt(authorization.validAfter),
121
+ validBefore: BigInt(authorization.validBefore),
122
+ nonce: authorization.nonce,
123
+ },
124
+ }));
125
+ return {
126
+ token: requirements.asset,
127
+ payload: { authorization, signature },
128
+ };
129
+ }
130
+ randomBytes32Hex() {
131
+ const cryptoObj = globalThis.crypto;
132
+ if (!cryptoObj?.getRandomValues) {
133
+ throw new Error("x402: crypto.getRandomValues is required to generate nonce");
134
+ }
135
+ const buf = new Uint8Array(32);
136
+ cryptoObj.getRandomValues(buf);
137
+ return ("0x" + Array.from(buf).map((b) => b.toString(16).padStart(2, "0")).join(""));
138
+ }
139
+ }
@@ -0,0 +1,52 @@
1
+ export type X402Network = string;
2
+ export interface PaymentRequirements {
3
+ scheme: "exact";
4
+ network: X402Network;
5
+ asset: `0x${string}`;
6
+ payTo: `0x${string}`;
7
+ maxAmountRequired: string;
8
+ maxTimeoutSeconds: number;
9
+ /** EIP-712 domain of the token (x402 `extra`). Known tokens (USDC, XSGD) are filled in automatically. */
10
+ extra?: {
11
+ name?: string;
12
+ version?: string;
13
+ };
14
+ /** @deprecated The A402 relayer is retired (its signed message lacked the token). Ignored. */
15
+ relayerContract?: `0x${string}`;
16
+ description?: string;
17
+ resource?: string;
18
+ }
19
+ export interface Authorization {
20
+ from: `0x${string}`;
21
+ to: `0x${string}`;
22
+ value: string;
23
+ validAfter: number;
24
+ validBefore: number;
25
+ nonce: `0x${string}`;
26
+ }
27
+ export interface PaymentPayload {
28
+ token: `0x${string}`;
29
+ payload: {
30
+ authorization: Authorization;
31
+ signature: `0x${string}`;
32
+ };
33
+ }
34
+ export interface VerifyResponse {
35
+ success: boolean;
36
+ verified?: boolean;
37
+ recoveredAddress?: `0x${string}`;
38
+ error?: string;
39
+ }
40
+ export interface SettleResponse {
41
+ success: boolean;
42
+ txHash?: `0x${string}`;
43
+ status?: string;
44
+ error?: string;
45
+ }
46
+ export interface FacilitatorConfig {
47
+ baseUrl: string;
48
+ apiKey?: string;
49
+ requestTimeoutMs?: number;
50
+ maxRetries?: number;
51
+ retryBaseDelayMs?: number;
52
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,12 @@
1
+ import { z } from "zod";
2
+ /**
3
+ * Centralized security validation module.
4
+ * Prevents vulnerabilities caused by falling back to raw inputs when schemas fail.
5
+ */
6
+ export declare class ValidationGate {
7
+ /**
8
+ * Strictly validates input against a Zod schema.
9
+ * Throws an error immediately on failure, actively preventing execution of hallucinated or injected prompts.
10
+ */
11
+ static validate<T>(schema: z.ZodType<T>, data: unknown): T;
12
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Centralized security validation module.
3
+ * Prevents vulnerabilities caused by falling back to raw inputs when schemas fail.
4
+ */
5
+ export class ValidationGate {
6
+ /**
7
+ * Strictly validates input against a Zod schema.
8
+ * Throws an error immediately on failure, actively preventing execution of hallucinated or injected prompts.
9
+ */
10
+ static validate(schema, data) {
11
+ // `.parse()` throws ZodError on failure, avoiding the silent fallback problem identified in legacy agentkit
12
+ return schema.parse(data);
13
+ }
14
+ }
@@ -0,0 +1,30 @@
1
+ import type { SXTQueryConfig } from "./sxtTypes.js";
2
+ /**
3
+ * Integrates Space and Time (SXT) Proof of SQL via DQL over indexed ERC-20 transfer data.
4
+ * Uses REST `POST /v1/sql/dql` with bearer auth, matching the platform’s SQL API surface.
5
+ *
6
+ * @see https://docs.spaceandtime.io/docs/javascript-sdk
7
+ */
8
+ export declare class SXTQueryProvider {
9
+ private readonly cfg;
10
+ constructor(cfg: SXTQueryConfig);
11
+ /** Exposes effective config for enterprise guardrails. */
12
+ get config(): Readonly<SXTQueryConfig>;
13
+ private postDql;
14
+ private defaultSpendingSql;
15
+ /**
16
+ * Proof-of-SQL bounded spending from indexed ERC-20 transfers (recipient = agent wallet).
17
+ */
18
+ getAgentSpendingHistory(agentId: string, timeframeHours: number): Promise<{
19
+ total: bigint;
20
+ proof: string;
21
+ }>;
22
+ /**
23
+ * Application-specific reputation aggregate; requires `reputationTableFqn` or `buildReputationSql`.
24
+ */
25
+ getAgentReputation(agentId: string): Promise<{
26
+ score: number;
27
+ count: number;
28
+ proof: string;
29
+ }>;
30
+ }