@sparkysolutions/agentrail 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 (88) hide show
  1. package/.github/ISSUE_TEMPLATE/drips_wave_task.md +33 -0
  2. package/.github/workflows/auto-merge.yml +119 -0
  3. package/.github/workflows/ci.yml +35 -0
  4. package/BENCHMARKS.md +67 -0
  5. package/CONTRIBUTING.md +40 -0
  6. package/DRIPS_WAVE.md +81 -0
  7. package/FUNDING.json +7 -0
  8. package/ISSUES_PIPELINE.json +106 -0
  9. package/LICENSE +21 -0
  10. package/README.md +145 -2
  11. package/RUNBOOK.md +95 -0
  12. package/SCF_ACTIVATION_PROPOSAL.md +137 -0
  13. package/assets/sorobanagents_avatar.jpg +0 -0
  14. package/assets/sorobanagents_avatar.png +0 -0
  15. package/assets/sorobanagents_avatar_elite.png +0 -0
  16. package/contracts/agentrail/Cargo.lock +1895 -0
  17. package/contracts/agentrail/Cargo.toml +25 -0
  18. package/contracts/agentrail/src/lib.rs +296 -0
  19. package/contracts/agentrail/src/test.rs +442 -0
  20. package/contracts/agentrail/test_snapshots/test/test_circuit_breaker_pause_and_unpause.1.json +195 -0
  21. package/contracts/agentrail/test_snapshots/test/test_double_initialize_fails.1.json +123 -0
  22. package/contracts/agentrail/test_snapshots/test/test_execute_spend_deducts_and_accumulates.1.json +347 -0
  23. package/contracts/agentrail/test_snapshots/test/test_get_allowance_returns_none_for_unregistered.1.json +61 -0
  24. package/contracts/agentrail/test_snapshots/test/test_get_version_matches_cargo_toml.1.json +61 -0
  25. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_negative_amount_fails.1.json +123 -0
  26. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_success.1.json +250 -0
  27. package/contracts/agentrail/test_snapshots/test/test_grant_allowance_zero_amount_fails.1.json +123 -0
  28. package/contracts/agentrail/test_snapshots/test/test_initialize_and_protocol_fee.1.json +154 -0
  29. package/contracts/agentrail/test_snapshots/test/test_initialize_success.1.json +124 -0
  30. package/contracts/agentrail/test_snapshots/test/test_initialize_with_excessive_fee_fails.1.json +61 -0
  31. package/contracts/agentrail/test_snapshots/test/test_max_protocol_fee_spend_boundary.1.json +298 -0
  32. package/contracts/agentrail/test_snapshots/test/test_multi_agent_allowance_isolation.1.json +426 -0
  33. package/contracts/agentrail/test_snapshots/test/test_multi_owner_isolation.1.json +426 -0
  34. package/contracts/agentrail/test_snapshots/test/test_regrant_allowance_updates_limits.1.json +346 -0
  35. package/contracts/agentrail/test_snapshots/test/test_revoke_allowance_freezes_spending.1.json +292 -0
  36. package/contracts/agentrail/test_snapshots/test/test_set_protocol_fee_by_admin.1.json +165 -0
  37. package/contracts/agentrail/test_snapshots/test/test_spend_after_expiry_fails.1.json +250 -0
  38. package/contracts/agentrail/test_snapshots/test/test_spend_exact_allowance_boundary.1.json +298 -0
  39. package/contracts/agentrail/test_snapshots/test/test_spend_exceeding_allowance_fails.1.json +250 -0
  40. package/contracts/agentrail/test_snapshots/test/test_spend_fails_when_circuit_breaker_tripped.1.json +285 -0
  41. package/contracts/agentrail/test_snapshots/test/test_spend_negative_amount_fails.1.json +250 -0
  42. package/contracts/agentrail/test_snapshots/test/test_spend_non_existent_allowance_fails.1.json +123 -0
  43. package/contracts/agentrail/test_snapshots/test/test_spend_on_revoked_allowance_fails.1.json +292 -0
  44. package/contracts/agentrail/test_snapshots/test/test_spend_with_protocol_fee.1.json +286 -0
  45. package/contracts/agentrail/test_snapshots/test/test_spend_zero_amount_fails.1.json +250 -0
  46. package/contracts/agentrail/test_snapshots/test/test_unpause_restores_spend_operations.1.json +370 -0
  47. package/contracts/agentrail/test_snapshots/test/test_zero_protocol_fee_spend.1.json +298 -0
  48. package/deployment.testnet.json +15 -0
  49. package/dist/cli/sandbox.d.ts +41 -0
  50. package/dist/cli/sandbox.js +82 -0
  51. package/dist/index.d.ts +10 -0
  52. package/dist/index.js +26 -0
  53. package/dist/lib/micro-stream.d.ts +21 -0
  54. package/dist/lib/micro-stream.js +41 -0
  55. package/dist/lib/proof-of-task.d.ts +12 -0
  56. package/dist/lib/proof-of-task.js +32 -0
  57. package/dist/lib/scoped-allowance.d.ts +11 -0
  58. package/dist/lib/scoped-allowance.js +95 -0
  59. package/dist/lib/ttl-keeper.d.ts +10 -0
  60. package/dist/lib/ttl-keeper.js +36 -0
  61. package/dist/sdk/agent-client.d.ts +26 -0
  62. package/dist/sdk/agent-client.js +53 -0
  63. package/dist/types.d.ts +72 -0
  64. package/dist/types.js +5 -0
  65. package/docs/assets/favicon.png +0 -0
  66. package/docs/assets/logo.png +0 -0
  67. package/docs/index.html +840 -0
  68. package/package.json +38 -4
  69. package/scripts/demo-agent.ts +52 -0
  70. package/scripts/deploy-testnet.ts +228 -0
  71. package/scripts/security-audit.mjs +159 -0
  72. package/src/cli/sandbox.ts +127 -0
  73. package/src/index.ts +11 -0
  74. package/src/lib/micro-stream.ts +52 -0
  75. package/src/lib/proof-of-task.ts +39 -0
  76. package/src/lib/scoped-allowance.ts +112 -0
  77. package/src/lib/ttl-keeper.ts +44 -0
  78. package/src/sdk/agent-client.ts +66 -0
  79. package/src/types.ts +78 -0
  80. package/tests/agent-client.test.ts +62 -0
  81. package/tests/cli.test.ts +68 -0
  82. package/tests/micro-stream.test.ts +38 -0
  83. package/tests/proof-of-task.test.ts +78 -0
  84. package/tests/scoped-allowance.test.ts +135 -0
  85. package/tests/security-audit.test.ts +76 -0
  86. package/tests/ttl-keeper.test.ts +36 -0
  87. package/tsconfig.json +16 -0
  88. package/vitest.config.ts +8 -0
