@agentbadge/circle-payments 0.1.17 → 0.1.19

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 (42) hide show
  1. package/README.md +77 -0
  2. package/dist/buyer/accepts.d.ts +33 -0
  3. package/dist/buyer/accepts.js +150 -0
  4. package/dist/buyer/caps.d.ts +27 -0
  5. package/dist/buyer/caps.js +67 -0
  6. package/dist/buyer/client.d.ts +66 -0
  7. package/dist/buyer/client.js +282 -0
  8. package/dist/buyer/guard.d.ts +9 -0
  9. package/dist/buyer/guard.js +1 -0
  10. package/dist/buyer/paginate.d.ts +6 -0
  11. package/dist/buyer/paginate.js +21 -0
  12. package/dist/buyer/risk-guard.d.ts +10 -0
  13. package/dist/buyer/risk-guard.js +47 -0
  14. package/dist/buyer/session.d.ts +18 -0
  15. package/dist/buyer/session.js +31 -0
  16. package/dist/chain/chain.d.ts +32 -0
  17. package/dist/chain/chain.js +44 -0
  18. package/dist/chain/index.d.ts +1 -0
  19. package/dist/chain/index.js +1 -0
  20. package/dist/chains.d.ts +8 -0
  21. package/dist/chains.js +28 -1
  22. package/dist/cli/pay.d.ts +7 -0
  23. package/dist/cli/pay.js +275 -0
  24. package/dist/gateway/deposit.d.ts +1 -1
  25. package/dist/gateway-probe.d.ts +1 -1
  26. package/dist/identity/erc8004.d.ts +18 -0
  27. package/dist/identity/erc8004.js +18 -1
  28. package/dist/identity/verify-passport.d.ts +1 -0
  29. package/dist/identity/verify-passport.js +1 -1
  30. package/dist/index.d.ts +12 -0
  31. package/dist/index.js +12 -0
  32. package/dist/middleware.d.ts +11 -0
  33. package/dist/middleware.js +40 -2
  34. package/dist/signer/arc-signer.d.ts +29 -0
  35. package/dist/signer/arc-signer.js +8 -0
  36. package/dist/signer/env-key.d.ts +20 -0
  37. package/dist/signer/env-key.js +58 -0
  38. package/dist/signer/protocol.d.ts +46 -0
  39. package/dist/signer/protocol.js +34 -0
  40. package/dist/signer/socket.d.ts +19 -0
  41. package/dist/signer/socket.js +139 -0
  42. package/package.json +5 -2
