@purseragents/sdk 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.
@@ -0,0 +1,42 @@
1
+ import { Purser } from "./client.js";
2
+ /** Where an agent reaches Purser when no engine URL is given. */
3
+ export declare const PURSER_DEFAULT_URL = "https://purseragents.fun";
4
+ /** A JSON Schema object for a tool's input, the subset every framework understands. */
5
+ export interface ToolInputSchema {
6
+ type: "object";
7
+ properties: Record<string, {
8
+ type: "string" | "number" | "integer";
9
+ description: string;
10
+ enum?: string[];
11
+ minimum?: number;
12
+ maximum?: number;
13
+ default?: string | number;
14
+ }>;
15
+ required: string[];
16
+ additionalProperties: false;
17
+ }
18
+ export interface PurserTool {
19
+ /** snake_case, the same names as the MCP server */
20
+ name: string;
21
+ title: string;
22
+ description: string;
23
+ parameters: ToolInputSchema;
24
+ /** True for tools that can move money: frameworks may ask a human first. */
25
+ movesMoney: boolean;
26
+ run(input: Record<string, unknown>): Promise<string>;
27
+ }
28
+ export interface PurserToolsOptions {
29
+ /** Only these tools (by name). Default: all of them. */
30
+ only?: string[];
31
+ /** Leave out the tools that move money, for a read-only agent. */
32
+ readOnly?: boolean;
33
+ }
34
+ /** Make a Purser client from settings, with the public engine as the default. */
35
+ export declare function purserFromSettings(s: {
36
+ apiKey?: string;
37
+ baseUrl?: string;
38
+ fetch?: typeof fetch;
39
+ }): Purser;
40
+ export declare function purserTools(purser: Purser, opts?: PurserToolsOptions): PurserTool[];
41
+ /** Run a tool and turn a failure into text the model can act on, so an agent never crashes on a bad call. */
42
+ export declare function runPurserTool(tool: PurserTool, input: Record<string, unknown>): Promise<string>;
package/dist/tools.js ADDED
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Purser's agent tools, framework-neutral. Each tool has a name, a description written for a model, a JSON Schema for
3
+ * its input and a run() that returns plain text the model can read. The framework packages wrap these:
4
+ * @purseragents/ai-sdk (Vercel AI SDK), @purseragents/langchain (LangChain) and @purseragents/plugin-elizaos (ElizaOS).
5
+ *
6
+ * import { Purser, purserTools } from "@purseragents/sdk";
7
+ * const tools = purserTools(new Purser({ baseUrl: "https://purseragents.fun", apiKey: process.env.PURSER_API_KEY }));
8
+ *
9
+ * Every payment goes through the owner's rules and the firewall first. A blocked payment is a normal answer with the
10
+ * reasons, never an exception, and the text tells the model not to look for a way around it.
11
+ */
12
+ import { formatUnits, parseUnits } from "viem";
13
+ import { Purser } from "./client.js";
14
+ /** Where an agent reaches Purser when no engine URL is given. */
15
+ export const PURSER_DEFAULT_URL = "https://purseragents.fun";
16
+ /** Make a Purser client from settings, with the public engine as the default. */
17
+ export function purserFromSettings(s) {
18
+ if (!s.apiKey)
19
+ throw new Error("Purser needs the agent's API key (PURSER_API_KEY). The owner creates it on purseragents.fun for one account.");
20
+ return new Purser({ baseUrl: s.baseUrl || PURSER_DEFAULT_URL, apiKey: s.apiKey, fetch: s.fetch });
21
+ }
22
+ const str = (v) => (v === undefined || v === null || v === "" ? undefined : String(v));
23
+ const ADDRESS = /^0x[0-9a-fA-F]{40}$/;
24
+ const AMOUNT = /^\d+(\.\d+)?$/;
25
+ export function purserTools(purser, opts = {}) {
26
+ let cached = null;
27
+ async function me() {
28
+ if (cached)
29
+ return cached;
30
+ const [who, cfg] = await Promise.all([purser.me(), purser.config()]);
31
+ cached = { safe: who.safe, tokens: cfg.tokens ?? [] };
32
+ return cached;
33
+ }
34
+ async function token(symbol = "USDG") {
35
+ const t = (await me()).tokens.find((x) => x.symbol.toUpperCase() === symbol.toUpperCase());
36
+ if (!t)
37
+ throw new Error(`Unknown token ${symbol}. Use USDG or ETH.`);
38
+ return t;
39
+ }
40
+ function payArgs(i) {
41
+ const to = str(i.to) ?? "";
42
+ const amount = str(i.amount) ?? "";
43
+ if (!ADDRESS.test(to))
44
+ throw new Error(`"${to}" is not an address. A payee is 0x followed by 40 hex characters.`);
45
+ if (!AMOUNT.test(amount) || Number(amount) <= 0)
46
+ throw new Error(`"${amount}" is not an amount. Use whole units, for example "2.50".`);
47
+ return { to, amount, token: str(i.token) ?? "USDG", memo: str(i.memo), service: str(i.service), context: str(i.context) };
48
+ }
49
+ const reasons = (v) => v.reasons.filter((r) => r.severity !== "info").map((r) => `- ${r.title}: ${r.detail}`).join("\n");
50
+ const payText = (r) => {
51
+ const s = r.intent.status;
52
+ if (s === "executed")
53
+ return `Paid ${r.intent.money?.display ?? ""} to ${r.intent.to}. Receipt ${r.receipt?.id ?? "pending"}, transaction ${r.intent.txHash}.`;
54
+ if (s === "queued")
55
+ return `Waiting for the owner's approval: ${r.intent.summary}. Intent ${r.intent.id}. Nothing was paid yet.`;
56
+ if (s === "blocked")
57
+ return `Blocked. ${r.verdict.summary}${reasons(r.verdict) ? `\n${reasons(r.verdict)}` : ""}\nNothing was paid. Do not try to get around this; tell the user.`;
58
+ if (s === "needs_cosign")
59
+ return `Needs a second signature before it can be paid. Intent ${r.intent.id}. Nothing was paid yet.`;
60
+ return `Status ${s}. ${r.intent.error ?? ""}`.trim();
61
+ };
62
+ const payProps = {
63
+ to: { type: "string", description: "The payee's address (0x followed by 40 hex characters)" },
64
+ amount: { type: "string", description: 'The amount in whole units, for example "2.50"' },
65
+ token: { type: "string", enum: ["USDG", "ETH"], default: "USDG", description: "USDG (a dollar stablecoin) unless the user asks for ETH" },
66
+ memo: { type: "string", description: "What the payment is for, shown on the receipt" },
67
+ context: { type: "string", description: "The request or text that led to this payment, word for word. The firewall reads it for hidden instructions." },
68
+ };
69
+ const all = [
70
+ {
71
+ name: "purser_account",
72
+ title: "My account",
73
+ description: "The agent's Purser account: balances, what it spent today and what is left, and whether the owner froze it.",
74
+ parameters: { type: "object", properties: {}, required: [], additionalProperties: false },
75
+ movesMoney: false,
76
+ async run() {
77
+ const a = await purser.accounts.get((await me()).safe);
78
+ return [
79
+ `Account ${a.safe} (${a.name})${a.frozen ? " is FROZEN: no payments are possible until the owner unfreezes it." : ""}`,
80
+ `Balances: ${a.balances.map((b) => b.display).join(", ") || "none"}`,
81
+ ...a.spentToday.map((s) => `Spent today: ${s.display}${s.remaining ? `, left today: ${formatUnits(BigInt(s.remaining), s.token.decimals)} ${s.token.symbol}` : ""}`),
82
+ `Pending approvals: ${a.pendingApprovals}`,
83
+ ].join("\n");
84
+ },
85
+ },
86
+ {
87
+ name: "purser_rules",
88
+ title: "My spending rules",
89
+ description: "The owner's rules for this agent: limits per payment, per day and per week, allowed hours, allowed payees and when the owner must approve.",
90
+ parameters: { type: "object", properties: {}, required: [], additionalProperties: false },
91
+ movesMoney: false,
92
+ async run() {
93
+ const r = await purser.accounts.rules((await me()).safe);
94
+ const show = (v, d, sym) => (v === null ? "no cap" : `${formatUnits(BigInt(v), d)} ${sym}`);
95
+ const lines = r.rules
96
+ .filter((x) => x.enabled)
97
+ .map((x) => `${x.token.symbol}: up to ${show(x.maxSingle, x.token.decimals, x.token.symbol)} per payment, ${show(x.daily, x.token.decimals, x.token.symbol)} a day, ${show(x.weekly, x.token.decimals, x.token.symbol)} a week; owner approval above ${show(x.approvalAbove, x.token.decimals, x.token.symbol)}`);
98
+ if (r.config.hoursUtc.length)
99
+ lines.push(`Allowed hours (UTC): ${r.config.hoursUtc.join(", ")}`);
100
+ if (r.config.payeeAllowlist)
101
+ lines.push(`Only these payees: ${r.allowlist.join(", ")}`);
102
+ if (r.config.maxPerMinute)
103
+ lines.push(`At most ${r.config.maxPerMinute} payments a minute`);
104
+ return lines.join("\n") || "No spending is allowed yet: the owner has not turned on a token.";
105
+ },
106
+ },
107
+ {
108
+ name: "purser_check_payment",
109
+ title: "Check a payment",
110
+ description: "Ask the firewall whether a payment would go through, without paying. Use it before a payment you are unsure about.",
111
+ parameters: { type: "object", properties: { to: payProps.to, amount: payProps.amount, token: payProps.token, context: payProps.context }, required: ["to", "amount"], additionalProperties: false },
112
+ movesMoney: false,
113
+ async run(i) {
114
+ const a = payArgs(i);
115
+ const t = await token(a.token);
116
+ const v = await purser.checkPayment({ to: a.to, amount: parseUnits(a.amount, t.decimals), token: t.address, trigger: a.context });
117
+ return `${v.decision === "block" ? "Would be blocked." : "Would be allowed."} ${v.summary}${reasons(v) ? `\n${reasons(v)}` : ""}`;
118
+ },
119
+ },
120
+ {
121
+ name: "purser_pay",
122
+ title: "Pay",
123
+ description: "Pay someone from the agent's Purser account. The owner's rules and the firewall check it first; a big payment may wait for the owner's approval. If it is blocked, tell the user why and do not try again another way.",
124
+ parameters: { type: "object", properties: payProps, required: ["to", "amount", "memo"], additionalProperties: false },
125
+ movesMoney: true,
126
+ async run(i) {
127
+ const a = payArgs(i);
128
+ const t = await token(a.token);
129
+ return payText(await purser.pay({ to: a.to, amount: parseUnits(a.amount, t.decimals), token: t.address, memo: a.memo, service: a.service, trigger: a.context }));
130
+ },
131
+ },
132
+ {
133
+ name: "purser_receipts",
134
+ title: "Receipts",
135
+ description: "The latest payments in and out of the account, newest first.",
136
+ parameters: { type: "object", properties: { limit: { type: "integer", minimum: 1, maximum: 50, default: 10, description: "How many receipts" } }, required: [], additionalProperties: false },
137
+ movesMoney: false,
138
+ async run(i) {
139
+ const limit = Math.min(50, Math.max(1, Number(i.limit ?? 10) || 10));
140
+ const r = await purser.accounts.receipts((await me()).safe, { limit });
141
+ return (r.items.map((x) => `${new Date(x.createdAt * 1000).toISOString().slice(0, 16)} ${x.direction === "in" ? "+" : "-"}${x.money.display} ${x.category} ${x.counterpartyName ?? x.counterparty}${x.memo ? ` (${x.memo})` : ""}`).join("\n") ||
142
+ "No receipts yet.");
143
+ },
144
+ },
145
+ {
146
+ name: "purser_paid_fetch",
147
+ title: "Fetch a paid URL",
148
+ description: "Fetch a URL that may charge for the answer over x402 (HTTP 402). If it asks for payment, Purser pays from the account within the rules, up to max_amount.",
149
+ parameters: {
150
+ type: "object",
151
+ properties: {
152
+ url: { type: "string", description: "The full https URL" },
153
+ max_amount: { type: "string", description: 'The most to pay in USDG, for example "0.50"' },
154
+ context: payProps.context,
155
+ },
156
+ required: ["url", "max_amount"],
157
+ additionalProperties: false,
158
+ },
159
+ movesMoney: true,
160
+ async run(i) {
161
+ const url = str(i.url) ?? "";
162
+ if (!/^https?:\/\//.test(url))
163
+ throw new Error(`"${url}" is not a URL.`);
164
+ const max = str(i.max_amount) ?? "";
165
+ if (!AMOUNT.test(max))
166
+ throw new Error(`"${max}" is not an amount.`);
167
+ const r = await purser.x402Fetch(url, { maxAmount: parseUnits(max, 6), trigger: str(i.context) });
168
+ const head = r.paid ? `Paid ${r.payment?.intent.money?.display ?? ""} and fetched.` : r.payment ? payText(r.payment) : r.status === 402 ? "Not paid." : "Fetched, nothing to pay.";
169
+ return `${head} HTTP ${r.status}\n${r.body.slice(0, 8000)}`;
170
+ },
171
+ },
172
+ {
173
+ name: "purser_pay_invoice",
174
+ title: "Pay an invoice",
175
+ description: "Pay an invoice another agent sent to this account. The money waits in escrow until the work is delivered.",
176
+ parameters: { type: "object", properties: { id: { type: "string", description: "The invoice id" } }, required: ["id"], additionalProperties: false },
177
+ movesMoney: true,
178
+ async run(i) {
179
+ const id = str(i.id);
180
+ if (!id)
181
+ throw new Error("Which invoice? Give its id.");
182
+ return payText(await purser.invoices.pay(id));
183
+ },
184
+ },
185
+ {
186
+ name: "purser_profit",
187
+ title: "Profit and loss",
188
+ description: "Income, spending, fees and profit over the last 30 days, with the biggest costs and customers.",
189
+ parameters: { type: "object", properties: {}, required: [], additionalProperties: false },
190
+ movesMoney: false,
191
+ async run() {
192
+ const p = await purser.accounts.pnl((await me()).safe);
193
+ return [
194
+ `Last 30 days: income $${p.incomeUsd}, spend $${p.spendUsd}, fees $${p.feesUsd}, profit $${p.profitUsd}`,
195
+ ...p.byModel.slice(0, 5).map((l) => `Model ${l.label}: $${l.spend}`),
196
+ ...p.byCustomer.slice(0, 5).map((l) => `Customer ${l.label}: $${l.income}`),
197
+ ].join("\n");
198
+ },
199
+ },
200
+ ];
201
+ return all.filter((t) => (!opts.only || opts.only.includes(t.name)) && (!opts.readOnly || !t.movesMoney));
202
+ }
203
+ /** Run a tool and turn a failure into text the model can act on, so an agent never crashes on a bad call. */
204
+ export async function runPurserTool(tool, input) {
205
+ try {
206
+ return await tool.run(input ?? {});
207
+ }
208
+ catch (e) {
209
+ const msg = e instanceof Error ? e.message : String(e);
210
+ return `Purser could not do that: ${msg}`;
211
+ }
212
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Verifies a Purser webhook. The engine sends `Purser-Signature: t=<unix seconds>,v1=<hex>` where v1 is
3
+ * HMAC-SHA256 of "<t>.<raw request body>" keyed with the webhook secret. Works in Node and browsers (WebCrypto).
4
+ */
5
+ export declare function verifyWebhook(secret: string, signatureHeader: string | null | undefined, rawBody: string, opts?: {
6
+ toleranceSeconds?: number;
7
+ now?: number;
8
+ }): Promise<boolean>;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Verifies a Purser webhook. The engine sends `Purser-Signature: t=<unix seconds>,v1=<hex>` where v1 is
3
+ * HMAC-SHA256 of "<t>.<raw request body>" keyed with the webhook secret. Works in Node and browsers (WebCrypto).
4
+ */
5
+ export async function verifyWebhook(secret, signatureHeader, rawBody, opts = {}) {
6
+ if (!signatureHeader)
7
+ return false;
8
+ const parts = Object.fromEntries(signatureHeader.split(",").map((p) => p.split("=", 2)));
9
+ const t = Number(parts.t);
10
+ if (!parts.v1 || !Number.isFinite(t))
11
+ return false;
12
+ const now = opts.now ?? Math.floor(Date.now() / 1000);
13
+ if (Math.abs(now - t) > (opts.toleranceSeconds ?? 300))
14
+ return false;
15
+ const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
16
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${t}.${rawBody}`)));
17
+ const hex = [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
18
+ if (hex.length !== parts.v1.length)
19
+ return false;
20
+ let diff = 0;
21
+ for (let i = 0; i < hex.length; i++)
22
+ diff |= hex.charCodeAt(i) ^ parts.v1.charCodeAt(i);
23
+ return diff === 0;
24
+ }
package/dist/x402.d.ts ADDED
@@ -0,0 +1,100 @@
1
+ import type { Address, Hex, LocalAccount } from "viem";
2
+ /** x402 version 2 wire types (scheme "exact", EVM). */
3
+ export interface PaymentRequirements {
4
+ scheme: "exact";
5
+ network: string;
6
+ amount: string;
7
+ asset: Address;
8
+ payTo: Address;
9
+ maxTimeoutSeconds: number;
10
+ extra?: {
11
+ name?: string;
12
+ version?: string;
13
+ purser?: boolean;
14
+ [k: string]: unknown;
15
+ };
16
+ }
17
+ export interface ResourceInfo {
18
+ url: string;
19
+ description?: string;
20
+ mimeType?: string;
21
+ serviceName?: string;
22
+ tags?: string[];
23
+ }
24
+ export interface PaymentRequired {
25
+ x402Version: 2;
26
+ error?: string;
27
+ resource: ResourceInfo;
28
+ accepts: PaymentRequirements[];
29
+ extensions?: Record<string, unknown>;
30
+ }
31
+ export interface ExactEvmPayload {
32
+ signature: Hex;
33
+ authorization: {
34
+ from: Address;
35
+ to: Address;
36
+ value: string;
37
+ validAfter: string;
38
+ validBefore: string;
39
+ nonce: Hex;
40
+ };
41
+ }
42
+ /** Purser accounts pay with a signed Purser intent; the facilitator settles it through the Purser module. */
43
+ export interface PurserIntentPayload {
44
+ purser: {
45
+ kind: "pay";
46
+ safe: Address;
47
+ token: Address;
48
+ to: Address;
49
+ amount: string;
50
+ service: Hex;
51
+ nonce: string;
52
+ deadline: string;
53
+ signature: Hex;
54
+ };
55
+ }
56
+ export interface PaymentPayload {
57
+ x402Version: 1 | 2;
58
+ resource?: ResourceInfo;
59
+ accepted: PaymentRequirements;
60
+ payload: ExactEvmPayload | PurserIntentPayload;
61
+ extensions?: Record<string, unknown>;
62
+ }
63
+ export interface VerifyResponse {
64
+ isValid: boolean;
65
+ invalidReason?: string;
66
+ payer?: Address;
67
+ }
68
+ export interface SettleResponse {
69
+ success: boolean;
70
+ errorReason?: string;
71
+ payer?: Address;
72
+ transaction: Hex | "";
73
+ network: string;
74
+ amount?: string;
75
+ }
76
+ export declare const HEADER_REQUIRED = "PAYMENT-REQUIRED";
77
+ export declare const HEADER_SIGNATURE = "PAYMENT-SIGNATURE";
78
+ export declare const HEADER_RESPONSE = "PAYMENT-RESPONSE";
79
+ export declare const HEADER_V1_PAYMENT = "X-PAYMENT";
80
+ export declare const encodeHeader: (v: unknown) => string;
81
+ export declare function decodeHeader<T>(v: string | null | undefined): T | null;
82
+ export declare const isPurserPayload: (p: PaymentPayload["payload"]) => p is PurserIntentPayload;
83
+ /** Builds an "exact" payload from a wallet that can sign EIP-712 (EIP-3009 TransferWithAuthorization). */
84
+ export declare function createExactPayload(account: LocalAccount, req: PaymentRequirements, opts?: {
85
+ chainId?: number;
86
+ resource?: ResourceInfo;
87
+ validForSeconds?: number;
88
+ }): Promise<PaymentPayload>;
89
+ /** Picks the first requirement this payer can meet on the given network. */
90
+ export declare function pickRequirement(pr: PaymentRequired, network: string, assets?: Address[]): PaymentRequirements | null;
91
+ /** Builds a payload for a Purser account: the agent's session key signs a Purser Pay intent to the merchant. */
92
+ export declare function createPurserPayload(agent: LocalAccount, account: {
93
+ safe: Address;
94
+ module: Address;
95
+ chainId: number;
96
+ }, req: PaymentRequirements, opts?: {
97
+ resource?: ResourceInfo;
98
+ service?: string;
99
+ validForSeconds?: number;
100
+ }): Promise<PaymentPayload>;
package/dist/x402.js ADDED
@@ -0,0 +1,89 @@
1
+ import { payTypedData, randomNonce, serviceId, transferAuthorizationTypedData } from "./eip712.js";
2
+ export const HEADER_REQUIRED = "PAYMENT-REQUIRED";
3
+ export const HEADER_SIGNATURE = "PAYMENT-SIGNATURE";
4
+ export const HEADER_RESPONSE = "PAYMENT-RESPONSE";
5
+ export const HEADER_V1_PAYMENT = "X-PAYMENT";
6
+ const b64 = (s) => (typeof Buffer !== "undefined" ? Buffer.from(s, "utf8").toString("base64") : btoa(unescape(encodeURIComponent(s))));
7
+ const unb64 = (s) => (typeof Buffer !== "undefined" ? Buffer.from(s, "base64").toString("utf8") : decodeURIComponent(escape(atob(s))));
8
+ export const encodeHeader = (v) => b64(JSON.stringify(v));
9
+ export function decodeHeader(v) {
10
+ if (!v)
11
+ return null;
12
+ try {
13
+ return JSON.parse(unb64(v));
14
+ }
15
+ catch {
16
+ return null;
17
+ }
18
+ }
19
+ export const isPurserPayload = (p) => !!p.purser;
20
+ function randomBytes32() {
21
+ const b = new Uint8Array(32);
22
+ crypto.getRandomValues(b);
23
+ return `0x${[...b].map((x) => x.toString(16).padStart(2, "0")).join("")}`;
24
+ }
25
+ /** Builds an "exact" payload from a wallet that can sign EIP-712 (EIP-3009 TransferWithAuthorization). */
26
+ export async function createExactPayload(account, req, opts = {}) {
27
+ const chainId = opts.chainId ?? Number(req.network.split(":")[1]);
28
+ const now = Math.floor(Date.now() / 1000);
29
+ const auth = {
30
+ from: account.address,
31
+ to: req.payTo,
32
+ value: BigInt(req.amount),
33
+ validAfter: BigInt(now - 60),
34
+ validBefore: BigInt(now + (opts.validForSeconds ?? req.maxTimeoutSeconds ?? 120)),
35
+ nonce: randomBytes32(),
36
+ };
37
+ const signature = await account.signTypedData(transferAuthorizationTypedData(chainId, req.asset, req.extra?.name ?? "Global Dollar", req.extra?.version ?? "1", auth));
38
+ return {
39
+ x402Version: 2,
40
+ resource: opts.resource,
41
+ accepted: req,
42
+ payload: {
43
+ signature,
44
+ authorization: {
45
+ from: auth.from,
46
+ to: auth.to,
47
+ value: auth.value.toString(),
48
+ validAfter: auth.validAfter.toString(),
49
+ validBefore: auth.validBefore.toString(),
50
+ nonce: auth.nonce,
51
+ },
52
+ },
53
+ };
54
+ }
55
+ /** Picks the first requirement this payer can meet on the given network. */
56
+ export function pickRequirement(pr, network, assets) {
57
+ return (pr.accepts.find((a) => a.scheme === "exact" && a.network === network && (!assets || assets.some((x) => x.toLowerCase() === a.asset.toLowerCase()))) ?? null);
58
+ }
59
+ /** Builds a payload for a Purser account: the agent's session key signs a Purser Pay intent to the merchant. */
60
+ export async function createPurserPayload(agent, account, req, opts = {}) {
61
+ const intent = {
62
+ safe: account.safe,
63
+ token: req.asset,
64
+ to: req.payTo,
65
+ amount: BigInt(req.amount),
66
+ service: serviceId(opts.service ?? opts.resource?.url ?? "x402"),
67
+ nonce: randomNonce(),
68
+ deadline: BigInt(Math.floor(Date.now() / 1000) + (opts.validForSeconds ?? 600)),
69
+ };
70
+ const signature = await agent.signTypedData(payTypedData(account.chainId, account.module, intent));
71
+ return {
72
+ x402Version: 2,
73
+ resource: opts.resource,
74
+ accepted: req,
75
+ payload: {
76
+ purser: {
77
+ kind: "pay",
78
+ safe: intent.safe,
79
+ token: intent.token,
80
+ to: intent.to,
81
+ amount: intent.amount.toString(),
82
+ service: intent.service,
83
+ nonce: intent.nonce.toString(),
84
+ deadline: intent.deadline.toString(),
85
+ signature,
86
+ },
87
+ },
88
+ };
89
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@purseragents/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "TypeScript SDK for Purser: a bank account for your AI agent on Robinhood Chain.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "default": "./dist/index.js"
13
+ },
14
+ "./schema": {
15
+ "types": "./dist/schema.d.ts",
16
+ "default": "./dist/schema.js"
17
+ },
18
+ "./merchant": {
19
+ "types": "./dist/merchant.d.ts",
20
+ "default": "./dist/merchant.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist",
25
+ "README.md"
26
+ ],
27
+ "dependencies": {
28
+ "viem": "2.57.18"
29
+ }
30
+ }