@@ -0,0 +1,41 @@
1
+ import { AgentRailClient } from "../sdk/agent-client.js";
2
+ import { ScopedAllowance, SpendResult } from "../types.js";
3
+ export interface SandboxAgent {
4
+ id: string;
5
+ name: string;
6
+ publicKey: string;
7
+ role: string;
8
+ }
9
+ export interface SandboxEnvironment {
10
+ client: AgentRailClient;
11
+ ownerAddress: string;
12
+ treasuryAddress: string;
13
+ agent: SandboxAgent;
14
+ allowance: ScopedAllowance;
15
+ protocolFeeBps: number;
16
+ }
17
+ export interface BalanceInspection {
18
+ allowanceId: string;
19
+ totalLimitStroops: string;
20
+ spentStroops: string;
21
+ remainingStroops: string;
22
+ remainingUsdc: string;
23
+ active: boolean;
24
+ isExpired: boolean;
25
+ }
26
+ /**
27
+ * Provision a sandboxed environment for autonomous AI agent micro-spend simulation.
28
+ */
29
+ export declare function provisionSandbox(agentName?: string, budgetUsdc?: string, feeBps?: number): SandboxEnvironment;
30
+ /**
31
+ * Inspect live allowance balance and capacity for an agent.
32
+ */
33
+ export declare function inspectBalance(env: SandboxEnvironment, allowanceId: string, currentTimeSec?: number): BalanceInspection;
34
+ /**
35
+ * Execute an automated micro-spend within the sandbox.
36
+ */
37
+ export declare function executeSandboxSpend(env: SandboxEnvironment, amountUsdc: string, memo?: string): {
38
+ result: SpendResult;
39
+ feeStroops: bigint;
40
+ netStroops: bigint;
41
+ };
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.provisionSandbox = provisionSandbox;
4
+ exports.inspectBalance = inspectBalance;
5
+ exports.executeSandboxSpend = executeSandboxSpend;
6
+ const agent_client_js_1 = require("../sdk/agent-client.js");
7
+ const micro_stream_js_1 = require("../lib/micro-stream.js");
8
+ /**
9
+ * Provision a sandboxed environment for autonomous AI agent micro-spend simulation.
10
+ */
11
+ function provisionSandbox(agentName = "Gemini-Soroban-Worker-01", budgetUsdc = "50.00", feeBps = 20) {
12
+ const client = new agent_client_js_1.AgentRailClient();
13
+ const ownerAddress = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
14
+ const treasuryAddress = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
15
+ const agentKey = "GAUTON0M0USAGNT77777777777777777777777777777777777777777";
16
+ const now = Math.floor(Date.now() / 1000);
17
+ const agent = {
18
+ id: `agent_${Date.now()}`,
19
+ name: agentName,
20
+ publicKey: agentKey,
21
+ role: "Autonomous Inference & Data Processing",
22
+ };
23
+ const limitStroops = (0, micro_stream_js_1.usdcToStroops)(budgetUsdc);
24
+ const allowance = {
25
+ id: `allowance_${agent.id}`,
26
+ ownerPublicKey: ownerAddress,
27
+ agentPublicKey: agent.publicKey,
28
+ maxStroops: limitStroops,
29
+ spentStroops: 0n,
30
+ validFrom: now - 60,
31
+ validUntil: now + 86400, // 24h
32
+ active: true,
33
+ protocolFeeBps: feeBps,
34
+ treasuryPublicKey: treasuryAddress,
35
+ };
36
+ client.registerAllowance(allowance);
37
+ return {
38
+ client,
39
+ ownerAddress,
40
+ treasuryAddress,
41
+ agent,
42
+ allowance,
43
+ protocolFeeBps: feeBps,
44
+ };
45
+ }
46
+ /**
47
+ * Inspect live allowance balance and capacity for an agent.
48
+ */
49
+ function inspectBalance(env, allowanceId, currentTimeSec = Math.floor(Date.now() / 1000)) {
50
+ const allowance = env.client.allowances.get(allowanceId);
51
+ if (!allowance) {
52
+ throw new Error(`Allowance ${allowanceId} does not exist in sandbox.`);
53
+ }
54
+ const remaining = allowance.maxStroops - allowance.spentStroops;
55
+ const isExpired = currentTimeSec > allowance.validUntil;
56
+ return {
57
+ allowanceId: allowance.id,
58
+ totalLimitStroops: allowance.maxStroops.toString(),
59
+ spentStroops: allowance.spentStroops.toString(),
60
+ remainingStroops: remaining.toString(),
61
+ remainingUsdc: (0, micro_stream_js_1.stroopsToUsdc)(remaining),
62
+ active: allowance.active && !isExpired,
63
+ isExpired,
64
+ };
65
+ }
66
+ /**
67
+ * Execute an automated micro-spend within the sandbox.
68
+ */
69
+ function executeSandboxSpend(env, amountUsdc, memo = "inference:gemini-pro-1.5") {
70
+ const amountStroops = (0, micro_stream_js_1.usdcToStroops)(amountUsdc);
71
+ const feeStroops = (amountStroops * BigInt(env.protocolFeeBps)) / 10000n;
72
+ const netStroops = amountStroops - feeStroops;
73
+ const result = env.client.spend({
74
+ allowanceId: env.allowance.id,
75
+ agentPublicKey: env.agent.publicKey,
76
+ destination: "GDEST1NAT10NPR0V1DER9999999999999999999999999999999999999",
77
+ amountStroops,
78
+ timestamp: Math.floor(Date.now() / 1000),
79
+ memo,
80
+ });
81
+ return { result, feeStroops, netStroops };
82
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * AgentRail Protocol Entrypoint.
3
+ */
4
+ export * from "./types.js";
5
+ export * from "./lib/scoped-allowance.js";
6
+ export * from "./lib/micro-stream.js";
7
+ export * from "./lib/ttl-keeper.js";
8
+ export * from "./lib/proof-of-task.js";
9
+ export * from "./sdk/agent-client.js";
10
+ export * from "./cli/sandbox.js";
package/dist/index.js ADDED
@@ -0,0 +1,26 @@
1
+ "use strict";
2
+ /**
3
+ * AgentRail Protocol Entrypoint.
4
+ */
5
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
+ if (k2 === undefined) k2 = k;
7
+ var desc = Object.getOwnPropertyDescriptor(m, k);
8
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
+ desc = { enumerable: true, get: function() { return m[k]; } };
10
+ }
11
+ Object.defineProperty(o, k2, desc);
12
+ }) : (function(o, m, k, k2) {
13
+ if (k2 === undefined) k2 = k;
14
+ o[k2] = m[k];
15
+ }));
16
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
17
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ __exportStar(require("./types.js"), exports);
21
+ __exportStar(require("./lib/scoped-allowance.js"), exports);
22
+ __exportStar(require("./lib/micro-stream.js"), exports);
23
+ __exportStar(require("./lib/ttl-keeper.js"), exports);
24
+ __exportStar(require("./lib/proof-of-task.js"), exports);
25
+ __exportStar(require("./sdk/agent-client.js"), exports);
26
+ __exportStar(require("./cli/sandbox.js"), exports);
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Real-time micro-payment streaming calculations for LLM inference, API usage, and continuous work.
3
+ */
4
+ export interface TokenPricingRate {
5
+ /** Cost in stroops per 1,000 prompt tokens (1 USDC = 10,000,000 stroops). */
6
+ promptStroopsPer1k: bigint;
7
+ /** Cost in stroops per 1,000 completion tokens. */
8
+ completionStroopsPer1k: bigint;
9
+ }
10
+ /**
11
+ * Calculate the exact stroop amount for given token usage.
12
+ */
13
+ export declare function calculateTokenCost(promptTokens: number, completionTokens: number, rates: TokenPricingRate): bigint;
14
+ /**
15
+ * Convert human-readable decimal USDC amount string to integer stroops (7 decimals).
16
+ */
17
+ export declare function usdcToStroops(usdcAmount: string): bigint;
18
+ /**
19
+ * Convert stroops integer to human-readable 7-decimal USDC string.
20
+ */
21
+ export declare function stroopsToUsdc(stroops: bigint): string;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ /**
3
+ * Real-time micro-payment streaming calculations for LLM inference, API usage, and continuous work.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.calculateTokenCost = calculateTokenCost;
7
+ exports.usdcToStroops = usdcToStroops;
8
+ exports.stroopsToUsdc = stroopsToUsdc;
9
+ /**
10
+ * Calculate the exact stroop amount for given token usage.
11
+ */
12
+ function calculateTokenCost(promptTokens, completionTokens, rates) {
13
+ if (promptTokens < 0 || completionTokens < 0) {
14
+ throw new Error("Token counts must be non-negative");
15
+ }
16
+ const promptCost = (BigInt(promptTokens) * rates.promptStroopsPer1k) / 1000n;
17
+ const completionCost = (BigInt(completionTokens) * rates.completionStroopsPer1k) / 1000n;
18
+ return promptCost + completionCost;
19
+ }
20
+ /**
21
+ * Convert human-readable decimal USDC amount string to integer stroops (7 decimals).
22
+ */
23
+ function usdcToStroops(usdcAmount) {
24
+ const parts = usdcAmount.trim().split(".");
25
+ if (parts.length > 2)
26
+ throw new Error("Invalid decimal format");
27
+ const whole = BigInt(parts[0] || "0");
28
+ const fractionStr = (parts[1] || "").slice(0, 7).padEnd(7, "0");
29
+ const fraction = BigInt(fractionStr);
30
+ return whole * 10000000n + fraction;
31
+ }
32
+ /**
33
+ * Convert stroops integer to human-readable 7-decimal USDC string.
34
+ */
35
+ function stroopsToUsdc(stroops) {
36
+ if (stroops < 0n)
37
+ throw new Error("Stroops must be non-negative");
38
+ const whole = stroops / 10000000n;
39
+ const fraction = stroops % 10000000n;
40
+ return `${whole}.${fraction.toString().padStart(7, "0")}`;
41
+ }
@@ -0,0 +1,12 @@
1
+ import { EscrowTask, ProofOfTaskSubmission } from "../types.js";
2
+ /**
3
+ * Compute the canonical SHA-256 commitment hash for a task output and nonce.
4
+ */
5
+ export declare function computeTaskCommitment(outputPayload: string, nonce: string): string;
6
+ /**
7
+ * Verify an autonomous AI agent's submitted proof against the on-chain task escrow.
8
+ */
9
+ export declare function verifyTaskProof(task: EscrowTask, submission: ProofOfTaskSubmission, currentTimestamp: number): {
10
+ ok: boolean;
11
+ reason?: string;
12
+ };
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.computeTaskCommitment = computeTaskCommitment;
4
+ exports.verifyTaskProof = verifyTaskProof;
5
+ const node_crypto_1 = require("node:crypto");
6
+ /**
7
+ * Compute the canonical SHA-256 commitment hash for a task output and nonce.
8
+ */
9
+ function computeTaskCommitment(outputPayload, nonce) {
10
+ return (0, node_crypto_1.createHash)("sha256")
11
+ .update(`${outputPayload}:${nonce}`, "utf8")
12
+ .digest("hex");
13
+ }
14
+ /**
15
+ * Verify an autonomous AI agent's submitted proof against the on-chain task escrow.
16
+ */
17
+ function verifyTaskProof(task, submission, currentTimestamp) {
18
+ if (task.status !== "pending") {
19
+ return { ok: false, reason: `Task is not pending (status: ${task.status})` };
20
+ }
21
+ if (submission.agentWorkerPublicKey !== task.agentWorkerPublicKey) {
22
+ return { ok: false, reason: "Proof submitter does not match designated worker key" };
23
+ }
24
+ if (currentTimestamp > task.expiresAt) {
25
+ return { ok: false, reason: "Task escrow deadline has expired; refund available" };
26
+ }
27
+ const computedHash = computeTaskCommitment(submission.outputPayload, submission.nonce);
28
+ if (computedHash !== task.taskCommitmentHash) {
29
+ return { ok: false, reason: "Cryptographic commitment hash mismatch" };
30
+ }
31
+ return { ok: true };
32
+ }
@@ -0,0 +1,11 @@
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
+ * Validate and process an agent spend attempt against a scoped allowance.
6
+ */
7
+ export declare function verifyAndDeductSpend(allowance: ScopedAllowance, request: SpendRequest): SpendResult;
8
+ /**
9
+ * Reset spent balance for a recurring epoch if timestamp has rolled over.
10
+ */
11
+ export declare function renewEpochAllowance(allowance: ScopedAllowance, newValidFrom: number, newValidUntil: number): ScopedAllowance;
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_TREASURY_ADDRESS = exports.DEFAULT_PROTOCOL_FEE_BPS = void 0;
4
+ exports.verifyAndDeductSpend = verifyAndDeductSpend;
5
+ exports.renewEpochAllowance = renewEpochAllowance;
6
+ exports.DEFAULT_PROTOCOL_FEE_BPS = 20; // 0.20%
7
+ exports.DEFAULT_TREASURY_ADDRESS = "GDDJH64X5VEXI7UWZMJA3YUG7ANYHKRRRFHLD2SF5OWEETNFBVYMRXZT";
8
+ /**
9
+ * Validate and process an agent spend attempt against a scoped allowance.
10
+ */
11
+ function verifyAndDeductSpend(allowance, request) {
12
+ if (!allowance.active) {
13
+ return {
14
+ ok: false,
15
+ code: "ALLOWANCE_PAUSED",
16
+ message: "The specified allowance is currently paused or inactive.",
17
+ };
18
+ }
19
+ if (request.agentPublicKey !== allowance.agentPublicKey) {
20
+ return {
21
+ ok: false,
22
+ code: "UNAUTHORIZED_AGENT",
23
+ message: "Agent public key does not match allowance beneficiary.",
24
+ };
25
+ }
26
+ if (request.timestamp < allowance.validFrom) {
27
+ return {
28
+ ok: false,
29
+ code: "ALLOWANCE_NOT_YET_VALID",
30
+ message: `Allowance window opens at timestamp ${allowance.validFrom}.`,
31
+ };
32
+ }
33
+ if (request.timestamp > allowance.validUntil) {
34
+ return {
35
+ ok: false,
36
+ code: "ALLOWANCE_EXPIRED",
37
+ message: `Allowance window expired at timestamp ${allowance.validUntil}.`,
38
+ };
39
+ }
40
+ if (request.amountStroops <= 0n) {
41
+ return {
42
+ ok: false,
43
+ code: "INVALID_AMOUNT",
44
+ message: "Spend amount must be strictly greater than zero.",
45
+ };
46
+ }
47
+ if (allowance.allowedDestinations &&
48
+ allowance.allowedDestinations.length > 0 &&
49
+ !allowance.allowedDestinations.includes(request.destination)) {
50
+ return {
51
+ ok: false,
52
+ code: "UNAPPROVED_DESTINATION",
53
+ message: `Destination ${request.destination} is not in the approved routing list.`,
54
+ };
55
+ }
56
+ const remaining = allowance.maxStroops - allowance.spentStroops;
57
+ if (request.amountStroops > remaining) {
58
+ return {
59
+ ok: false,
60
+ code: "ALLOWANCE_EXCEEDED",
61
+ message: `Requested ${request.amountStroops} stroops exceeds remaining allowance of ${remaining} stroops.`,
62
+ remainingStroops: remaining,
63
+ };
64
+ }
65
+ // Calculate protocol monetization fee
66
+ const feeBps = allowance.protocolFeeBps !== undefined ? allowance.protocolFeeBps : exports.DEFAULT_PROTOCOL_FEE_BPS;
67
+ const treasury = allowance.treasuryPublicKey || exports.DEFAULT_TREASURY_ADDRESS;
68
+ const feeStroops = (request.amountStroops * BigInt(feeBps)) / 10000n;
69
+ const netStroops = request.amountStroops - feeStroops;
70
+ // Deduct
71
+ allowance.spentStroops += request.amountStroops;
72
+ const newRemaining = allowance.maxStroops - allowance.spentStroops;
73
+ return {
74
+ ok: true,
75
+ code: "SPEND_AUTHORIZED",
76
+ message: "Spend authorized successfully within scoped allowance.",
77
+ remainingStroops: newRemaining,
78
+ spentStroops: allowance.spentStroops,
79
+ feeStroops,
80
+ netStroops,
81
+ treasuryPublicKey: treasury,
82
+ };
83
+ }
84
+ /**
85
+ * Reset spent balance for a recurring epoch if timestamp has rolled over.
86
+ */
87
+ function renewEpochAllowance(allowance, newValidFrom, newValidUntil) {
88
+ return {
89
+ ...allowance,
90
+ spentStroops: 0n,
91
+ validFrom: newValidFrom,
92
+ validUntil: newValidUntil,
93
+ active: true,
94
+ };
95
+ }
@@ -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;
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_EXTEND_TO_LEDGERS = exports.DEFAULT_TTL_THRESHOLD_LEDGERS = void 0;
4
+ exports.evaluateContractTtl = evaluateContractTtl;
5
+ /** Default ledger threshold (approx 1 day at ~5 sec/ledger = 17,280 ledgers). */
6
+ exports.DEFAULT_TTL_THRESHOLD_LEDGERS = 17_280;
7
+ /** Default ledger extension size (approx 30 days = 518,400 ledgers). */
8
+ exports.DEFAULT_EXTEND_TO_LEDGERS = 518_400;
9
+ /**
10
+ * Evaluate the Soroban contract state Time-To-Live (TTL) and determine
11
+ * if an automated `extend_ttl` transaction is required to prevent state archival.
12
+ */
13
+ function evaluateContractTtl(contractId, currentLedger, liveUntilLedger, thresholdLedgers = exports.DEFAULT_TTL_THRESHOLD_LEDGERS, extendToLedgers = exports.DEFAULT_EXTEND_TO_LEDGERS) {
14
+ if (liveUntilLedger < currentLedger) {
15
+ return {
16
+ contractId,
17
+ currentLedger,
18
+ liveUntilLedger,
19
+ remainingLedgers: 0,
20
+ thresholdLedgers,
21
+ needsBump: true,
22
+ recommendedExtendLedgers: extendToLedgers,
23
+ };
24
+ }
25
+ const remaining = liveUntilLedger - currentLedger;
26
+ const needsBump = remaining <= thresholdLedgers;
27
+ return {
28
+ contractId,
29
+ currentLedger,
30
+ liveUntilLedger,
31
+ remainingLedgers: remaining,
32
+ thresholdLedgers,
33
+ needsBump,
34
+ recommendedExtendLedgers: needsBump ? extendToLedgers - remaining : 0,
35
+ };
36
+ }
@@ -0,0 +1,26 @@
1
+ import { ScopedAllowance, SpendRequest, SpendResult } from "../types.js";
2
+ import { TokenPricingRate } from "../lib/micro-stream.js";
3
+ export declare class AgentRailClient {
4
+ private allowances;
5
+ /**
6
+ * Register a newly provisioned scoped allowance for an autonomous agent session.
7
+ */
8
+ registerAllowance(allowance: ScopedAllowance): void;
9
+ /**
10
+ * Authorize a micropayment spend from an active agent allowance.
11
+ */
12
+ spend(request: SpendRequest): SpendResult;
13
+ /**
14
+ * Helper to compute inference micropayment cost in stroops.
15
+ */
16
+ computeTokenFee(promptTokens: number, completionTokens: number, rates: TokenPricingRate): bigint;
17
+ /**
18
+ * Helper to inspect Soroban contract TTL health.
19
+ */
20
+ checkContractTtl(contractId: string, currentLedger: number, liveUntilLedger: number): import("../types.js").SorobanTtlStatus;
21
+ /**
22
+ * Helper for proof of task commitment computation.
23
+ */
24
+ makeProofCommitment(outputPayload: string, nonce: string): string;
25
+ getAllowance(id: string): ScopedAllowance | undefined;
26
+ }
@@ -0,0 +1,53 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AgentRailClient = void 0;
4
+ const scoped_allowance_js_1 = require("../lib/scoped-allowance.js");
5
+ const micro_stream_js_1 = require("../lib/micro-stream.js");
6
+ const ttl_keeper_js_1 = require("../lib/ttl-keeper.js");
7
+ const proof_of_task_js_1 = require("../lib/proof-of-task.js");
8
+ class AgentRailClient {
9
+ allowances = new Map();
10
+ /**
11
+ * Register a newly provisioned scoped allowance for an autonomous agent session.
12
+ */
13
+ registerAllowance(allowance) {
14
+ this.allowances.set(allowance.id, { ...allowance });
15
+ }
16
+ /**
17
+ * Authorize a micropayment spend from an active agent allowance.
18
+ */
19
+ spend(request) {
20
+ const allowance = this.allowances.get(request.allowanceId);
21
+ if (!allowance) {
22
+ return {
23
+ ok: false,
24
+ code: "ALLOWANCE_NOT_FOUND",
25
+ message: `Allowance with ID ${request.allowanceId} was not found.`,
26
+ };
27
+ }
28
+ const result = (0, scoped_allowance_js_1.verifyAndDeductSpend)(allowance, request);
29
+ return result;
30
+ }
31
+ /**
32
+ * Helper to compute inference micropayment cost in stroops.
33
+ */
34
+ computeTokenFee(promptTokens, completionTokens, rates) {
35
+ return (0, micro_stream_js_1.calculateTokenCost)(promptTokens, completionTokens, rates);
36
+ }
37
+ /**
38
+ * Helper to inspect Soroban contract TTL health.
39
+ */
40
+ checkContractTtl(contractId, currentLedger, liveUntilLedger) {
41
+ return (0, ttl_keeper_js_1.evaluateContractTtl)(contractId, currentLedger, liveUntilLedger);
42
+ }
43
+ /**
44
+ * Helper for proof of task commitment computation.
45
+ */
46
+ makeProofCommitment(outputPayload, nonce) {
47
+ return (0, proof_of_task_js_1.computeTaskCommitment)(outputPayload, nonce);
48
+ }
49
+ getAllowance(id) {
50
+ return this.allowances.get(id);
51
+ }
52
+ }
53
+ exports.AgentRailClient = AgentRailClient;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Core type definitions for AgentRail Protocol.
3
+ */
4
+ export interface ScopedAllowance {
5
+ /** Unique allowance identifier. */
6
+ id: string;
7
+ /** Human or organization master account public key (G...). */
8
+ ownerPublicKey: string;
9
+ /** Autonomous AI Agent session public key (G...). */
10
+ agentPublicKey: string;
11
+ /** Maximum allowance amount in stroops (1 USDC = 10^7 stroops). */
12
+ maxStroops: bigint;
13
+ /** Currently spent stroops in the active epoch. */
14
+ spentStroops: bigint;
15
+ /** Unix timestamp in seconds when the allowance window opens. */
16
+ validFrom: number;
17
+ /** Unix timestamp in seconds when the allowance window expires. */
18
+ validUntil: number;
19
+ /** Array of approved destination public keys or contract IDs. */
20
+ allowedDestinations?: string[];
21
+ /** Whether the allowance is currently active or paused. */
22
+ active: boolean;
23
+ /** Protocol fee basis points (e.g. 20 bps = 0.20%). Defaults to 20 if omitted. */
24
+ protocolFeeBps?: number;
25
+ /** Protocol treasury wallet address that collects transaction fees. */
26
+ treasuryPublicKey?: string;
27
+ }
28
+ export interface SpendRequest {
29
+ allowanceId: string;
30
+ agentPublicKey: string;
31
+ destination: string;
32
+ amountStroops: bigint;
33
+ timestamp: number;
34
+ memo?: string;
35
+ }
36
+ export interface SpendResult {
37
+ ok: boolean;
38
+ code: string;
39
+ message: string;
40
+ remainingStroops?: bigint;
41
+ spentStroops?: bigint;
42
+ /** Protocol monetization fee in stroops routed to treasury. */
43
+ feeStroops?: bigint;
44
+ /** Net amount in stroops routed to recipient. */
45
+ netStroops?: bigint;
46
+ /** Treasury address where fee was routed. */
47
+ treasuryPublicKey?: string;
48
+ }
49
+ export interface EscrowTask {
50
+ taskId: string;
51
+ payerPublicKey: string;
52
+ agentWorkerPublicKey: string;
53
+ rewardStroops: bigint;
54
+ taskCommitmentHash: string;
55
+ expiresAt: number;
56
+ status: "pending" | "fulfilled" | "refunded" | "disputed";
57
+ }
58
+ export interface ProofOfTaskSubmission {
59
+ taskId: string;
60
+ agentWorkerPublicKey: string;
61
+ outputPayload: string;
62
+ nonce: string;
63
+ }
64
+ export interface SorobanTtlStatus {
65
+ contractId: string;
66
+ currentLedger: number;
67
+ liveUntilLedger: number;
68
+ remainingLedgers: number;
69
+ thresholdLedgers: number;
70
+ needsBump: boolean;
71
+ recommendedExtendLedgers: number;
72
+ }
package/dist/types.js ADDED
@@ -0,0 +1,5 @@
1
+ "use strict";
2
+ /**
3
+ * Core type definitions for AgentRail Protocol.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
Binary file
Binary file