@@ -0,0 +1,275 @@
1
+ #!/usr/bin/env node
2
+ import { createPublicClient, createWalletClient, defineChain, erc20Abi, http, } from "viem";
3
+ import { privateKeyToAccount } from "viem/accounts";
4
+ import { getChain } from "../chains.js";
5
+ import { decode402 } from "../identity/verify-passport.js";
6
+ import { assertCaps, BudgetExhaustedError, CapExceededError, PaymentNotAcceptedError, } from "../buyer/caps.js";
7
+ import { atomicToUsd, validateAccepts, } from "../buyer/accepts.js";
8
+ import { createPayingClient, PaymentRefusedError, } from "../buyer/client.js";
9
+ import { createRiskGuard } from "../buyer/risk-guard.js";
10
+ import { gatewayBalance } from "../gateway/deposit.js";
11
+ const EXIT_OK = 0;
12
+ const EXIT_REFUSED = 2;
13
+ const EXIT_TRANSPORT = 3;
14
+ const USAGE = `agentbadge pay <url> — pay an x402-gated resource
15
+
16
+ Required (flag or env, flag wins):
17
+ --max-payment <usd> per-call cap (AGENTBADGE_MAX_PAYMENT)
18
+ --budget <usd> session budget (AGENTBADGE_BUDGET)
19
+
20
+ Optional:
21
+ --method <m> HTTP method (default GET)
22
+ --body <json> request body
23
+ --network <caip2> restrict to one network (e.g. eip155:5042002)
24
+ --auto-deposit <usd> auto top-up Gateway balance when short
25
+ --risk-check vet every payTo via risk API before signing
26
+ (AGENTBADGE_RISK_ENDPOINT to override)
27
+ --print-only show payment details, never sign
28
+ --help this text
29
+
30
+ Secrets:
31
+ AGENTBADGE_PAYER_KEY payer private key (env only — never a flag)
32
+
33
+ Exit codes: 0 ok · 2 refusal/cap/budget/usage · 3 transport`;
34
+ function parseArgs(argv) {
35
+ const args = { method: "GET", printOnly: false, help: false, riskCheck: false };
36
+ const takeValue = (i, flag) => {
37
+ const v = argv[i + 1];
38
+ if (v === undefined || v.startsWith("--")) {
39
+ throw new TypeError(`flag ${flag} requires a value`);
40
+ }
41
+ return v;
42
+ };
43
+ for (let i = 0; i < argv.length; i++) {
44
+ const a = argv[i];
45
+ switch (a) {
46
+ case "pay":
47
+ break;
48
+ case "--max-payment":
49
+ args.maxPayment = takeValue(i++, a);
50
+ break;
51
+ case "--budget":
52
+ args.budget = takeValue(i++, a);
53
+ break;
54
+ case "--method":
55
+ args.method = takeValue(i++, a).toUpperCase();
56
+ break;
57
+ case "--body":
58
+ args.body = takeValue(i++, a);
59
+ break;
60
+ case "--network":
61
+ args.network = takeValue(i++, a);
62
+ break;
63
+ case "--auto-deposit":
64
+ args.autoDeposit = takeValue(i++, a);
65
+ break;
66
+ case "--risk-check":
67
+ args.riskCheck = true;
68
+ break;
69
+ case "--print-only":
70
+ args.printOnly = true;
71
+ break;
72
+ case "--help":
73
+ case "-h":
74
+ args.help = true;
75
+ break;
76
+ default:
77
+ if (!a.startsWith("-") && args.url === undefined) {
78
+ args.url = a;
79
+ }
80
+ else {
81
+ throw new TypeError(`unknown argument: ${a}`);
82
+ }
83
+ }
84
+ }
85
+ return args;
86
+ }
87
+ function toViemChain(c) {
88
+ return defineChain({
89
+ id: c.chainId,
90
+ name: c.name,
91
+ nativeCurrency: { name: "USDC", symbol: "USDC", decimals: 18 },
92
+ rpcUrls: { default: { http: [c.rpcUrl] } },
93
+ });
94
+ }
95
+ function toCaps(args, env) {
96
+ const maxPaymentUsd = args.maxPayment ?? env.AGENTBADGE_MAX_PAYMENT;
97
+ const sessionBudgetUsd = args.budget ?? env.AGENTBADGE_BUDGET;
98
+ const caps = {
99
+ maxPaymentUsd: maxPaymentUsd ?? "",
100
+ sessionBudgetUsd: sessionBudgetUsd ?? "",
101
+ ...(args.network
102
+ ? { allowedNetworks: [args.network] }
103
+ : {}),
104
+ };
105
+ assertCaps(caps);
106
+ return caps;
107
+ }
108
+ async function eoaUsdcBalance(chain, address) {
109
+ try {
110
+ const client = createPublicClient({
111
+ chain: toViemChain(chain),
112
+ transport: http(chain.rpcUrl),
113
+ });
114
+ return (await client.readContract({
115
+ address: chain.usdc,
116
+ abi: erc20Abi,
117
+ functionName: "balanceOf",
118
+ args: [address],
119
+ }));
120
+ }
121
+ catch {
122
+ return undefined;
123
+ }
124
+ }
125
+ export async function runPay(argv, env = process.env, io = {}) {
126
+ const out = io.stdout ?? ((s) => console.log(s));
127
+ const err = io.stderr ?? ((s) => console.error(s));
128
+ const fetchImpl = io.fetchImpl ?? fetch;
129
+ let args;
130
+ try {
131
+ args = parseArgs(argv);
132
+ }
133
+ catch (e) {
134
+ err(`${e.message}\n\n${USAGE}`);
135
+ return EXIT_REFUSED;
136
+ }
137
+ if (args.help) {
138
+ out(USAGE);
139
+ return EXIT_OK;
140
+ }
141
+ if (!args.url) {
142
+ err(`missing <url>\n\n${USAGE}`);
143
+ return EXIT_REFUSED;
144
+ }
145
+ let caps;
146
+ try {
147
+ caps = toCaps(args, env);
148
+ }
149
+ catch (e) {
150
+ err(`${e.message}\n\n${USAGE}`);
151
+ return EXIT_REFUSED;
152
+ }
153
+ const init = {
154
+ method: args.method,
155
+ ...(args.body !== undefined ? { body: args.body } : {}),
156
+ };
157
+ let preflight;
158
+ try {
159
+ preflight = await fetchImpl(args.url, init);
160
+ }
161
+ catch (e) {
162
+ err(`transport error: ${e.message}`);
163
+ return EXIT_TRANSPORT;
164
+ }
165
+ if (preflight.status !== 402) {
166
+ out(`status ${preflight.status} — no payment required`);
167
+ return preflight.ok ? EXIT_OK : EXIT_TRANSPORT;
168
+ }
169
+ const pr = decode402((preflight.headers.get("payment-required") ??
170
+ (await preflight.clone().json().catch(() => undefined))));
171
+ const verdict = validateAccepts(pr, caps);
172
+ if (!verdict.ok) {
173
+ err(`refused field=${verdict.field} value=${JSON.stringify(verdict.value)}: ${verdict.reason}`);
174
+ return EXIT_REFUSED;
175
+ }
176
+ const req = verdict.requirements;
177
+ const chain = getChain(req.network);
178
+ err(`paying ${verdict.priceUsd} USDC to ${req.payTo} on ${chain?.name ?? req.network} (scheme ${req.scheme})`);
179
+ if (args.printOnly) {
180
+ out(JSON.stringify({
181
+ scheme: req.scheme,
182
+ network: req.network,
183
+ asset: req.asset,
184
+ amountAtomic: req.amount,
185
+ priceUsd: verdict.priceUsd,
186
+ payTo: req.payTo,
187
+ }, null, 2));
188
+ return EXIT_OK;
189
+ }
190
+ const key = env.AGENTBADGE_PAYER_KEY;
191
+ if (!key) {
192
+ err("AGENTBADGE_PAYER_KEY is not set — cannot sign payment");
193
+ return EXIT_REFUSED;
194
+ }
195
+ const account = privateKeyToAccount((key.startsWith("0x") ? key : `0x${key}`));
196
+ if (req.scheme === "gateway-batch" && !args.autoDeposit && chain) {
197
+ const gw = await gatewayBalance({
198
+ depositor: account.address,
199
+ chain,
200
+ fetchImpl,
201
+ });
202
+ const need = BigInt(req.amount);
203
+ if (gw && BigInt(gw.available ?? "0") < need) {
204
+ const eoa = await eoaUsdcBalance(chain, account.address);
205
+ const suggestion = eoa !== undefined && eoa >= need
206
+ ? `run: agentbadge gateway deposit --amount ${verdict.priceUsd} --network ${req.network}`
207
+ : `deposit USDC to GatewayWallet ${chain.gatewayWallet} on ${chain.name}`;
208
+ err(`gateway balance ${gw.available} < price ${req.amount} — ${suggestion}`);
209
+ return EXIT_REFUSED;
210
+ }
211
+ }
212
+ const signer = {
213
+ address: account.address,
214
+ signTypedData: (a) => account.signTypedData(a),
215
+ signMessage: (a) => account.signMessage(a),
216
+ writeContract: async (wcArgs) => {
217
+ if (!chain) {
218
+ throw new PaymentRefusedError("network", req.network, "unknown chain");
219
+ }
220
+ const wc = createWalletClient({
221
+ account,
222
+ chain: toViemChain(chain),
223
+ transport: http(chain.rpcUrl),
224
+ });
225
+ return wc.writeContract(wcArgs);
226
+ },
227
+ };
228
+ const client = createPayingClient({
229
+ caps,
230
+ signer,
231
+ fetch: fetchImpl,
232
+ ...(args.autoDeposit
233
+ ? { gateway: { autoDepositUsd: args.autoDeposit } }
234
+ : {}),
235
+ ...(args.riskCheck
236
+ ? {
237
+ beforePayment: createRiskGuard({
238
+ ...(env.AGENTBADGE_RISK_ENDPOINT
239
+ ? { endpoint: env.AGENTBADGE_RISK_ENDPOINT }
240
+ : {}),
241
+ fetchImpl,
242
+ }),
243
+ }
244
+ : {}),
245
+ });
246
+ try {
247
+ const res = await client.request(args.url, init);
248
+ const text = await res.text().catch(() => "");
249
+ out(`status ${res.status} spent=${client.spent()} atomic (${atomicToUsd(client.spent())} USDC of budget ${atomicToUsd(client.budget())})`);
250
+ if (text)
251
+ out(text);
252
+ return res.ok ? EXIT_OK : EXIT_TRANSPORT;
253
+ }
254
+ catch (e) {
255
+ if (e instanceof PaymentRefusedError ||
256
+ e instanceof CapExceededError ||
257
+ e instanceof BudgetExhaustedError ||
258
+ e instanceof PaymentNotAcceptedError ||
259
+ e instanceof TypeError) {
260
+ const named = e instanceof PaymentRefusedError
261
+ ? ` field=${e.field} value=${JSON.stringify(e.value)}`
262
+ : "";
263
+ err(`refused:${named} ${e.message}`);
264
+ return EXIT_REFUSED;
265
+ }
266
+ err(`transport error: ${e.message}`);
267
+ return EXIT_TRANSPORT;
268
+ }
269
+ }
270
+ const isMain = typeof process !== "undefined" &&
271
+ process.argv[1] !== undefined &&
272
+ import.meta.url === `file://${process.argv[1]}`;
273
+ if (isMain) {
274
+ runPay(process.argv.slice(2)).then((code) => process.exit(code));
275
+ }
@@ -42,5 +42,5 @@ export declare function gatewayBalance(args: {
42
42
  depositor: `0x${string}`;
43
43
  chain: SupportedChain;
44
44
  apiUrl?: string;
45
- fetchImpl?: typeof fetch;
45
+ fetchImpl?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
46
46
  }): Promise<GatewayBalanceInfo | null>;
