-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.ts
More file actions
81 lines (71 loc) · 2.55 KB
/
Copy pathclient.ts
File metadata and controls
81 lines (71 loc) · 2.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import { Keypair } from "@stellar/stellar-sdk";
import { wrapFetchWithPayment } from "stellar-x402/client-http";
import * as dotenv from "dotenv";
import * as path from "path";
// Load environment variables
dotenv.config({ path: path.join(__dirname, "../.env") });
const agentSecret = process.env.AGENT_SECRET_KEY;
if (!agentSecret || agentSecret.startsWith("SDUMMY")) {
console.error("Error: AGENT_SECRET_KEY is not configured with a valid Stellar secret key.");
console.log("Please update agent-node/.env with a valid Stellar Testnet secret key.");
process.exit(1);
}
// Generate the keypair from secret key
let keypair: Keypair;
try {
keypair = Keypair.fromSecret(agentSecret);
} catch (err) {
console.error("Invalid AGENT_SECRET_KEY format:", err);
process.exit(1);
}
console.log("--------------------------------------------------");
console.log("Starting Stellar x402 Programmatic Client:");
console.log(`- Agent Public Key: ${keypair.publicKey()}`);
console.log("--------------------------------------------------");
// Wrap the global fetch function.
// wrapFetchWithPayment automatically intercept 402 challenges, signs the required Soroban authorization
// payload using the provided keypair, submits the payment to the network via the RPC, and retries the request.
const fetchWithPayment = wrapFetchWithPayment(
fetch,
keypair,
10000000n, // Max allowed payment (1.0 USDC = 10,000,000 stroops)
undefined,
{
stellarConfig: {
rpcUrl: "https://soroban-testnet.stellar.org",
},
}
);
async function executeAgentAction() {
const targetUrl = "http://localhost:3000/agent/execute";
console.log(`[Client] Sending POST request to protected route: ${targetUrl}...`);
try {
const response = await fetchWithPayment(targetUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
action: "defi_swap",
params: {
fromAsset: "USDC",
toAsset: "XLM",
amount: "10",
},
}),
});
console.log(`[Client] Received response. Status code: ${response.status}`);
if (response.ok) {
const data = await response.json();
console.log("[Client] Request Succeeded!");
console.log(JSON.stringify(data, null, 2));
} else {
const errorText = await response.text();
console.error(`[Client] Request failed with status ${response.status}:`, errorText);
}
} catch (error) {
console.error("[Client] Unexpected error during request execution:", error);
}
}
// Execute the call
executeAgentAction();