@sparkysolutions/agentrail 0.0.0-stage → 0.1.1
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 +21 -0
- package/README.md +249 -3
- package/dist/cli/mcp-stdio.d.ts +8 -0
- package/dist/cli/mcp-stdio.js +454 -0
- package/dist/cli/pipeline.d.ts +40 -0
- package/dist/cli/pipeline.js +114 -0
- package/dist/cli/sandbox.d.ts +55 -0
- package/dist/cli/sandbox.js +107 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.js +39 -0
- package/dist/lib/agent-badge-issuer.d.ts +36 -0
- package/dist/lib/agent-badge-issuer.js +166 -0
- package/dist/lib/agent-registry.d.ts +136 -0
- package/dist/lib/agent-registry.js +124 -0
- package/dist/lib/agenthustle-pipeline.d.ts +68 -0
- package/dist/lib/agenthustle-pipeline.js +143 -0
- package/dist/lib/agentpass-pipeline.d.ts +44 -0
- package/dist/lib/agentpass-pipeline.js +84 -0
- package/dist/lib/audit-trail-provider.d.ts +24 -0
- package/dist/lib/audit-trail-provider.js +60 -0
- package/dist/lib/axis-clob-provider.d.ts +50 -0
- package/dist/lib/axis-clob-provider.js +150 -0
- package/dist/lib/circuit-breaker.d.ts +60 -0
- package/dist/lib/circuit-breaker.js +136 -0
- package/dist/lib/conditional-escrow.d.ts +42 -0
- package/dist/lib/conditional-escrow.js +126 -0
- package/dist/lib/mcp-server.d.ts +29 -0
- package/dist/lib/mcp-server.js +165 -0
- package/dist/lib/micro-stream.d.ts +21 -0
- package/dist/lib/micro-stream.js +41 -0
- package/dist/lib/proof-of-task.d.ts +12 -0
- package/dist/lib/proof-of-task.js +32 -0
- package/dist/lib/receipts.d.ts +153 -0
- package/dist/lib/receipts.js +173 -0
- package/dist/lib/reflector-oracle-adapter.d.ts +44 -0
- package/dist/lib/reflector-oracle-adapter.js +173 -0
- package/dist/lib/scoped-allowance.d.ts +15 -0
- package/dist/lib/scoped-allowance.js +116 -0
- package/dist/lib/ttl-keeper.d.ts +10 -0
- package/dist/lib/ttl-keeper.js +36 -0
- package/dist/lib/universal-adapters.d.ts +42 -0
- package/dist/lib/universal-adapters.js +69 -0
- package/dist/lib/x402-gateway.d.ts +86 -0
- package/dist/lib/x402-gateway.js +128 -0
- package/dist/lib/x402-pipeline.d.ts +51 -0
- package/dist/lib/x402-pipeline.js +105 -0
- package/dist/sdk/agent-client.d.ts +26 -0
- package/dist/sdk/agent-client.js +53 -0
- package/dist/types.d.ts +181 -0
- package/dist/types.js +5 -0
- package/glama.json +12 -0
- package/package.json +56 -6
- package/smithery.json +43 -0
- package/smithery.yaml +29 -0
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
import { SpendRequest, SpendResult } from "../types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Opt-in public receipts for AgentRail spends and proof-of-task results.
|
|
5
|
+
*
|
|
6
|
+
* Build a canonical record, hash it, and anchor only the SHA-256 hash to a public
|
|
7
|
+
* Audit Trail node through an injected provider. The record itself never leaves
|
|
8
|
+
* the caller. Anchoring sits outside the payment path: `anchorReceipt` never throws,
|
|
9
|
+
* so a spend or a proof is unaffected when anchoring fails.
|
|
10
|
+
*/
|
|
11
|
+
export declare const RECEIPT_VERSION = "agentrail-receipt-v1";
|
|
12
|
+
export declare const RECEIPT_VERIFY_URL = "https://nirium.xyz/verify";
|
|
13
|
+
export declare const SpendReceiptSchema: z.ZodObject<{
|
|
14
|
+
kind: z.ZodLiteral<"spend">;
|
|
15
|
+
version: z.ZodLiteral<"agentrail-receipt-v1">;
|
|
16
|
+
contractId: z.ZodString;
|
|
17
|
+
allowanceId: z.ZodString;
|
|
18
|
+
agentPublicKey: z.ZodString;
|
|
19
|
+
destination: z.ZodEffects<z.ZodString, string, string>;
|
|
20
|
+
amountStroops: z.ZodBigInt;
|
|
21
|
+
feeStroops: z.ZodBigInt;
|
|
22
|
+
netStroops: z.ZodBigInt;
|
|
23
|
+
timestamp: z.ZodNumber;
|
|
24
|
+
txHash: z.ZodOptional<z.ZodString>;
|
|
25
|
+
}, "strip", z.ZodTypeAny, {
|
|
26
|
+
kind: "spend";
|
|
27
|
+
version: "agentrail-receipt-v1";
|
|
28
|
+
contractId: string;
|
|
29
|
+
allowanceId: string;
|
|
30
|
+
agentPublicKey: string;
|
|
31
|
+
destination: string;
|
|
32
|
+
amountStroops: bigint;
|
|
33
|
+
feeStroops: bigint;
|
|
34
|
+
netStroops: bigint;
|
|
35
|
+
timestamp: number;
|
|
36
|
+
txHash?: string | undefined;
|
|
37
|
+
}, {
|
|
38
|
+
kind: "spend";
|
|
39
|
+
version: "agentrail-receipt-v1";
|
|
40
|
+
contractId: string;
|
|
41
|
+
allowanceId: string;
|
|
42
|
+
agentPublicKey: string;
|
|
43
|
+
destination: string;
|
|
44
|
+
amountStroops: bigint;
|
|
45
|
+
feeStroops: bigint;
|
|
46
|
+
netStroops: bigint;
|
|
47
|
+
timestamp: number;
|
|
48
|
+
txHash?: string | undefined;
|
|
49
|
+
}>;
|
|
50
|
+
export declare const TaskProofReceiptSchema: z.ZodObject<{
|
|
51
|
+
kind: z.ZodLiteral<"proof-of-task">;
|
|
52
|
+
version: z.ZodLiteral<"agentrail-receipt-v1">;
|
|
53
|
+
taskId: z.ZodString;
|
|
54
|
+
agentWorkerPublicKey: z.ZodString;
|
|
55
|
+
taskCommitmentHash: z.ZodString;
|
|
56
|
+
verified: z.ZodBoolean;
|
|
57
|
+
reason: z.ZodOptional<z.ZodString>;
|
|
58
|
+
timestamp: z.ZodNumber;
|
|
59
|
+
}, "strip", z.ZodTypeAny, {
|
|
60
|
+
kind: "proof-of-task";
|
|
61
|
+
version: "agentrail-receipt-v1";
|
|
62
|
+
timestamp: number;
|
|
63
|
+
taskId: string;
|
|
64
|
+
agentWorkerPublicKey: string;
|
|
65
|
+
taskCommitmentHash: string;
|
|
66
|
+
verified: boolean;
|
|
67
|
+
reason?: string | undefined;
|
|
68
|
+
}, {
|
|
69
|
+
kind: "proof-of-task";
|
|
70
|
+
version: "agentrail-receipt-v1";
|
|
71
|
+
timestamp: number;
|
|
72
|
+
taskId: string;
|
|
73
|
+
agentWorkerPublicKey: string;
|
|
74
|
+
taskCommitmentHash: string;
|
|
75
|
+
verified: boolean;
|
|
76
|
+
reason?: string | undefined;
|
|
77
|
+
}>;
|
|
78
|
+
export type SpendReceipt = z.infer<typeof SpendReceiptSchema>;
|
|
79
|
+
export type TaskProofReceipt = z.infer<typeof TaskProofReceiptSchema>;
|
|
80
|
+
export type Receipt = SpendReceipt | TaskProofReceipt;
|
|
81
|
+
/**
|
|
82
|
+
* Build a spend receipt from a successful `verifyAndDeductSpend` result.
|
|
83
|
+
* Throws if the spend was rejected (there is nothing to attest) or an input is invalid.
|
|
84
|
+
*/
|
|
85
|
+
export declare function buildSpendReceipt(request: SpendRequest, result: SpendResult, extras: {
|
|
86
|
+
contractId: string;
|
|
87
|
+
txHash?: string;
|
|
88
|
+
}): SpendReceipt;
|
|
89
|
+
/**
|
|
90
|
+
* Build a proof-of-task receipt from the output of `verifyTaskProof`.
|
|
91
|
+
* Records the commitment hash and the verification result, never the raw output or nonce.
|
|
92
|
+
*/
|
|
93
|
+
export declare function buildTaskProofReceipt(input: {
|
|
94
|
+
taskId: string;
|
|
95
|
+
agentWorkerPublicKey: string;
|
|
96
|
+
taskCommitmentHash: string;
|
|
97
|
+
verification: {
|
|
98
|
+
ok: boolean;
|
|
99
|
+
reason?: string;
|
|
100
|
+
};
|
|
101
|
+
timestamp: number;
|
|
102
|
+
}): TaskProofReceipt;
|
|
103
|
+
/** Deterministic JSON: sorted keys, bigint as a decimal string, undefined fields dropped. */
|
|
104
|
+
export declare function canonicalizeReceipt(receipt: Receipt): string;
|
|
105
|
+
/** SHA-256 hex of the canonical receipt. This is the only value that leaves AgentRail. */
|
|
106
|
+
export declare function hashReceipt(receipt: Receipt): string;
|
|
107
|
+
/** A service that anchors a sha-256 hash and returns a content id (see `createAuditTrailProvider`). */
|
|
108
|
+
export interface ReceiptAnchorProvider {
|
|
109
|
+
anchor(request: {
|
|
110
|
+
hash: string;
|
|
111
|
+
tag?: string;
|
|
112
|
+
txHash?: string;
|
|
113
|
+
network?: string;
|
|
114
|
+
agent?: {
|
|
115
|
+
id?: string;
|
|
116
|
+
key: string;
|
|
117
|
+
signature: string;
|
|
118
|
+
};
|
|
119
|
+
}): Promise<{
|
|
120
|
+
cid: string;
|
|
121
|
+
contentSha256: string;
|
|
122
|
+
gatewayUrl?: string;
|
|
123
|
+
anchoredAt?: string;
|
|
124
|
+
attestedBy?: string;
|
|
125
|
+
}>;
|
|
126
|
+
}
|
|
127
|
+
export type AnchorOutcome = {
|
|
128
|
+
ok: true;
|
|
129
|
+
cid: string;
|
|
130
|
+
contentSha256: string;
|
|
131
|
+
verifyUrl: string;
|
|
132
|
+
gatewayUrl?: string;
|
|
133
|
+
anchoredAt?: string;
|
|
134
|
+
attestedBy?: string;
|
|
135
|
+
} | {
|
|
136
|
+
ok: false;
|
|
137
|
+
contentSha256: string;
|
|
138
|
+
error: string;
|
|
139
|
+
};
|
|
140
|
+
export interface AnchorOptions {
|
|
141
|
+
tag?: string;
|
|
142
|
+
network?: string;
|
|
143
|
+
agentId?: string;
|
|
144
|
+
signerKeypair?: {
|
|
145
|
+
publicKey(): string;
|
|
146
|
+
sign(data: Buffer): Buffer;
|
|
147
|
+
};
|
|
148
|
+
}
|
|
149
|
+
/**
|
|
150
|
+
* Anchor a receipt's hash through `provider`. Never throws: a failure comes back as
|
|
151
|
+
* `{ ok: false }` so callers can log it and carry on.
|
|
152
|
+
*/
|
|
153
|
+
export declare function anchorReceipt(receipt: Receipt, provider: ReceiptAnchorProvider, options?: AnchorOptions): Promise<AnchorOutcome>;
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.TaskProofReceiptSchema = exports.SpendReceiptSchema = exports.RECEIPT_VERIFY_URL = exports.RECEIPT_VERSION = void 0;
|
|
4
|
+
exports.buildSpendReceipt = buildSpendReceipt;
|
|
5
|
+
exports.buildTaskProofReceipt = buildTaskProofReceipt;
|
|
6
|
+
exports.canonicalizeReceipt = canonicalizeReceipt;
|
|
7
|
+
exports.hashReceipt = hashReceipt;
|
|
8
|
+
exports.anchorReceipt = anchorReceipt;
|
|
9
|
+
const node_crypto_1 = require("node:crypto");
|
|
10
|
+
const zod_1 = require("zod");
|
|
11
|
+
/**
|
|
12
|
+
* Opt-in public receipts for AgentRail spends and proof-of-task results.
|
|
13
|
+
*
|
|
14
|
+
* Build a canonical record, hash it, and anchor only the SHA-256 hash to a public
|
|
15
|
+
* Audit Trail node through an injected provider. The record itself never leaves
|
|
16
|
+
* the caller. Anchoring sits outside the payment path: `anchorReceipt` never throws,
|
|
17
|
+
* so a spend or a proof is unaffected when anchoring fails.
|
|
18
|
+
*/
|
|
19
|
+
exports.RECEIPT_VERSION = "agentrail-receipt-v1";
|
|
20
|
+
exports.RECEIPT_VERIFY_URL = "https://nirium.xyz/verify";
|
|
21
|
+
const HEX64 = /^[0-9a-f]{64}$/;
|
|
22
|
+
const STELLAR_ACCOUNT = /^G[A-Z2-7]{55}$/;
|
|
23
|
+
const STELLAR_CONTRACT = /^C[A-Z2-7]{55}$/;
|
|
24
|
+
const accountOrContract = zod_1.z
|
|
25
|
+
.string()
|
|
26
|
+
.refine((v) => STELLAR_ACCOUNT.test(v) || STELLAR_CONTRACT.test(v), "must be a Stellar G... account or C... contract id");
|
|
27
|
+
const hex64 = zod_1.z.string().toLowerCase().regex(HEX64, "must be a 64-char sha-256 hex");
|
|
28
|
+
const stroops = zod_1.z.bigint().nonnegative();
|
|
29
|
+
const unixSeconds = zod_1.z.number().int().nonnegative();
|
|
30
|
+
exports.SpendReceiptSchema = zod_1.z.object({
|
|
31
|
+
kind: zod_1.z.literal("spend"),
|
|
32
|
+
version: zod_1.z.literal(exports.RECEIPT_VERSION),
|
|
33
|
+
contractId: zod_1.z.string().regex(STELLAR_CONTRACT, "must be a C... contract id"),
|
|
34
|
+
allowanceId: zod_1.z.string().min(1).max(128),
|
|
35
|
+
agentPublicKey: zod_1.z.string().regex(STELLAR_ACCOUNT, "must be a G... account"),
|
|
36
|
+
destination: accountOrContract,
|
|
37
|
+
amountStroops: stroops,
|
|
38
|
+
feeStroops: stroops,
|
|
39
|
+
netStroops: stroops,
|
|
40
|
+
timestamp: unixSeconds,
|
|
41
|
+
txHash: hex64.optional(),
|
|
42
|
+
});
|
|
43
|
+
exports.TaskProofReceiptSchema = zod_1.z.object({
|
|
44
|
+
kind: zod_1.z.literal("proof-of-task"),
|
|
45
|
+
version: zod_1.z.literal(exports.RECEIPT_VERSION),
|
|
46
|
+
taskId: zod_1.z.string().min(1).max(128),
|
|
47
|
+
agentWorkerPublicKey: zod_1.z.string().regex(STELLAR_ACCOUNT, "must be a G... account"),
|
|
48
|
+
taskCommitmentHash: hex64,
|
|
49
|
+
verified: zod_1.z.boolean(),
|
|
50
|
+
reason: zod_1.z.string().max(256).optional(),
|
|
51
|
+
timestamp: unixSeconds,
|
|
52
|
+
});
|
|
53
|
+
const SpendExtrasSchema = zod_1.z.object({
|
|
54
|
+
contractId: zod_1.z.string(),
|
|
55
|
+
txHash: zod_1.z.string().optional(),
|
|
56
|
+
});
|
|
57
|
+
/**
|
|
58
|
+
* Build a spend receipt from a successful `verifyAndDeductSpend` result.
|
|
59
|
+
* Throws if the spend was rejected (there is nothing to attest) or an input is invalid.
|
|
60
|
+
*/
|
|
61
|
+
function buildSpendReceipt(request, result, extras) {
|
|
62
|
+
if (!result.ok) {
|
|
63
|
+
throw new Error(`Cannot build a receipt for a rejected spend (${result.code})`);
|
|
64
|
+
}
|
|
65
|
+
const { contractId, txHash } = SpendExtrasSchema.parse(extras);
|
|
66
|
+
return exports.SpendReceiptSchema.parse({
|
|
67
|
+
kind: "spend",
|
|
68
|
+
version: exports.RECEIPT_VERSION,
|
|
69
|
+
contractId,
|
|
70
|
+
allowanceId: request.allowanceId,
|
|
71
|
+
agentPublicKey: request.agentPublicKey,
|
|
72
|
+
destination: request.destination,
|
|
73
|
+
amountStroops: request.amountStroops,
|
|
74
|
+
feeStroops: result.feeStroops ?? 0n,
|
|
75
|
+
netStroops: result.netStroops ?? request.amountStroops,
|
|
76
|
+
timestamp: request.timestamp,
|
|
77
|
+
...(txHash !== undefined ? { txHash } : {}),
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
const TaskProofInputSchema = zod_1.z.object({
|
|
81
|
+
taskId: zod_1.z.string(),
|
|
82
|
+
agentWorkerPublicKey: zod_1.z.string(),
|
|
83
|
+
taskCommitmentHash: zod_1.z.string(),
|
|
84
|
+
verification: zod_1.z.object({ ok: zod_1.z.boolean(), reason: zod_1.z.string().optional() }),
|
|
85
|
+
timestamp: zod_1.z.number(),
|
|
86
|
+
});
|
|
87
|
+
/**
|
|
88
|
+
* Build a proof-of-task receipt from the output of `verifyTaskProof`.
|
|
89
|
+
* Records the commitment hash and the verification result, never the raw output or nonce.
|
|
90
|
+
*/
|
|
91
|
+
function buildTaskProofReceipt(input) {
|
|
92
|
+
const parsed = TaskProofInputSchema.parse(input);
|
|
93
|
+
return exports.TaskProofReceiptSchema.parse({
|
|
94
|
+
kind: "proof-of-task",
|
|
95
|
+
version: exports.RECEIPT_VERSION,
|
|
96
|
+
taskId: parsed.taskId,
|
|
97
|
+
agentWorkerPublicKey: parsed.agentWorkerPublicKey,
|
|
98
|
+
taskCommitmentHash: parsed.taskCommitmentHash,
|
|
99
|
+
verified: parsed.verification.ok,
|
|
100
|
+
...(parsed.verification.reason !== undefined ? { reason: parsed.verification.reason } : {}),
|
|
101
|
+
timestamp: parsed.timestamp,
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
function canonicalValue(value) {
|
|
105
|
+
if (typeof value === "bigint")
|
|
106
|
+
return value.toString();
|
|
107
|
+
if (Array.isArray(value))
|
|
108
|
+
return value.map(canonicalValue);
|
|
109
|
+
if (value !== null && typeof value === "object") {
|
|
110
|
+
const out = {};
|
|
111
|
+
for (const key of Object.keys(value).sort()) {
|
|
112
|
+
const v = value[key];
|
|
113
|
+
if (v !== undefined)
|
|
114
|
+
out[key] = canonicalValue(v);
|
|
115
|
+
}
|
|
116
|
+
return out;
|
|
117
|
+
}
|
|
118
|
+
return value;
|
|
119
|
+
}
|
|
120
|
+
/** Deterministic JSON: sorted keys, bigint as a decimal string, undefined fields dropped. */
|
|
121
|
+
function canonicalizeReceipt(receipt) {
|
|
122
|
+
return JSON.stringify(canonicalValue(receipt));
|
|
123
|
+
}
|
|
124
|
+
/** SHA-256 hex of the canonical receipt. This is the only value that leaves AgentRail. */
|
|
125
|
+
function hashReceipt(receipt) {
|
|
126
|
+
return (0, node_crypto_1.createHash)("sha256").update(canonicalizeReceipt(receipt), "utf8").digest("hex");
|
|
127
|
+
}
|
|
128
|
+
const TagSchema = zod_1.z.string().min(1).max(64).optional();
|
|
129
|
+
/**
|
|
130
|
+
* Anchor a receipt's hash through `provider`. Never throws: a failure comes back as
|
|
131
|
+
* `{ ok: false }` so callers can log it and carry on.
|
|
132
|
+
*/
|
|
133
|
+
async function anchorReceipt(receipt, provider, options = {}) {
|
|
134
|
+
let contentSha256 = "";
|
|
135
|
+
try {
|
|
136
|
+
const tag = TagSchema.parse(options.tag);
|
|
137
|
+
const valid = receipt.kind === "spend" ? exports.SpendReceiptSchema.parse(receipt) : exports.TaskProofReceiptSchema.parse(receipt);
|
|
138
|
+
contentSha256 = hashReceipt(valid);
|
|
139
|
+
const txHash = valid.kind === "spend" ? valid.txHash : undefined;
|
|
140
|
+
let agentPayload;
|
|
141
|
+
if (options.signerKeypair) {
|
|
142
|
+
const statement = Buffer.from(`nirium-audit-v1:${contentSha256}`, "utf8");
|
|
143
|
+
const signature = options.signerKeypair.sign(statement).toString("base64");
|
|
144
|
+
agentPayload = {
|
|
145
|
+
id: options.agentId ?? "agentrail",
|
|
146
|
+
key: options.signerKeypair.publicKey(),
|
|
147
|
+
signature,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
const res = await provider.anchor({
|
|
151
|
+
hash: contentSha256,
|
|
152
|
+
...(tag !== undefined ? { tag } : {}),
|
|
153
|
+
...(txHash !== undefined ? { txHash } : {}),
|
|
154
|
+
...(options.network !== undefined ? { network: options.network } : {}),
|
|
155
|
+
...(agentPayload !== undefined ? { agent: agentPayload } : {}),
|
|
156
|
+
});
|
|
157
|
+
if (res.contentSha256 !== contentSha256) {
|
|
158
|
+
return { ok: false, contentSha256, error: "Anchor returned a different content hash" };
|
|
159
|
+
}
|
|
160
|
+
return {
|
|
161
|
+
ok: true,
|
|
162
|
+
cid: res.cid,
|
|
163
|
+
contentSha256,
|
|
164
|
+
verifyUrl: `${exports.RECEIPT_VERIFY_URL}?cid=${encodeURIComponent(res.cid)}`,
|
|
165
|
+
...(res.gatewayUrl !== undefined ? { gatewayUrl: res.gatewayUrl } : {}),
|
|
166
|
+
...(res.anchoredAt !== undefined ? { anchoredAt: res.anchoredAt } : {}),
|
|
167
|
+
...(res.attestedBy !== undefined ? { attestedBy: res.attestedBy } : {}),
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
return { ok: false, contentSha256, error: err instanceof Error ? err.message : String(err) };
|
|
172
|
+
}
|
|
173
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AgentRail - Reflector Oracle Price Feed Adapter
|
|
3
|
+
*
|
|
4
|
+
* Provides verifiable real-time on-chain pricing feeds from Reflector Oracle
|
|
5
|
+
* on Stellar Soroban with dynamic staleness guards, multi-currency conversion,
|
|
6
|
+
* and automatic circuit-breaker triggers to protect AI agents from MEV/arbitrage front-running.
|
|
7
|
+
*/
|
|
8
|
+
import { ReflectorPriceFeed, ReflectorAdapterConfig, ReflectorValidationResult } from "../types.js";
|
|
9
|
+
export declare const DEFAULT_REFLECTOR_CONTRACT = "CAXQ2V55N6O3YF7DXHQB32MOGGOHQ75X46H6QYCYH4C45AWTQYYFLX7B";
|
|
10
|
+
export declare class ReflectorOracleAdapter {
|
|
11
|
+
private config;
|
|
12
|
+
private priceFeeds;
|
|
13
|
+
private circuitBreakers;
|
|
14
|
+
constructor(config?: ReflectorAdapterConfig);
|
|
15
|
+
private initializeDefaultFeeds;
|
|
16
|
+
/**
|
|
17
|
+
* Retrieves the latest verified price feed for an asset.
|
|
18
|
+
*/
|
|
19
|
+
getPrice(symbol: string): Promise<ReflectorPriceFeed>;
|
|
20
|
+
/**
|
|
21
|
+
* Validates a proposed execution price against the Reflector Oracle benchmark.
|
|
22
|
+
*/
|
|
23
|
+
validateTradePrice(symbol: string, proposedPriceUsd: number, customMaxDeviationPercent?: number): Promise<ReflectorValidationResult>;
|
|
24
|
+
/**
|
|
25
|
+
* Converts an amount from one asset to another using real-time oracle exchange rates.
|
|
26
|
+
*/
|
|
27
|
+
convertAmount(fromSymbol: string, toSymbol: string, amount: number): Promise<{
|
|
28
|
+
convertedAmount: number;
|
|
29
|
+
rate: number;
|
|
30
|
+
timestamp: number;
|
|
31
|
+
}>;
|
|
32
|
+
/**
|
|
33
|
+
* Updates or injects a live oracle price feed (e.g. from Horizon, Soroban RPC, or test harness).
|
|
34
|
+
*/
|
|
35
|
+
updatePriceFeed(symbol: string, priceUsd: number, timestamp?: number, ledgerSeq?: number): void;
|
|
36
|
+
/**
|
|
37
|
+
* Triggers an emergency circuit breaker on a specific asset feed.
|
|
38
|
+
*/
|
|
39
|
+
triggerCircuitBreaker(symbol: string, _reason?: string): void;
|
|
40
|
+
/**
|
|
41
|
+
* Resets an emergency circuit breaker once safety is confirmed.
|
|
42
|
+
*/
|
|
43
|
+
resetCircuitBreaker(symbol: string): void;
|
|
44
|
+
}
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* AgentRail - Reflector Oracle Price Feed Adapter
|
|
4
|
+
*
|
|
5
|
+
* Provides verifiable real-time on-chain pricing feeds from Reflector Oracle
|
|
6
|
+
* on Stellar Soroban with dynamic staleness guards, multi-currency conversion,
|
|
7
|
+
* and automatic circuit-breaker triggers to protect AI agents from MEV/arbitrage front-running.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.ReflectorOracleAdapter = exports.DEFAULT_REFLECTOR_CONTRACT = void 0;
|
|
11
|
+
exports.DEFAULT_REFLECTOR_CONTRACT = "CAXQ2V55N6O3YF7DXHQB32MOGGOHQ75X46H6QYCYH4C45AWTQYYFLX7B"; // Reflector Mainnet Contract
|
|
12
|
+
class ReflectorOracleAdapter {
|
|
13
|
+
config;
|
|
14
|
+
priceFeeds = new Map();
|
|
15
|
+
circuitBreakers = new Set();
|
|
16
|
+
constructor(config) {
|
|
17
|
+
this.config = {
|
|
18
|
+
reflectorContractId: config?.reflectorContractId || exports.DEFAULT_REFLECTOR_CONTRACT,
|
|
19
|
+
maxStalenessSeconds: config?.maxStalenessSeconds ?? 300, // 5 minutes default
|
|
20
|
+
maxDeviationPercent: config?.maxDeviationPercent ?? 2.5, // 2.5% max allowable slippage
|
|
21
|
+
fallbackEnabled: config?.fallbackEnabled ?? true,
|
|
22
|
+
};
|
|
23
|
+
// Initialize baseline canonical test / reference prices
|
|
24
|
+
this.initializeDefaultFeeds();
|
|
25
|
+
}
|
|
26
|
+
initializeDefaultFeeds() {
|
|
27
|
+
const now = Math.floor(Date.now() / 1000);
|
|
28
|
+
const defaults = [
|
|
29
|
+
{ symbol: "XLM", priceUsd: 0.52, decimals: 7, ledgerSeq: 65701000 },
|
|
30
|
+
{ symbol: "USDC", priceUsd: 1.00, decimals: 7, ledgerSeq: 65701000 },
|
|
31
|
+
{ symbol: "BTC", priceUsd: 96500.00, decimals: 7, ledgerSeq: 65701000 },
|
|
32
|
+
{ symbol: "ETH", priceUsd: 3600.00, decimals: 7, ledgerSeq: 65701000 },
|
|
33
|
+
{ symbol: "EURC", priceUsd: 1.05, decimals: 7, ledgerSeq: 65701000 },
|
|
34
|
+
];
|
|
35
|
+
for (const d of defaults) {
|
|
36
|
+
this.priceFeeds.set(d.symbol.toUpperCase(), {
|
|
37
|
+
symbol: d.symbol.toUpperCase(),
|
|
38
|
+
priceUsd: d.priceUsd,
|
|
39
|
+
decimals: d.decimals,
|
|
40
|
+
timestamp: now,
|
|
41
|
+
ledgerSeq: d.ledgerSeq,
|
|
42
|
+
oracleContractId: this.config.reflectorContractId,
|
|
43
|
+
status: "live",
|
|
44
|
+
});
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Retrieves the latest verified price feed for an asset.
|
|
49
|
+
*/
|
|
50
|
+
async getPrice(symbol) {
|
|
51
|
+
const sym = symbol.toUpperCase();
|
|
52
|
+
const feed = this.priceFeeds.get(sym);
|
|
53
|
+
if (!feed) {
|
|
54
|
+
throw new Error(`Reflector Oracle: No price feed available for asset '${sym}'`);
|
|
55
|
+
}
|
|
56
|
+
if (this.circuitBreakers.has(sym)) {
|
|
57
|
+
return {
|
|
58
|
+
...feed,
|
|
59
|
+
status: "circuit_broken",
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
const now = Math.floor(Date.now() / 1000);
|
|
63
|
+
const isStale = (now - feed.timestamp) > this.config.maxStalenessSeconds;
|
|
64
|
+
if (isStale) {
|
|
65
|
+
return {
|
|
66
|
+
...feed,
|
|
67
|
+
status: "stale",
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
return {
|
|
71
|
+
...feed,
|
|
72
|
+
status: "live",
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* Validates a proposed execution price against the Reflector Oracle benchmark.
|
|
77
|
+
*/
|
|
78
|
+
async validateTradePrice(symbol, proposedPriceUsd, customMaxDeviationPercent) {
|
|
79
|
+
const feed = await this.getPrice(symbol);
|
|
80
|
+
const maxDev = customMaxDeviationPercent ?? this.config.maxDeviationPercent;
|
|
81
|
+
if (feed.status === "circuit_broken") {
|
|
82
|
+
return {
|
|
83
|
+
ok: false,
|
|
84
|
+
code: "ORACLE_CIRCUIT_BROKEN",
|
|
85
|
+
message: `Reflector Oracle: Price feed for ${symbol} is locked due to active circuit-breaker!`,
|
|
86
|
+
referencePriceUsd: feed.priceUsd,
|
|
87
|
+
feedStatus: "circuit_broken",
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
if (feed.status === "stale") {
|
|
91
|
+
if (!this.config.fallbackEnabled) {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
code: "ORACLE_PRICE_STALE",
|
|
95
|
+
message: `Reflector Oracle: Price feed for ${symbol} is older than ${this.config.maxStalenessSeconds}s and fallback is disabled.`,
|
|
96
|
+
referencePriceUsd: feed.priceUsd,
|
|
97
|
+
feedStatus: "stale",
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const deviation = Math.abs((proposedPriceUsd - feed.priceUsd) / feed.priceUsd) * 100;
|
|
102
|
+
if (deviation > maxDev) {
|
|
103
|
+
// Auto-trigger circuit breaker if deviation is severe (> 10% flash crash / manipulation)
|
|
104
|
+
if (deviation >= 10.0) {
|
|
105
|
+
this.triggerCircuitBreaker(symbol, `Extreme price anomaly detected: ${deviation.toFixed(2)}% deviation`);
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
ok: false,
|
|
109
|
+
code: "EXCESSIVE_SLIPPAGE_DEVIATION",
|
|
110
|
+
message: `Proposed price ($${proposedPriceUsd}) deviates by ${deviation.toFixed(2)}% from Reflector Oracle benchmark ($${feed.priceUsd}), exceeding max limit of ${maxDev}%.`,
|
|
111
|
+
referencePriceUsd: feed.priceUsd,
|
|
112
|
+
deviationPercent: Number(deviation.toFixed(4)),
|
|
113
|
+
feedStatus: feed.status,
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
return {
|
|
117
|
+
ok: true,
|
|
118
|
+
code: "PRICE_VALIDATED",
|
|
119
|
+
message: `Price successfully validated against Reflector Oracle (${deviation.toFixed(2)}% deviation within ${maxDev}% tolerance).`,
|
|
120
|
+
referencePriceUsd: feed.priceUsd,
|
|
121
|
+
deviationPercent: Number(deviation.toFixed(4)),
|
|
122
|
+
feedStatus: feed.status,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Converts an amount from one asset to another using real-time oracle exchange rates.
|
|
127
|
+
*/
|
|
128
|
+
async convertAmount(fromSymbol, toSymbol, amount) {
|
|
129
|
+
const fromFeed = await this.getPrice(fromSymbol);
|
|
130
|
+
const toFeed = await this.getPrice(toSymbol);
|
|
131
|
+
if (fromFeed.status === "circuit_broken" || toFeed.status === "circuit_broken") {
|
|
132
|
+
throw new Error(`Cannot convert currency: Circuit breaker active on ${fromSymbol} or ${toSymbol}`);
|
|
133
|
+
}
|
|
134
|
+
const rate = fromFeed.priceUsd / toFeed.priceUsd;
|
|
135
|
+
const convertedAmount = amount * rate;
|
|
136
|
+
const timestamp = Math.min(fromFeed.timestamp, toFeed.timestamp);
|
|
137
|
+
return {
|
|
138
|
+
convertedAmount: Number(convertedAmount.toFixed(7)),
|
|
139
|
+
rate: Number(rate.toFixed(7)),
|
|
140
|
+
timestamp,
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
/**
|
|
144
|
+
* Updates or injects a live oracle price feed (e.g. from Horizon, Soroban RPC, or test harness).
|
|
145
|
+
*/
|
|
146
|
+
updatePriceFeed(symbol, priceUsd, timestamp, ledgerSeq) {
|
|
147
|
+
const sym = symbol.toUpperCase();
|
|
148
|
+
const existing = this.priceFeeds.get(sym);
|
|
149
|
+
const now = timestamp ?? Math.floor(Date.now() / 1000);
|
|
150
|
+
this.priceFeeds.set(sym, {
|
|
151
|
+
symbol: sym,
|
|
152
|
+
priceUsd,
|
|
153
|
+
decimals: existing?.decimals ?? 7,
|
|
154
|
+
timestamp: now,
|
|
155
|
+
ledgerSeq: ledgerSeq ?? (existing?.ledgerSeq ? existing.ledgerSeq + 1 : 65701001),
|
|
156
|
+
oracleContractId: this.config.reflectorContractId,
|
|
157
|
+
status: "live",
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
/**
|
|
161
|
+
* Triggers an emergency circuit breaker on a specific asset feed.
|
|
162
|
+
*/
|
|
163
|
+
triggerCircuitBreaker(symbol, _reason) {
|
|
164
|
+
this.circuitBreakers.add(symbol.toUpperCase());
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Resets an emergency circuit breaker once safety is confirmed.
|
|
168
|
+
*/
|
|
169
|
+
resetCircuitBreaker(symbol) {
|
|
170
|
+
this.circuitBreakers.delete(symbol.toUpperCase());
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
exports.ReflectorOracleAdapter = ReflectorOracleAdapter;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { ScopedAllowance, SpendRequest, SpendResult } from "../types.js";
|
|
2
|
+
export declare const DEFAULT_PROTOCOL_FEE_BPS = 20;
|
|
3
|
+
export declare const DEFAULT_TREASURY_ADDRESS = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
|
|
4
|
+
/**
|
|
5
|
+
* Detects if a destination address mimics a known safe wallet via prefix/suffix vanity spoofing (address poisoning).
|
|
6
|
+
*/
|
|
7
|
+
export declare function isPoisonedAddress(target: string, safeAddress: string): boolean;
|
|
8
|
+
/**
|
|
9
|
+
* Validate and process an agent spend attempt against a scoped allowance.
|
|
10
|
+
*/
|
|
11
|
+
export declare function verifyAndDeductSpend(allowance: ScopedAllowance, request: SpendRequest): SpendResult;
|
|
12
|
+
/**
|
|
13
|
+
* Reset spent balance for a recurring epoch if timestamp has rolled over.
|
|
14
|
+
*/
|
|
15
|
+
export declare function renewEpochAllowance(allowance: ScopedAllowance, newValidFrom: number, newValidUntil: number): ScopedAllowance;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.DEFAULT_TREASURY_ADDRESS = exports.DEFAULT_PROTOCOL_FEE_BPS = void 0;
|
|
4
|
+
exports.isPoisonedAddress = isPoisonedAddress;
|
|
5
|
+
exports.verifyAndDeductSpend = verifyAndDeductSpend;
|
|
6
|
+
exports.renewEpochAllowance = renewEpochAllowance;
|
|
7
|
+
exports.DEFAULT_PROTOCOL_FEE_BPS = 20; // 0.20%
|
|
8
|
+
exports.DEFAULT_TREASURY_ADDRESS = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
|
|
9
|
+
/**
|
|
10
|
+
* Detects if a destination address mimics a known safe wallet via prefix/suffix vanity spoofing (address poisoning).
|
|
11
|
+
*/
|
|
12
|
+
function isPoisonedAddress(target, safeAddress) {
|
|
13
|
+
if (target === safeAddress)
|
|
14
|
+
return false;
|
|
15
|
+
if (!target || !safeAddress || target.length !== safeAddress.length || target.length < 20)
|
|
16
|
+
return false;
|
|
17
|
+
const prefixMatch = target.slice(0, 4) === safeAddress.slice(0, 4);
|
|
18
|
+
const suffixMatch = target.slice(-4) === safeAddress.slice(-4);
|
|
19
|
+
return prefixMatch && suffixMatch;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Validate and process an agent spend attempt against a scoped allowance.
|
|
23
|
+
*/
|
|
24
|
+
function verifyAndDeductSpend(allowance, request) {
|
|
25
|
+
const treasury = allowance.treasuryPublicKey || exports.DEFAULT_TREASURY_ADDRESS;
|
|
26
|
+
if (isPoisonedAddress(request.destination, treasury) ||
|
|
27
|
+
(allowance.ownerPublicKey && isPoisonedAddress(request.destination, allowance.ownerPublicKey))) {
|
|
28
|
+
return {
|
|
29
|
+
ok: false,
|
|
30
|
+
code: "ADDRESS_POISONING_ATTACK_DETECTED",
|
|
31
|
+
message: `Destination ${request.destination} mimics a known treasury/owner wallet with identical prefix/suffix. Transaction blocked.`,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
if (!allowance.active) {
|
|
35
|
+
return {
|
|
36
|
+
ok: false,
|
|
37
|
+
code: "ALLOWANCE_PAUSED",
|
|
38
|
+
message: "The specified allowance is currently paused or inactive.",
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
if (request.agentPublicKey !== allowance.agentPublicKey) {
|
|
42
|
+
return {
|
|
43
|
+
ok: false,
|
|
44
|
+
code: "UNAUTHORIZED_AGENT",
|
|
45
|
+
message: "Agent public key does not match allowance beneficiary.",
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
if (request.timestamp < allowance.validFrom) {
|
|
49
|
+
return {
|
|
50
|
+
ok: false,
|
|
51
|
+
code: "ALLOWANCE_NOT_YET_VALID",
|
|
52
|
+
message: `Allowance window opens at timestamp ${allowance.validFrom}.`,
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (request.timestamp > allowance.validUntil) {
|
|
56
|
+
return {
|
|
57
|
+
ok: false,
|
|
58
|
+
code: "ALLOWANCE_EXPIRED",
|
|
59
|
+
message: `Allowance window expired at timestamp ${allowance.validUntil}.`,
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
if (request.amountStroops <= 0n) {
|
|
63
|
+
return {
|
|
64
|
+
ok: false,
|
|
65
|
+
code: "INVALID_AMOUNT",
|
|
66
|
+
message: "Spend amount must be strictly greater than zero.",
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
if (allowance.allowedDestinations &&
|
|
70
|
+
allowance.allowedDestinations.length > 0 &&
|
|
71
|
+
!allowance.allowedDestinations.includes(request.destination)) {
|
|
72
|
+
return {
|
|
73
|
+
ok: false,
|
|
74
|
+
code: "UNAPPROVED_DESTINATION",
|
|
75
|
+
message: `Destination ${request.destination} is not in the approved routing list.`,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
const remaining = allowance.maxStroops - allowance.spentStroops;
|
|
79
|
+
if (request.amountStroops > remaining) {
|
|
80
|
+
return {
|
|
81
|
+
ok: false,
|
|
82
|
+
code: "ALLOWANCE_EXCEEDED",
|
|
83
|
+
message: `Requested ${request.amountStroops} stroops exceeds remaining allowance of ${remaining} stroops.`,
|
|
84
|
+
remainingStroops: remaining,
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
// Calculate protocol monetization fee
|
|
88
|
+
const feeBps = allowance.protocolFeeBps !== undefined ? allowance.protocolFeeBps : exports.DEFAULT_PROTOCOL_FEE_BPS;
|
|
89
|
+
const feeStroops = (request.amountStroops * BigInt(feeBps)) / 10000n;
|
|
90
|
+
const netStroops = request.amountStroops - feeStroops;
|
|
91
|
+
// Deduct
|
|
92
|
+
allowance.spentStroops += request.amountStroops;
|
|
93
|
+
const newRemaining = allowance.maxStroops - allowance.spentStroops;
|
|
94
|
+
return {
|
|
95
|
+
ok: true,
|
|
96
|
+
code: "SPEND_AUTHORIZED",
|
|
97
|
+
message: "Spend authorized successfully within scoped allowance.",
|
|
98
|
+
remainingStroops: newRemaining,
|
|
99
|
+
spentStroops: allowance.spentStroops,
|
|
100
|
+
feeStroops,
|
|
101
|
+
netStroops,
|
|
102
|
+
treasuryPublicKey: treasury,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* Reset spent balance for a recurring epoch if timestamp has rolled over.
|
|
107
|
+
*/
|
|
108
|
+
function renewEpochAllowance(allowance, newValidFrom, newValidUntil) {
|
|
109
|
+
return {
|
|
110
|
+
...allowance,
|
|
111
|
+
spentStroops: 0n,
|
|
112
|
+
validFrom: newValidFrom,
|
|
113
|
+
validUntil: newValidUntil,
|
|
114
|
+
active: true,
|
|
115
|
+
};
|
|
116
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { SorobanTtlStatus } from "../types.js";
|
|
2
|
+
/** Default ledger threshold (approx 1 day at ~5 sec/ledger = 17,280 ledgers). */
|
|
3
|
+
export declare const DEFAULT_TTL_THRESHOLD_LEDGERS = 17280;
|
|
4
|
+
/** Default ledger extension size (approx 30 days = 518,400 ledgers). */
|
|
5
|
+
export declare const DEFAULT_EXTEND_TO_LEDGERS = 518400;
|
|
6
|
+
/**
|
|
7
|
+
* Evaluate the Soroban contract state Time-To-Live (TTL) and determine
|
|
8
|
+
* if an automated `extend_ttl` transaction is required to prevent state archival.
|
|
9
|
+
*/
|
|
10
|
+
export declare function evaluateContractTtl(contractId: string, currentLedger: number, liveUntilLedger: number, thresholdLedgers?: number, extendToLedgers?: number): SorobanTtlStatus;
|