@@ -3,7 +3,7 @@ export interface GatewayProbeOptions {
3
3
  probePath?: string;
4
4
  intervalMs?: number;
5
5
  downMs?: number;
6
- fetchImpl?: typeof fetch;
6
+ fetchImpl?: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
7
7
  onChange?: (up: boolean, reason: string) => void;
8
8
  }
9
9
  export interface GatewayProbe {
@@ -1,6 +1,8 @@
1
1
  import type { Hex } from "viem";
2
2
  import type { ReadClient, WriteClient } from "../escrow/erc8183.js";
3
3
  export declare const ERC8004_IDENTITY_REGISTRY: "0x8004A818BFB912233c491871b3d84c89A494BD9e";
4
+ export declare const ERC8004_IDENTITY_REGISTRY_ARC_MAINNET: "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432";
5
+ export declare function erc8004IdentityRegistry(chainId?: number): `0x${string}`;
4
6
  export declare const ERC8004_REPUTATION_REGISTRY: "0x8004B663056A597Dffe9eCcC1965A193B7388713";
5
7
  export declare const ERC8004_VALIDATION_REGISTRY: "0x8004Cb1BF31DAf7788923b405b754f57acEB4272";
6
8
  export declare const ERC8004_ABI: readonly [{
@@ -15,6 +17,21 @@ export declare const ERC8004_ABI: readonly [{
15
17
  readonly name: "agentId";
16
18
  readonly type: "uint256";
17
19
  }];
20
+ }, {
21
+ readonly type: "function";
22
+ readonly name: "transferFrom";
23
+ readonly stateMutability: "nonpayable";
24
+ readonly inputs: readonly [{
25
+ readonly name: "from";
26
+ readonly type: "address";
27
+ }, {
28
+ readonly name: "to";
29
+ readonly type: "address";
30
+ }, {
31
+ readonly name: "tokenId";
32
+ readonly type: "uint256";
33
+ }];
34
+ readonly outputs: readonly [];
18
35
  }, {
19
36
  readonly type: "function";
20
37
  readonly name: "ownerOf";
@@ -160,6 +177,7 @@ export declare class Erc8004Error extends Error {
160
177
  }
161
178
  export interface Erc8004Config {
162
179
  read: ReadClient;
180
+ chainId?: number;
163
181
  identity?: `0x${string}`;
164
182
  reputation?: `0x${string}`;
165
183
  validation?: `0x${string}`;
@@ -1,5 +1,11 @@
1
1
  import { decodeEventLog } from "viem";
2
2
  export const ERC8004_IDENTITY_REGISTRY = "0x8004A818BFB912233c491871b3d84c89A494BD9e";
3
+ export const ERC8004_IDENTITY_REGISTRY_ARC_MAINNET = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432";
4
+ export function erc8004IdentityRegistry(chainId) {
5
+ return chainId === 5042
6
+ ? ERC8004_IDENTITY_REGISTRY_ARC_MAINNET
7
+ : ERC8004_IDENTITY_REGISTRY;
8
+ }
3
9
  export const ERC8004_REPUTATION_REGISTRY = "0x8004B663056A597Dffe9eCcC1965A193B7388713";
4
10
  export const ERC8004_VALIDATION_REGISTRY = "0x8004Cb1BF31DAf7788923b405b754f57acEB4272";
5
11
  export const ERC8004_ABI = [
@@ -10,6 +16,17 @@ export const ERC8004_ABI = [
10
16
  inputs: [{ name: "metadataURI", type: "string" }],
11
17
  outputs: [{ name: "agentId", type: "uint256" }],
12
18
  },
19
+ {
20
+ type: "function",
21
+ name: "transferFrom",
22
+ stateMutability: "nonpayable",
23
+ inputs: [
24
+ { name: "from", type: "address" },
25
+ { name: "to", type: "address" },
26
+ { name: "tokenId", type: "uint256" },
27
+ ],
28
+ outputs: [],
29
+ },
13
30
  {
14
31
  type: "function",
15
32
  name: "ownerOf",
@@ -119,7 +136,7 @@ function extractAgentId(receipt) {
119
136
  throw new Erc8004Error("Transfer event not found in receipt", "register");
120
137
  }
121
138
  export function createErc8004(cfg) {
122
- const identity = cfg.identity ?? ERC8004_IDENTITY_REGISTRY;
139
+ const identity = cfg.identity ?? erc8004IdentityRegistry(cfg.chainId);
123
140
  const reputation = cfg.reputation ?? ERC8004_REPUTATION_REGISTRY;
124
141
  const validation = cfg.validation ?? ERC8004_VALIDATION_REGISTRY;
125
142
  return {
@@ -13,5 +13,6 @@ export interface PassportCheck {
13
13
  interface PaymentRequiredLike {
14
14
  extensions?: Record<string, unknown> | undefined;
15
15
  }
16
+ export declare function decode402(input: string | PaymentRequiredLike): PaymentRequiredLike | undefined;
16
17
  export declare function verifyPassport(paymentRequired: string | PaymentRequiredLike): PassportCheck;
17
18
  export {};
@@ -1,5 +1,5 @@
1
1
  const B64_RE = /^[A-Za-z0-9+/=]+$/;
2
- function decode402(input) {
2
+ export function decode402(input) {
3
3
  if (typeof input !== "string")
4
4
  return input;
5
5
  try {
package/dist/index.d.ts CHANGED
@@ -21,3 +21,15 @@ export * from "./identity/verify-passport.js";
21
21
  export * from "./memo/memo.js";
22
22
  export * from "./agent-wallet/index.js";
23
23
  export * from "./payer-bind.js";
24
+ export * from "./chain/index.js";
25
+ export * from "./signer/arc-signer.js";
26
+ export * from "./signer/env-key.js";
27
+ export * from "./signer/protocol.js";
28
+ export * from "./signer/socket.js";
29
+ export * from "./buyer/caps.js";
30
+ export * from "./buyer/session.js";
31
+ export * from "./buyer/accepts.js";
32
+ export * from "./buyer/client.js";
33
+ export * from "./buyer/guard.js";
34
+ export * from "./buyer/risk-guard.js";
35
+ export * from "./buyer/paginate.js";
package/dist/index.js CHANGED
@@ -21,3 +21,15 @@ export * from "./identity/verify-passport.js";
21
21
  export * from "./memo/memo.js";
22
22
  export * from "./agent-wallet/index.js";
23
23
  export * from "./payer-bind.js";
24
+ export * from "./chain/index.js";
25
+ export * from "./signer/arc-signer.js";
26
+ export * from "./signer/env-key.js";
27
+ export * from "./signer/protocol.js";
28
+ export * from "./signer/socket.js";
29
+ export * from "./buyer/caps.js";
30
+ export * from "./buyer/session.js";
31
+ export * from "./buyer/accepts.js";
32
+ export * from "./buyer/client.js";
33
+ export * from "./buyer/guard.js";
34
+ export * from "./buyer/risk-guard.js";
35
+ export * from "./buyer/paginate.js";
@@ -27,6 +27,17 @@ export interface RequirePaymentOptions extends PaymentRouterConfig {
27
27
  }) => Promise<void> | void;
28
28
  legacyHeader?: boolean;
29
29
  extraRequirements?: Record<string, unknown>;
30
+ onRailError?: (args: {
31
+ c: Context;
32
+ phase: "verify" | "settle";
33
+ rail: string;
34
+ scheme: string;
35
+ network: string;
36
+ path: string;
37
+ requestId?: string;
38
+ message: string;
39
+ error: unknown;
40
+ }) => void;
30
41
  }
31
42
  export interface PaymentInfo {
32
43
  payer?: string;
@@ -1,6 +1,25 @@
1
1
  import { recordFailure, } from "./ledger.js";
2
2
  import { classifyRail, createPaymentRouter, } from "./router.js";
3
3
  const b64encode = (o) => Buffer.from(JSON.stringify(o)).toString("base64");
4
+ function reportRailError(opts, c, phase, requirements, err) {
5
+ const message = err instanceof Error ? err.message : String(err);
6
+ const info = {
7
+ phase,
8
+ rail: classifyRail(requirements) ?? "unknown",
9
+ scheme: requirements.scheme,
10
+ network: requirements.network,
11
+ path: c.req.path,
12
+ requestId: typeof c.get("requestId") === "string"
13
+ ? c.get("requestId")
14
+ : undefined,
15
+ message,
16
+ };
17
+ if (opts.onRailError) {
18
+ opts.onRailError({ c, ...info, error: err });
19
+ return;
20
+ }
21
+ console.error(`[x402] rail error ${JSON.stringify(info)}`);
22
+ }
4
23
  function b64decode(s) {
5
24
  try {
6
25
  return JSON.parse(Buffer.from(s, "base64").toString("utf-8"));
@@ -110,7 +129,14 @@ export function requirePayment(price, opts) {
110
129
  return paymentRequired(c, accepts, opts, `Price $${priceUsd} exceeds declared X-Max-Amount "${maxHeader}"`);
111
130
  }
112
131
  }
113
- const verifyResult = await router.verify(paymentPayload, requirements);
132
+ let verifyResult;
133
+ try {
134
+ verifyResult = await router.verify(paymentPayload, requirements);
135
+ }
136
+ catch (err) {
137
+ reportRailError(opts, c, "verify", requirements, err);
138
+ return paymentRequired(c, accepts, opts, `verify_unavailable: ${err instanceof Error ? err.message : String(err)}`);
139
+ }
114
140
  if (!verifyResult.isValid) {
115
141
  return paymentRequired(c, accepts, opts, verifyResult.invalidReason ?? "Payment verification failed");
116
142
  }
@@ -124,7 +150,19 @@ export function requirePayment(price, opts) {
124
150
  if (deny instanceof Response)
125
151
  return deny;
126
152
  }
127
- const settleResult = await router.settle(paymentPayload, requirements);
153
+ let settleResult;
154
+ try {
155
+ settleResult = await router.settle(paymentPayload, requirements);
156
+ }
157
+ catch (err) {
158
+ reportRailError(opts, c, "settle", requirements, err);
159
+ await opts.onSettleResult?.({
160
+ c,
161
+ ok: false,
162
+ error: "settle_unavailable",
163
+ });
164
+ return paymentRequired(c, accepts, opts, `settle_unavailable: ${err instanceof Error ? err.message : String(err)}`);
165
+ }
128
166
  if (!settleResult.success) {
129
167
  await opts.onSettleResult?.({
130
168
  c,
@@ -0,0 +1,29 @@
1
+ import type { Hex } from "viem";
2
+ export interface SignerTxRequest {
3
+ to: `0x${string}`;
4
+ data: Hex;
5
+ value?: bigint;
6
+ }
7
+ export interface SignerWriteCall {
8
+ address: `0x${string}`;
9
+ abi: unknown;
10
+ functionName: string;
11
+ args: readonly unknown[];
12
+ }
13
+ export interface ArcSigner {
14
+ readonly address: `0x${string}`;
15
+ signMessage(message: string | {
16
+ raw: Hex;
17
+ }): Promise<Hex>;
18
+ signTypedData?(args: {
19
+ domain: Record<string, unknown>;
20
+ types: Record<string, unknown>;
21
+ primaryType: string;
22
+ message: Record<string, unknown>;
23
+ }): Promise<Hex>;
24
+ sendTransaction(tx: SignerTxRequest): Promise<Hex>;
25
+ }
26
+ export declare class SignerUnavailableError extends Error {
27
+ readonly operation: string;
28
+ constructor(operation: string, reason: string);
29
+ }
@@ -0,0 +1,8 @@
1
+ export class SignerUnavailableError extends Error {
2
+ operation;
3
+ constructor(operation, reason) {
4
+ super(`signer cannot ${operation}: ${reason}`);
5
+ this.operation = operation;
6
+ this.name = "SignerUnavailableError";
7
+ }
8
+ }
@@ -0,0 +1,20 @@
1
+ import { type Account, type Chain, type Hex } from "viem";
2
+ import { type ArcSigner, type SignerWriteCall } from "./arc-signer.js";
3
+ export interface EnvKeySignerOptions {
4
+ rpcUrl?: string;
5
+ chain?: Chain | null;
6
+ broadcast?: (tx: {
7
+ account: Account;
8
+ to: `0x${string}`;
9
+ data: Hex;
10
+ value?: bigint;
11
+ chain: Chain | null;
12
+ }) => Promise<Hex>;
13
+ }
14
+ export interface EnvKeySigner extends ArcSigner {
15
+ writeContract(call: SignerWriteCall): Promise<Hex>;
16
+ }
17
+ export declare function createEnvKeySigner(privateKey: `0x${string}`, opts?: EnvKeySignerOptions): EnvKeySigner;
18
+ export declare function arcSignerAsWriteClient(signer: ArcSigner): {
19
+ writeContract: (call: SignerWriteCall) => Promise<Hex>;
20
+ };
@@ -0,0 +1,58 @@
1
+ import { createWalletClient, encodeFunctionData, http, } from "viem";
2
+ import { privateKeyToAccount } from "viem/accounts";
3
+ import { SignerUnavailableError, } from "./arc-signer.js";
4
+ const KEY_RE = /^0x[0-9a-fA-F]{64}$/;
5
+ export function createEnvKeySigner(privateKey, opts = {}) {
6
+ if (!KEY_RE.test(privateKey)) {
7
+ throw new TypeError("createEnvKeySigner: expected 0x-prefixed 64-hex private key");
8
+ }
9
+ const account = privateKeyToAccount(privateKey);
10
+ const wallet = opts.rpcUrl && !opts.broadcast
11
+ ? createWalletClient({
12
+ account,
13
+ transport: http(opts.rpcUrl),
14
+ ...(opts.chain != null ? { chain: opts.chain } : {}),
15
+ })
16
+ : null;
17
+ const sendTransaction = async (tx) => {
18
+ const req = {
19
+ account,
20
+ to: tx.to,
21
+ data: tx.data,
22
+ ...(tx.value !== undefined ? { value: tx.value } : {}),
23
+ chain: opts.chain ?? null,
24
+ };
25
+ if (opts.broadcast)
26
+ return opts.broadcast(req);
27
+ if (!wallet) {
28
+ throw new SignerUnavailableError("sendTransaction", "no rpcUrl or broadcast bound to this signer");
29
+ }
30
+ return wallet.sendTransaction(req);
31
+ };
32
+ return {
33
+ address: account.address,
34
+ signMessage: (message) => account.signMessage(typeof message === "string" ? { message } : { message }),
35
+ signTypedData: (args) => account.signTypedData(args),
36
+ sendTransaction,
37
+ writeContract: (call) => sendTransaction({
38
+ to: call.address,
39
+ data: encodeFunctionData({
40
+ abi: call.abi,
41
+ functionName: call.functionName,
42
+ args: call.args,
43
+ }),
44
+ }),
45
+ };
46
+ }
47
+ export function arcSignerAsWriteClient(signer) {
48
+ return {
49
+ writeContract: (call) => signer.sendTransaction({
50
+ to: call.address,
51
+ data: encodeFunctionData({
52
+ abi: call.abi,
53
+ functionName: call.functionName,
54
+ args: call.args,
55
+ }),
56
+ }),
57
+ };
58
+ }
@@ -0,0 +1,46 @@
1
+ import type { Hex } from "viem";
2
+ import type { SignerTxRequest } from "./arc-signer.js";
3
+ export declare const SIGNER_METHODS: readonly ["getAddress", "health", "signMessage", "signTypedData", "sendTransaction"];
4
+ export type SignerMethod = (typeof SIGNER_METHODS)[number];
5
+ export interface SignerRpcRequest {
6
+ id: string;
7
+ method: SignerMethod;
8
+ params?: Record<string, unknown>;
9
+ }
10
+ export type SignerRpcResponse = {
11
+ id: string;
12
+ ok: true;
13
+ result: unknown;
14
+ } | {
15
+ id: string;
16
+ ok: false;
17
+ error: {
18
+ code: SignerErrorCode;
19
+ message: string;
20
+ };
21
+ };
22
+ export type SignerErrorCode = "policy_denied" | "unavailable" | "bad_request" | "internal";
23
+ export interface SignMessageParams {
24
+ message: string | {
25
+ raw: Hex;
26
+ };
27
+ }
28
+ export interface SignTypedDataParams {
29
+ domain: Record<string, unknown>;
30
+ types: Record<string, unknown>;
31
+ primaryType: string;
32
+ message: Record<string, unknown>;
33
+ }
34
+ export interface SendTransactionParams extends Omit<SignerTxRequest, "value"> {
35
+ value?: string;
36
+ }
37
+ export interface HealthResult {
38
+ status: "ok";
39
+ address: `0x${string}`;
40
+ uptimeSec: number;
41
+ chainId?: number;
42
+ }
43
+ export declare function encodeRpcLine(msg: SignerRpcRequest | SignerRpcResponse): string;
44
+ export declare function createLineDecoder<T = SignerRpcRequest | SignerRpcResponse>(): {
45
+ push(chunk: string): T[];
46
+ };